All Products
Search
Document Center

Resource Orchestration Service:Deploy an auto-scaling ECS cluster with ROS

Last Updated:Sep 15, 2026

Use Alibaba Cloud Resource Orchestration Service (ROS) to provision a VPC network, a group of ECS instances, and an Auto Scaling (ESS) group from a single YAML template. Add the ECS instances to the scaling group so it can scale out or scale in automatically based on business load. This tutorial suits scenarios that require elastic management of server clusters, such as web applications and microservices.

Solution overview

Business scenario

Batch-create ECS instances in an Alibaba Cloud Virtual Private Cloud (VPC) and add them to a scaling group. After you configure scaling rules, the scaling group increases or decreases the number of ECS instances based on business load, which gives you elastic management of server clusters.

Resources created

No.

Resource name

ROS resource type

Purpose

1

VPC

ALIYUN::ECS::VPC

Provides an isolated network environment.

2

VSwitch

ALIYUN::ECS::VSwitch

Allocates a subnet CIDR block and specifies the zone in the VPC.

3

SecurityGroup

ALIYUN::ECS::SecurityGroup

Controls inbound and outbound network access rules for the ECS instances.

4

ECS InstanceGroup

ALIYUN::ECS::InstanceGroup

Batch-creates the initial ECS instances.

5

ScalingGroup

ALIYUN::ESS::ScalingGroup

Manages the elastic scaling policy (minimum and maximum instance counts).

6

ScalingConfiguration

ALIYUN::ESS::ScalingConfiguration

Defines the ECS specification template used during scale-out.

7

ScalingGroupEnable

ALIYUN::ESS::ScalingGroupEnable

Enables the scaling group and adds the existing ECS instances to it.

Expected results after deployment

After the template deploys successfully, you will have:

  • A complete VPC network environment that includes the VPC, VSwitch, and security group.

  • A group of ECS instances. (The count is parameterized by ECSInstanceGroupCount, default 3.)

  • An enabled scaling group with a scaling configuration for automatic scale-out.

  • All ECS instances added to the scaling group.

Architecture Diagram

使用伸缩组管理多台云服务器-架构图

Prerequisites

Before you start, confirm the following:

  1. Account and permissions: An Alibaba Cloud account that has permissions to create resources in ECS, ESS (Elastic Scaling), and VPC.

  2. Knowledge preparation: Basic knowledge of ROS template syntax and structure. For details, see Quick start for templates.

Template writing tutorial

This tutorial demonstrates the template writing process in two phases:

  • Phase 1 (basic version): uses fixed parameter values and focuses on understanding resource definitions and dependencies.

  • Phase 2 (advanced version): parameterizes all variable configurations and adds dynamic parameter filtering and parameter grouping.

Phase 1: Basic template — define resources and their dependencies

Step 1: Define the basic network resources (VPC + VSwitch + Security group)

Network resources are the foundation for all other resources and must be created first.

Resources:
  # ============================================================
  # Basic network layer: VPC → VSwitch → SecurityGroup
  # ============================================================
  
  Vpc:
    Type: ALIYUN::ECS::VPC  # Create the VPC
    Properties:
      CidrBlock: 192.168.0.0/16  # VPC CIDR block, which provides 65,534 private IP addresses
      VpcName:
        Ref: ALIYUN::StackName  # Pseudo parameter: uses the stack name as the VPC name

  VSwitch:
    Type: ALIYUN::ECS::VSwitch  # Create a VSwitch (subnet) in the VPC
    Properties:
      VSwitchName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc  # Ref returns the VpcId of Vpc (an implicit dependency, so ROS creates Vpc first)
      ZoneId: cn-beijing-h # This scenario uses zone H in the China (Beijing) region as an example
      CidrBlock: 192.168.0.0/24  # Subnet CIDR block, which must be a subset of the VPC CIDR block

  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup  # Create the security group
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc  # Bind the security group to the same VPC
      # Inbound rule: this example allows all inbound traffic for simplicity. Restrict the ports as needed in production.
      SecurityGroupIngress:
        - PortRange: '-1/-1'
          Priority: 1
          IpProtocol: all
          SourceCidrIp: 0.0.0.0/0
          NicType: intranet

Key points:

  • Custom settings such as VpcName, VSwitchName, and SecurityGroupName can be configured with pseudo parameters, which lets you quickly find the resources deployed by a specific stack after deployment.

  • The access rules of SecurityGroup can be customized based on your business requirements. For example:

    • To access a web service from the Internet, open inbound port HTTP 80 or 8080 in the security group.

    • To log on to the servers over SSH, open inbound port 22 in the security group.

Step 2: Define the ECS instance group resource

ALIYUN::ECS::InstanceGroup creates multiple ECS instances with the same configuration at a time, which is more efficient than declaring ALIYUN::ECS::Instance multiple times.

Resources:
  # ============================================================
  # Compute layer: batch-create ECS instances
  # ============================================================

  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup  # Batch-create ECS instances
    Properties:
      VpcId:
        Ref: Vpc
      SecurityGroupId:
        Ref: EcsSecurityGroup
      VSwitchId:
        Ref: VSwitch
      ImageId: centos_7_9_x64_20G_alibase_20220727.vhd  # CentOS 7.9 image
      AllocatePublicIP: false  # Do not allocate a public IP address
      InstanceType: ecs.c5.large  # Instance type: 2 vCPUs, 4 GiB
      SystemDiskSize: 200  # 200 GiB system disk
      SystemDiskCategory: cloud_essd  # ESSD cloud disk
      MaxAmount: 3  # Create 3 ECS instances
      Password: <YourPassword>  # Replace with an actual password at deployment time (must contain uppercase letters, lowercase letters, digits, and special characters)
      InstanceName:  # Instance name: stack name plus a sequence number, such as mystack-0001
        Fn::Sub:
           - ${StackName}-[1,4]
           - StackName:
               Ref: ALIYUN::StackName

Key points:

  • ALIYUN::ECS::InstanceGroup uses the MaxAmount property to specify the number of ECS instances to create.

  • The Fn::Sub function concatenates strings. [1,4] is a sequence-number placeholder specific to ROS. It indicates a 4-digit number that increments from 1, such as 0001 and 0002.

  • The output attribute InstanceIds of this resource is a list of ECS instance IDs, which can be referenced by the scaling group.

Step 3: Define the scaling group resources (Scaling group+Scaling configuration+Enable scaling configuration)

A scaling group works through three resources: ScalingGroup defines the scaling policy, ScalingConfiguration defines the ECS template used during scale-out, and ScalingGroupEnable enables the scaling group and adds the existing instances to it.

Resources:
  # ============================================================
  # Auto Scaling layer: scaling group + scaling configuration + enable scaling group
  # ============================================================
  
  EssInstanceScalingGroup:
    Type: ALIYUN::ESS::ScalingGroup  # Create the scaling group
    Properties:
      ScalingGroupName:
        Ref: ALIYUN::StackName
      RemovalPolicys:
        - NewestInstance  # Scale-in policy: removes the most recently created instances first
      MinSize: 3  # The scaling group keeps at least 3 instances
      MaxSize: 50  # The scaling group can scale out to at most 50 instances
      VSwitchId:
        Ref: VSwitch  # Bind the scaling group to the VSwitch (determines the network location of instances added during scale-out)
      DefaultCooldown: 300  # A cooldown period of 300 seconds prevents frequent scaling

  EssInstanceScalingConfiguration:
    Type: ALIYUN::ESS::ScalingConfiguration  # Scaling configuration (the ECS template used during scale-out)
    Properties:
      SecurityGroupId:
        Ref: EcsSecurityGroup
      ScalingGroupId:
        Ref: EssInstanceScalingGroup  # Associate with the scaling group defined above
      ScalingConfigurationName:
        Fn::Sub: sc-${ALIYUN::StackName}  # Fn::Sub substitutes the pseudo parameter variable directly
      InstanceType: ecs.c5.large  # ECS instance type created during scale-out (should match the initial ECS instances)
      SystemDiskCategory: cloud_essd
      SystemDiskSize: 200
      ImageId: centos_7_9_x64_20G_alibase_20220727.vhd  # Image used during scale-out (should match the initial ECS instances)

  EssInstanceScalingGroupEnable:
    Type: ALIYUN::ESS::ScalingGroupEnable  # Enable the scaling group
    Properties:
      ScalingRuleArisExecuteVersion: '1'
      ScalingConfigurationId:
        Ref: EssInstanceScalingConfiguration  # Specify the scaling configuration to take effect
      InstanceIds:
        # Add the ECS instances created in Step 2 to the scaling group
        Fn::GetAtt:
          - EcsInstanceGroup
          - InstanceIds  # Obtain the list of all instance IDs of InstanceGroup
      ScalingGroupId:
        Ref: EssInstanceScalingGroup

Key points:

  • Set MinSize of the scaling group to the same value as ECSInstanceGroupCount (the number of instances created initially) to prevent scale-in from being triggered immediately after the group is enabled.

  • You can add a scaling rule (ALIYUN::ESS::ScalingRule) and an alarm task (ALIYUN::ESS::AlarmTask) to the scaling group to implement auto-scaling based on metrics such as CPU utilization and memory usage.

  • The difference between Ref and Fn::GetAtt:

    • Ref returns the primary identifier of a resource, such as the VpcId of a VPC.

    • Fn::GetAtt returns a related attribute of a resource, such as the InstanceIds of EcsInstanceGroup.

Basic version — complete template

The following is the complete, ready-to-use template that combines the three preceding steps:

ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: 创建VPC网络环境,批量部署ECS实例并加入伸缩组,实现弹性扩缩容管理
  en: Create VPC network, deploy ECS instance group and manage them with ESS scaling group

Resources:
  # === basic network layer ===
  Vpc:
    Type: ALIYUN::ECS::VPC
    Properties:
      CidrBlock: 192.168.0.0/16
      VpcName:
        Ref: ALIYUN::StackName

  VSwitch:
    Type: ALIYUN::ECS::VSwitch
    Properties:
      VSwitchName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      ZoneId: cn-beijing-h
      CidrBlock: 192.168.0.0/24

  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      SecurityGroupIngress:
        - PortRange: '-1/-1'
          Priority: 1
          IpProtocol: all
          SourceCidrIp: 0.0.0.0/0
          NicType: intranet

  # === Computing layer ===
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      VpcId:
        Ref: Vpc
      SecurityGroupId:
        Ref: EcsSecurityGroup
      VSwitchId:
        Ref: VSwitch
      ImageId: centos_7_9_x64_20G_alibase_20220727.vhd
      AllocatePublicIP: false
      InstanceType: ecs.c5.large
      SystemDiskSize: 200
      SystemDiskCategory: cloud_essd
      MaxAmount: 3
      Password: <YourPassword>  
      InstanceName:
        Fn::Sub:
           - ${StackName}-[1,4]
           - StackName:
               Ref: ALIYUN::StackName

  # === ESS layer ===
  EssInstanceScalingGroup:
    Type: ALIYUN::ESS::ScalingGroup
    Properties:
      ScalingGroupName:
        Ref: ALIYUN::StackName
      RemovalPolicys:
        - NewestInstance
      MinSize: 3
      MaxSize: 50
      VSwitchId:
        Ref: VSwitch
      DefaultCooldown: 300

  EssInstanceScalingConfiguration:
    Type: ALIYUN::ESS::ScalingConfiguration
    Properties:
      SecurityGroupId:
        Ref: EcsSecurityGroup
      ScalingGroupId:
        Ref: EssInstanceScalingGroup
      ScalingConfigurationName:
        Fn::Sub: sc-${ALIYUN::StackName}
      InstanceType: ecs.c5.large
      SystemDiskCategory: cloud_essd
      SystemDiskSize: 200
      ImageId: centos_7_9_x64_20G_alibase_20220727.vhd

  EssInstanceScalingGroupEnable:
    Type: ALIYUN::ESS::ScalingGroupEnable
    Properties:
      ScalingRuleArisExecuteVersion: '1'
      ScalingConfigurationId:
        Ref: EssInstanceScalingConfiguration
      InstanceIds:
        Fn::GetAtt:
          - EcsInstanceGroup
          - InstanceIds
      ScalingGroupId:
        Ref: EssInstanceScalingGroup

Outputs:
  ECSInstanceIds:
    Label: ECS instance ID list
    Value:
      Fn::GetAtt:
        - EcsInstanceGroup
        - InstanceIds

Key points:

  • After the template creates the resources, you can query the internal attributes of those resources directly from the Outputs of the template, such as the list of ECS instance IDs.

Phase 2: Advanced template — parameterization and dynamic configuration

In the basic template, properties such as InstanceType, SystemDiskCategory, and ImageId of the ECS instances and MaxSize of the scaling group use fixed values. To reuse the template in a different region or with different specifications, you must modify the template repeatedly. In addition, parameters in a template often depend on each other. For example, the ECS instance type is limited by the zone (different zones have different instance type inventories), and the system disk category is limited by both the zone and the instance type. If you specify these parameters manually, you can easily select an unavailable combination, which causes the deployment to fail.

The following optimizations greatly improve the flexibility and reusability of the template:

  • Parameterization (Parameters): extract variable configurations as parameters and specify them dynamically at deployment time.

  • Dynamic parameter filtering (AssociationProperty): let the ROS console automatically filter the available options based on the parameters that are already selected.

  • Parameter grouping (Metadata): display parameters in logical groups in the console to improve the input experience.

Parameter dependency diagram

The following example uses the ECS instance type and the system disk category to show the dependency chain between parameters:

VSwitchZoneId (zone)  ← base parameter, no prerequisite
    ├──→ ECSInstanceType (ECS instance type)
    │             Depends on: ZoneId
    │
    └──→ ECSDiskCategory (system disk category)
                  Depends on: ZoneId + InstanceType

Core logic: select the zone first, then filter the ECS instance types available in that zone, and finally filter the disk categories supported by the selected zone and instance type. Each step shows only the options that are valid under the current conditions, which prevents invalid combinations.

AssociationProperty explained

1. VSwitchZoneId — zone (base parameter)

Set AssociationProperty to ALIYUN::ECS::ZoneId to list all zones in the current region. Example:

VSwitchZoneId:
    Type: String
    Label:
      zh-cn: 交换机可用区
      en: VSwitch Availability Zone
    Description:
      zh-cn: 选择交换机所在的可用区,ECS和伸缩组将部署在此可用区
      en: Select the availability zone for VSwitch, ECS and scaling group will be deployed here
    AssociationProperty: ALIYUN::ECS::ZoneId

This parameter is the filtering basis for all subsequent parameters. After you select a zone, the option lists of the other parameters are updated accordingly.

2. ECSInstanceType — ECS instance type

Set AssociationProperty to ALIYUN::ECS::Instance::InstanceType to list the available ECS instance types, and associate ${VSwitchZoneId} to filter the instance types available in the selected zone. Example:

ECSInstanceType:
    Type: String
    Label:
      zh-cn: ECS实例规格
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${VSwitchZoneId}

Instance type inventory differs by zone. Without filtering, you might select a type that is out of stock in the zone, which causes creation to fail.

3. ECSDiskCategory — system disk category

Set AssociationProperty to ALIYUN::ECS::Disk::SystemDiskCategory to list the available system disk categories, and associate ${VSwitchZoneId} and ${ECSInstanceType} to filter the system disk categories supported by the selected zone and ECS instance type. Example:

ECSDiskCategory:
    Type: String
    Label:
      zh-cn: 系统盘类型
      en: System Disk Category
    Description:
      zh-cn: 选择系统盘类型。可选值:cloud_essd(ESSD云盘)、cloud_ssd(SSD云盘)、cloud_efficiency(高效云盘)
      en: "System disk type. Options: cloud_essd, cloud_ssd, cloud_efficiency"
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${VSwitchZoneId}
      InstanceType: ${ECSInstanceType}

The availability of a system disk category depends on both the zone (some zones do not support ESSD) and the instance type (some types support only specific disk categories).

Dynamic parameter filtering example

The following example shows the effect of configuring AssociationProperty to dynamically obtain ECS instance types and disk categories:

Parameters:
  VSwitchZoneId:
    Type: String
    Label:
      zh-cn: 交换机可用区
      en: VSwitch Availability Zone
    Description:
      zh-cn: 选择交换机所在的可用区,ECS和伸缩组将部署在此可用区
      en: Select the availability zone for VSwitch, ECS and scaling group will be deployed here
    AssociationProperty: ALIYUN::ECS::ZoneId
  ECSInstanceType:
    Type: String
    Label:
      zh-cn: ECS实例规格
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${VSwitchZoneId}
  ECSDiskCategory:
    Type: String
    Label:
      zh-cn: 系统盘类型
      en: System Disk Category
    Description:
      zh-cn: 选择系统盘类型。可选值:cloud_essd(ESSD云盘)、cloud_ssd(SSD云盘)、cloud_efficiency(高效云盘)
      en: "System disk type. Options: cloud_essd, cloud_ssd, cloud_efficiency"
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${VSwitchZoneId}
      InstanceType: ${ECSInstanceType}

How AssociationProperty works

When creates a stack in the ROS console, parameter selection is triggered in a cascade:

  1. Select a zone (VSwitchZoneId).

  2. The ECS instance type drop-down list refreshes automatically and shows only the instance types that are in stock in that zone.

  3. After you select an ECS instance type, the system disk category drop-down list refreshes automatically and shows only the disk categories supported by both that zone and that instance type.

In this way, each step shows only the options that are available under the current conditions, which prevents deployment failures caused by invalid parameter combinations.

Metadata parameter groups

By configuring ALIYUN::ROS::Interface in Metadata, you can divide parameters into logical groups, each with a heading. The console displays the parameters by group, which greatly improves the input experience.

Metadata syntax structure
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:           # List of parameter groups (required)
      - Parameters:            # List of parameter names in the group (required)
          - Parameter1
          - Parameter2
        Label:                 # Group heading (required)
          default:
            zh-cn: 中文标题
            en: English Title

Metadata syntax rules:

  • ParameterGroups, Parameters, and Label are all required.

  • The parameter names listed in Parameters must exactly match the parameter names defined in the Parameters section of the template.

  • Parameters that do not appear in any group are displayed in an ungrouped area in the console.

Parameter group design

This template divides nine parameters into three groups by resource type:

┌────────────────────────────────────────────────────┐
│  Network configuration                             │
│  ├── VSwitch zone (VSwitchZoneId)                  │
│  ├── VPC CIDR block (VpcCidrBlock)                 │
│  └── VSwitch CIDR block (VSwitchCidrBlock)         │
├────────────────────────────────────────────────────┤
│  ECS instance configuration                        │
│  ├── ECS instance type (ECSInstanceType)           │
│  ├── ECS image ID (ECSImageId)                     │
│  ├── System disk category (ECSDiskCategory)        │
│  ├── ECS instance password (EcsInstancePassword)   │
│  └── ECS instance count (ECSInstanceGroupCount)    │
├────────────────────────────────────────────────────┤
│  ESS scaling group configuration                   │
│  └── Maximum instance count (ESSGroupMaxSize)      │
└────────────────────────────────────────────────────┘
Metadata grouping example
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - VSwitchZoneId
          - VpcCidrBlock
          - VSwitchCidrBlock
        Label:
          default:
            zh-cn: 基础网络配置
            en: Network Configuration
      - Parameters:
          - ECSInstanceType
          - ECSDiskCategory
          - ECSImageId
          - EcsInstancePassword
          - ECSInstanceGroupCount
        Label:
          default:
            zh-cn: ECS实例配置
            en: ECS Instance Configuration
      - Parameters:
          - ESSGroupMaxSize
        Label:
          default:
            zh-cn: ESS伸缩组配置
            en: Scaling Group Configuration

Advanced version — complete template

ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: >-
    参数化模板:批量创建ECS实例并通过弹性伸缩组管理,支持自动扩缩容。
    支持动态选择可用区、实例规格、磁盘类型和镜像,适用于多地域复用。
  en: >-
    Parameterized template: Create ECS instance group managed by ESS scaling group.
    Supports dynamic selection of zone, instance type, disk category and image.

Parameters:
  # ─── basic network parameters ───
  VSwitchZoneId:
    Type: String
    Label:
      zh-cn: 交换机可用区
      en: VSwitch Availability Zone
    Description:
      zh-cn: 选择交换机所在的可用区,ECS和伸缩组将部署在此可用区
      en: Select the availability zone for VSwitch, ECS and scaling group will be deployed here
    AssociationProperty: ALIYUN::ECS::ZoneId

  VpcCidrBlock:
    Type: String
    Label:
      zh-cn: VPC网段
      en: VPC CIDR Block
    Description:
      zh-cn: VPC的IP地址段范围。推荐使用 10.0.0.0/8、172.16.0.0/12 或 192.168.0.0/16
      en: VPC IP address range. Recommended 10.0.0.0/8, 172.16.0.0/12, or 192.168.0.0/16
    Default: 192.168.0.0/16

  VSwitchCidrBlock:
    Type: String
    Label:
      zh-cn: 交换机网段
      en: VSwitch CIDR Block
    Description:
      zh-cn: 必须是VPC网段的子网段,且不能与同VPC下其他交换机网段重叠
      en: Must be a subnet of VPC CIDR and not overlap with other VSwitches
    Default: 192.168.0.0/24

  # ─── ECS instance parameters ───
  ECSInstanceType:
    Type: String
    Label:
      zh-cn: ECS实例规格
      en: ECS Instance Type
    Description:
      zh-cn: 选择ECS实例规格。列表已根据可用区自动过滤可用规格。
      en: Select ECS instance type. List is filtered by selected availability zone.
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${VSwitchZoneId}

  ECSDiskCategory:
    Type: String
    Label:
      zh-cn: 系统盘类型
      en: System Disk Category
    Description:
      zh-cn: 选择系统盘类型。可选值:cloud_essd(ESSD云盘)、cloud_ssd(SSD云盘)、cloud_efficiency(高效云盘)
      en: "System disk type. Options: cloud_essd, cloud_ssd, cloud_efficiency"
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${VSwitchZoneId}
      InstanceType: ${ECSInstanceType}

  ECSImageId:
    Type: String
    Label:
      zh-cn: ECS镜像ID
      en: Image ID
    Description:
      zh-cn: 选择ECS实例使用的操作系统镜像
      en: Select the OS image for ECS instances
    AssociationProperty: ALIYUN::ECS::Image::ImageId

  ECSInstanceGroupCount:
    Type: Number
    Label:
      zh-cn: ECS初始实例数量
      en: Initial Instance Count
    Description:
      zh-cn: 初始创建的ECS实例数量,这些实例将加入伸缩组管理
      en: Number of ECS instances to create initially, they will be added to scaling group
    Default: 3

  EcsInstancePassword:
    Type: String
    NoEcho: true
    Label:
      zh-cn: ECS实例密码
      en: ECS Instance Password
    Description:
      zh-cn: 长度8-30位,需包含大写字母、小写字母、数字、特殊字符中的至少三种
      en: Length 8-30, must contain at least three of uppercase, lowercase, digits, special characters
    MinLength: 8
    MaxLength: 30
    AssociationProperty: ALIYUN::ECS::Instance::Password

  # ─── scaling group parameters ───
  ESSGroupMaxSize:
    Type: Number
    Label:
      zh-cn: 伸缩组最大实例数
      en: Scaling Group Max Size
    Description:
      zh-cn: 伸缩组内ECS实例的最大数量,达到此上限后不再自动扩容
      en: Maximum number of ECS instances in scaling group
    Default: 50

Resources:
  # === basic network layer ===
  Vpc:
    Type: ALIYUN::ECS::VPC
    Properties:
      CidrBlock:
        Ref: VpcCidrBlock
      VpcName:
        Ref: ALIYUN::StackName

  VSwitch:
    Type: ALIYUN::ECS::VSwitch
    Properties:
      VSwitchName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      ZoneId:
        Ref: VSwitchZoneId
      CidrBlock:
        Ref: VSwitchCidrBlock

  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      SecurityGroupIngress:
        - PortRange: 8080/8080
          Priority: 1
          SourceCidrIp: 0.0.0.0/0
          IpProtocol: tcp
          NicType: internet
      SecurityGroupEgress:
        - PortRange: '-1/-1'
          Priority: 1
          IpProtocol: all
          DestCidrIp: 0.0.0.0/0
          NicType: internet
        - PortRange: '-1/-1'
          Priority: 1
          IpProtocol: all
          DestCidrIp: 0.0.0.0/0
          NicType: intranet

  # === Computing layer ===
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InstanceName:
        Fn::Sub:
           - ${StackName}-[1,4]
           - StackName:
               Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      VSwitchId:
        Ref: VSwitch
      SecurityGroupId:
        Ref: EcsSecurityGroup
      SystemDiskCategory:
        Ref: ECSDiskCategory
      SystemDiskSize: 200
      MaxAmount:
        Ref: ECSInstanceGroupCount
      ImageId:
        Ref: ECSImageId
      InstanceType:
        Ref: ECSInstanceType
      Password:
        Ref: EcsInstancePassword
      AllocatePublicIP: false

  # === ESS layer ===
  EssInstanceScalingGroup:
    Type: ALIYUN::ESS::ScalingGroup
    Properties:
      ScalingGroupName:
        Ref: ALIYUN::StackName
      RemovalPolicys:
        - NewestInstance
      MinSize:
        Ref: ECSInstanceGroupCount
      MaxSize:
        Ref: ESSGroupMaxSize
      VSwitchId:
        Ref: VSwitch
      DefaultCooldown: 300

  EssInstanceScalingConfiguration:
    Type: ALIYUN::ESS::ScalingConfiguration
    Properties:
      SecurityGroupId:
        Ref: EcsSecurityGroup
      ScalingGroupId:
        Ref: EssInstanceScalingGroup
      ScalingConfigurationName:
        Fn::Sub: sc-${ALIYUN::StackName}
      InstanceType:
        Ref: ECSInstanceType
      SystemDiskCategory:
        Ref: ECSDiskCategory
      SystemDiskSize: 200
      ImageId:
        Ref: ECSImageId
      InstanceName:
        Fn::Sub:
           - ${StackName}-[index,1,4]
           - StackName:
               Ref: ALIYUN::StackName

  EssInstanceScalingGroupEnable:
    Type: ALIYUN::ESS::ScalingGroupEnable
    Properties:
      ScalingRuleArisExecuteVersion: '1'
      ScalingConfigurationId:
        Ref: EssInstanceScalingConfiguration
      InstanceIds:
        Fn::GetAtt:
          - EcsInstanceGroup
          - InstanceIds
      ScalingGroupId:
        Ref: EssInstanceScalingGroup

Outputs:
  ECSInstanceIds:
    Label: ECS 实例 ID 列表
    Value:
      Fn::GetAtt:
        - EcsInstanceGroup
        - InstanceIds

# === Metadata ===
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - VSwitchZoneId
          - VpcCidrBlock
          - VSwitchCidrBlock
        Label:
          default:
            zh-cn: 基础网络配置
            en: Network Configuration
      - Parameters:
          - ECSInstanceType
          - ECSDiskCategory
          - ECSImageId
          - EcsInstancePassword
          - ECSInstanceGroupCount
        Label:
          default:
            zh-cn: ECS实例配置
            en: ECS Instance Configuration
      - Parameters:
          - ESSGroupMaxSize
        Label:
          default:
            zh-cn: 伸缩组配置
            en: Scaling Group Configuration

Quick reference for the ROS built-in functions used in this template

Function

Syntax example

Usage in this template

Description

Ref

Ref: MyVpc

Reference a parameter value or the primary identifier of a resource.

Referencing a parameter returns its value; referencing a resource returns its primary identifier.

Fn::GetAtt

Fn::GetAtt: [EcsInstanceGroup, InstanceIds]

Obtain the instance ID list of the ECS instance group.

Obtains an output attribute of a resource after creation (not the primary identifier).

Fn::Sub

Fn::Sub: sc-${ALIYUN::StackName}

Concatenate the scaling configuration name.

Use ${Var} in a template string to reference a variable or a pseudo parameter.

Deployment

Deployment parameters

Required parameters (must be specified at deployment time)

Parameter

Description

Constraint

VSwitchZoneId

Zone ID.

Dynamically selected in the console.

ECSInstanceType

ECS instance type.

Available instance types are filtered automatically based on the zone.

ECSDiskCategory

ECS system disk category.

Filtered automatically based on the zone and the instance type.

ECSImageId

ECS image ID.

Dynamically selected in the console.

Optional parameters (have default values and can be left empty)

Parameter

Default value

Description

VpcCidrBlock

192.168.0.0/16

CIDR block of the VPC.

VSwitchCidrBlock

192.168.0.0/24

CIDR block of the VSwitch subnet.

ECSInstanceGroupCount

3

Number of ECS instances created initially.

ESSGroupMaxSize

50

Maximum number of instances in the ESS scaling group.

EcsInstancePassword

None

Logon password of the ECS instances. It must be 8 to 30 characters in length and contain at least three of the following character types: uppercase letters, lowercase letters, digits, and special characters.

Deployment methods

Method 1: Deploy through the ROS console

  1. Log in to the ROS console.

  2. In the left-side navigation pane, choose Stacks > Create Stack.

  3. Select Select an Existing Template > Enter Template Content and paste the complete template into the editor.

  4. Click Next, and configure parameters by group.

  5. After confirming the configuration, click Create and wait for the stack status to change to CREATE_COMPLETE.

Method 2: Deploy through ROS IaC code

IaC Code is an AI infrastructure-as-code assistant for cloud infrastructure. It helps cloud resource users and O&M engineers generate, deploy, and manage infrastructure templates through a terminal workflow.

# Prompt
Deploy a group of ECS instances and manage them with an Auto Scaling group. Requirements:
1. Use a newly created VPC and VSwitch.
2. Create 3 ECS instances initially and add them to the scaling group.
3. Set the maximum number of instances in the scaling group to 50 and the minimum number to 3.
4. Set the scale-in policy to remove the newest instances first.
5. Open inbound port 8080 in the security group.
6. Configure VSwitchZoneId, ECSInstanceType, ECSDiskCategory, and ECSImageId with AssociationProperty so that they are dynamically filtered in the console.

FAQ

Q1: Deployment fails with "The specified InstanceType is not available in the zone"

Cause: the selected ECS instance type is out of stock in the specified zone.

Solution:

  • In the advanced template, AssociationProperty automatically filters the available instance types, which avoids this issue.

  • If you use the basic template, go to Elastic Compute Service (ECS) pricing to check the instance type inventory in the target zone, or select another zone.

Q2: The scaling group triggers scale-in immediately after enabling

Cause: the MinSize value is greater than the number of instances that actually joined the group, or the instances failed to join.

Solution:

  1. Make sure that the value of ECSInstanceGroupCount is greater than or equal to the MinSize of the scaling group.

  2. Check whether the ECS instances are in the Running state.

  3. Confirm that the instances and the scaling group are in the same VPC or VSwitch.

Q3: Newly created ECS instances during scale-out have unexpected configuration

Cause: the configurations in ScalingConfiguration, such as InstanceType and ImageId, are inconsistent with the configurations of the initial ECS instances.

Solution:

  • In the advanced template, the parameters of ScalingConfiguration, such as InstanceType and ImageId, already reference the same parameters as EcsInstanceGroup, which keeps the scale-out configuration consistent.

  • If you need to scale out with different configurations, create multiple ScalingConfiguration resources and control their proportions by weight.

Q4: How do I implement auto-scaling based on CPU utilization?

Solution: add a scaling rule and an alarm task to the template:

# Scale-out rule: adds 2 instances each time
ScaleOutRule:
  Type: ALIYUN::ESS::ScalingRule
  Properties:
    ScalingGroupId:
      Ref: EssInstanceScalingGroup
    ScalingRuleName: scale-out-2
    ScalingRuleType: SimpleScalingRule
    AdjustmentType: QuantityChangeInCapacity  # Adjust by quantity
    AdjustmentValue: 2  # Add 2 instances each time

# Alarm trigger: triggers scale-out when CPU utilization exceeds 80%
CpuAlarm:
  Type: ALIYUN::ESS::AlarmTask
  Properties:
    AlarmTaskName: cpu-high-alarm
    ScalingGroupId:
      Ref: EssInstanceScalingGroup
    MetricName: CpuUtilization
    Threshold: 80
    ComparisonOperator: '>='
    EvaluationCount: 3  # Triggers only after 3 consecutive samples exceed the threshold
    AlarmActions:
      - Fn::GetAtt:
          - ScaleOutRule
          - ScalingRuleAri

Q5: How do I use an existing VPC instead of creating a new one?

Solution: remove the VPC and VSwitch from Resources and pass them in through Parameters:

Parameters:
  ExistingVpcId:
    Type: String
    Label:
      en: Existing VPC ID
    AssociationProperty: ALIYUN::ECS::VPC::VPCId
  ExistingVSwitchId:
    Type: String
    Label:
      en: Existing VSwitch ID
    AssociationProperty: ALIYUN::VPC::VSwitch::VSwitchId
    AssociationPropertyMetadata:
      VpcId: ${ExistingVpcId}

Q6: How do I attach an SLB to the scaling group for traffic distribution?

Solution: add LoadBalancerIds to the Properties of ScalingGroup:

EssInstanceScalingGroup:
  Type: ALIYUN::ESS::ScalingGroup
  Properties:
    ScalingGroupName:
      Ref: ALIYUN::StackName
    RemovalPolicys:
      - NewestInstance
    MinSize:
      Ref: ECSInstanceGroupCount
    MaxSize:
      Ref: ESSGroupMaxSize
    VSwitchId:
      Ref: VSwitch
    DefaultCooldown: 300
    LoadBalancerIds:
      - Ref: MyLoadBalancer  # References an existing SLB instance

When the scaling group adds or removes instances, the instances are automatically added to or removed from the SLB backend server group.