Create an ECS instance group and attach it to a CLB instance

更新时间:
复制 MD 格式

Learn how to edit a Resource Orchestration Service (ROS) template to create an Elastic Compute Service (ECS) instance group and attach it to a Classic Load Balancer (CLB) instance.

Prerequisites

Familiarize yourself with the template syntax and structure. For more information, see Quick Start.

Example scenario

Create an ECS instance group in a virtual private cloud (VPC), deploy an Nginx service within the instance group, and then attach the instance group to a CLB instance.

1

Usage notes

View the property details for each resource type. For more information, see View resource types.

Each resource type defines the type, requirements, and update policy for its properties. Required properties must be declared in the `Properties` section of the `Resources` block. Optional properties do not need to be declared. If a property allows updates, you can modify it in a new template and then update the stack to apply the changes. Otherwise, the property cannot be updated.

Edit the template

Find the required resource types in the resource type index. For more information, see Resource type index.

This scenario requires the following resources: a VPC (ALIYUN::ECS::VPC), an ECS instance group (ALIYUN::ECS::InstanceGroup), a Server Load Balancer (SLB) instance (ALIYUN::SLB::LoadBalancer), an SLB listener (ALIYUN::SLB::Listener), an elastic IP address (EIP) (ALIYUN::VPC::EIP), a vSwitch (ALIYUN::ECS::VSwitch), and a security group (ALIYUN::ECS::SecurityGroup). When you create the ECS instance group, you can use the UserData parameter of ALIYUN::ECS::InstanceGroup to run an initialization command. You can use a wait condition resource (ALIYUN::ROS::WaitCondition) and a wait condition handle resource (ALIYUN::ROS::WaitConditionHandle) to control the execution flow within the ECS instance group.

Define these resources in the Resources section of the template.

Define template resources and their dependencies

Define basic network resources

Define basic network resources such as Vpc, VSwitch, and EcsSecurityGroup.

  • Use the Ref function with the ALIYUN::StackName pseudo parameter to retrieve the stack name and use it as the value for a resource property. For example, this method is used for the VpcName property in the Vpc resource and the VSwitchName property in the VSwitch resource. For more information, see Functions and ALIYUN::StackName.

  • Use the Ref function to retrieve the return value of a specified resource. For example, `Ref: Vpc` in the VSwitch resource retrieves the VpcId return value of the Vpc resource. The return value is typically the resource ID. For more information, see Functions.

Resources:
  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:
        Ref: ZoneId
      CidrBlock: 192.168.0.0/24
  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      SecurityGroupIngress:
        - PortRange: 80/80
          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

Define the SLB instance and EIP resources

Define the SLB instance Slb, the SLB listener SlbListener, and the EIP resource EipSlbAddress.

The Fn::Sub function concatenates the ALIYUN::StackName pseudo parameter into a new string for use as a resource property value. For more information, see ALIYUN::StackName.

Resources:
  Slb:
    Type: ALIYUN::SLB::LoadBalancer
    Properties:
      VpcId:
        Ref: Vpc
      VSwitchId:
        Ref: VSwitch
      LoadBalancerName:
        Fn::Sub: slb-${ALIYUN::StackName}
      PayType:
        Ref: PayType
      PricingCycle:
        Ref: PayPeriodUnit
      Duration:
        Ref: PayPeriod
      AddressType: intranet
      LoadBalancerSpec:
        Ref: LoadBalancerSpec
      AutoPay: true
  SlbListener:
    DependsOn:
      - Slb
    Type: ALIYUN::SLB::Listener
    Properties:
      Persistence:
        CookieTimeout: 60
        StickySession: 'on'
        PersistenceTimeout: 180
        XForwardedFor: 'off'
        StickySessionType: insert
      ListenerPort: 80
      Bandwidth: -1
      HealthCheck:
        HttpCode: http_2xx,http_3xx,http_4xx,http_5xx
        HealthCheckType: tcp
        UnhealthyThreshold: 3
        Timeout: 5
        HealthyThreshold: 3
        Port: 80
        URI: /
        Interval: 2
      LoadBalancerId:
        Ref: Slb
      BackendServerPort: 80
      Protocol: tcp
  EipSlbAddress:
    Type: ALIYUN::VPC::EIP
    Properties:
      Name:
        Ref: ALIYUN::StackName
      InternetChargeType: PayByTraffic
      Bandwidth:
        Ref: Bandwidth

Define the ECS instance group, wait condition resource, and wait condition handle resource

Define the ECS instance group EcsInstanceGroup, the wait condition resource WaitCondition, and the wait condition handle resource WaitConditionHandle.

  • Use the Fn::GetAtt function to retrieve the value of an attribute from a resource in the template. For example, you can retrieve the CurlCli return value of the WaitConditionHandle resource. For more information, see Functions.

  • Use the Fn::Sub function to construct a command string and substitute variables in an input string with specified values. For example, in the UserData property of the EcsInstanceGroup resource, ${CurlCli} is replaced by the value of CurlCli. For more information, see Functions.

  • The following combination of resources controls the initialization process within the ECS instances.

    1. Create a wait condition resource (ALIYUN::ROS::WaitCondition).

    2. Create a wait condition handle resource (ALIYUN::ROS::WaitConditionHandle).

    3. In the UserData of the ECS instance, run a script and send a signal. For example, the UserData content in the EcsInstanceGroup resource contains an initialization script for the ECS instance. After the script runs successfully, it sends a callback to the WaitConditionHandle resource. This ends the wait state of the WaitCondition resource.

Resources:
  WaitCondition:
    Type: ALIYUN::ROS::WaitCondition
    Properties:
      Count: 1
      Handle:
        Ref: WaitConditionHandle
      Timeout: 300
  WaitConditionHandle:
    Type: ALIYUN::ROS::WaitConditionHandle
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InstanceChargeType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
      IoOptimized: optimized
      SystemDiskCategory:
        Ref: SystemDiskCategory
      SystemDiskSize:
        Ref: SystemDiskSize
      DiskMappings:
        - Category:
            Ref: DataDiskCategory
          Size:
            Ref: DataDiskSize
      VpcId:
        Ref: Vpc
      SecurityGroupId:
        Ref: EcsSecurityGroup
      VSwitchId:
        Ref: VSwitch
      MaxAmount: 2
      ImageId: centos_7
      InstanceType:
        Ref: EcsInstanceType
      Password:
        Ref: InstancePassword
      AllocatePublicIP: false
      UserData:
        Fn::Sub:
          - |
            #!/bin/bash
            # Mount the disk to /disk1
            cat >> /root/InitDataDisk.sh << EOF
            #!/bin/bash
            echo "p
            n
            p
            w
            " |  fdisk -u /dev/vdb
            EOF
            /bin/bash /root/InitDataDisk.sh
            rm -f /root/InitDataDisk.sh
            rm -f InitDataDisk.sh
            mkfs -t ext4 /dev/vdb1
            cp /etc/fstab /etc/fstab.bak
            mkdir /disk1
            echo `blkid /dev/vdb1 | awk '{print $2}' | sed 's/\\\"//g'` /disk1 ext4 defaults 0 0 >> /etc/fstab
            mount -a
            # Configure the installation script
            yum install -y nginx
            # Configure the startup script
            systemctl start nginx.service
            # Send a success signal to WaitConditionHandle to end the wait of WaitCondition.
            ${CurlCli} -d "{\"Data\" : \"Success\", \"status\" : \"SUCCESS\"}"
          - CurlCli:
              Fn::GetAtt:
                - WaitConditionHandle
                - CurlCli
      

Define dependencies for the ECS instance group, SLB instance, and backend server attachment

Define the ECS instance group EcsInstanceGroup, the SLB instance Slb, and the backend server attachment SlbBackendServerAttachment.

  • Use SlbBackendServerAttachment to attach the ECS instance group to the CLB instance. For more information, see ALIYUN::SLB::BackendServerAttachment.

    In ALIYUN::SLB::BackendServerAttachment, if you do not specify a value for BackendServerWeightList, the weight of all ECS instances in BackendServerList defaults to 100. If BackendServerWeightList contains fewer entries than BackendServerList, the last weight value in BackendServerWeightList is applied to all remaining ECS instances in BackendServerList.

  • Use the DependsOn property to specify that a resource is created only after another resource is created. For more information, see DependsOn.

  • Use the Fn::GetAtt function to retrieve the value of a resource's output property. For example, you can retrieve the InstanceIds from the EcsInstanceGroup resource. For more information, see Functions.

Resources:
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InstanceChargeType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
      IoOptimized: optimized
      SystemDiskCategory:
        Ref: SystemDiskCategory
      SystemDiskSize:
        Ref: SystemDiskSize
      DiskMappings:
        - Category:
            Ref: DataDiskCategory
          Size:
            Ref: DataDiskSize
      VpcId:
        Ref: Vpc
      SecurityGroupId:
        Ref: EcsSecurityGroup
      VSwitchId:
        Ref: VSwitch
      MaxAmount: 2
      ImageId: centos_7
      InstanceType:
        Ref: EcsInstanceType
      Password:
        Ref: InstancePassword
      AllocatePublicIP: false
  Slb:
    Type: ALIYUN::SLB::LoadBalancer
    Properties:
      VpcId:
        Ref: Vpc
      VSwitchId:
        Ref: VSwitch
      LoadBalancerName:
        Fn::Sub: slb-${ALIYUN::StackName}
      PayType:
        Ref: PayType
      PricingCycle:
        Ref: PayPeriodUnit
      Duration:
        Ref: PayPeriod
      AddressType: intranet
      LoadBalancerSpec:
        Ref: LoadBalancerSpec
      AutoPay: true
  SlbBackendServerAttachment:
    DependsOn:
      - EcsInstanceGroup
      - Slb
    Type: ALIYUN::SLB::BackendServerAttachment
    Properties:
      BackendServerList:
        Fn::GetAtt:
          - EcsInstanceGroup
          - InstanceIds
      LoadBalancerId:
        Ref: Slb
      BackendServerWeightList:
        - 100
        - 50

Complete sample template

ROSTemplateFormatVersion: '2015-09-01'
Description:
  en: Create a new VPC and vSwitch, create one CLB instance, two ECS instances, and attach all ECS instances to the CLB instance.
  zh-cn: Create a new VPC and vSwitch, create one CLB instance, two ECS instances, and attach all ECS instances to the CLB instance.
Parameters:
  ZoneId:
    Type: String
    AssociationProperty: ALIYUN::ECS::Instance::ZoneId
    Label:
      en: vSwitch Zone
      zh-cn: vSwitch Zone
  VpcCidrBlock:
    Default: 192.168.0.0/16
    Label:
      zh-cn: VPC CIDR Block
      en: VPC CIDR Block
    Type: String
    Description:
      zh-cn: The CIDR block for the new VPC. The following CIDR blocks are recommended<font color='green'>[10.0.0.0/8]</font><br><font color='green'>[172.16.0.0/12]</font><br><font color='green'>[192.168.0.0/16]</font>
      en: The CIDR block for the new VPC. The following CIDR blocks are recommended<br><font color='green'>[10.0.0.0/8]</font><br><font color='green'>[172.16.0.0/12]</font><br><font color='green'>[192.168.0.0/16]</font>
  VSwitchCidrBlock:
    Default: 192.168.0.0/24
    Type: String
    Description:
      zh-cn: Must be a subnet of the VPC and not used by other vSwitches.
      en: Must be a subnet of the VPC and not used by other vSwitches.
    Label:
      zh-cn: vSwitch CIDR Block
      en: vSwitch CIDR Block
  EcsInstanceType:
    Type: String
    Label:
      en: Instance Type
      zh-cn: Instance Type
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceChargeType: ${InstanceChargeType}
  SystemDiskCategory:
    Type: String
    Description:
      en: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]<br>[ephemeral_ssd: <font color=''green''>local SSD</font>]'
      zh-cn: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]<br>[ephemeral_ssd: <font color=''green''>local SSD</font>]'
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Label:
      en: System Disk Type
      zh-cn: System Disk Type
  SystemDiskSize:
    Default: 40
    Type: Number
    Description:
      zh-cn: The size of the system disk. Valid values: 40 to 500. Unit: GB.
    Label:
      zh-cn: System Disk Size
      en: System Disk Size
  DataDiskCategory:
    AssociationProperty: ALIYUN::ECS::Disk::DataDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Type: String
    Description:
      zh-cn: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]'
      en: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]'
    Label:
      zh-cn: Data Disk Type
      en: Data Disk Type
  DataDiskSize:
    Description:
      zh-cn: The size of the data disk for the ECS instance. Unit: GiB. Valid values: 20 to 32768.
    Default: 100
    MaxValue: 32768
    MinValue: 20
    Label:
      zh-cn: Data Disk Size
      en: Data Disk Size
    Type: Number
  InstancePassword:
    NoEcho: true
    Type: String
    Description:
      en: The logon password for the server. The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
      zh-cn: The logon password for the server. The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
    AllowedPattern: '[0-9A-Za-z\_\-\&:;''<>,=%`~!@#\(\)\$\^\*\+\|\{\}\[\]\.\?\/]+$'
    Label:
      en: Instance Password
      zh-cn: Instance Password
    ConstraintDescription:
      en: The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
      zh-cn: The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
    MinLength: 8
    MaxLength: 30
    AssociationProperty: ALIYUN::ECS::Instance::Password
  PayType:
    Type: String
    Label:
      en: Billing Method
      zh-cn: Billing Method
    Default: PostPaid
    AllowedValues:
      - PostPaid
      - PrePaid
    AssociationProperty: ChargeType
    AssociationPropertyMetadata:
      LocaleKey: InstanceChargeType
  PayPeriodUnit:
    Type: String
    Description:
      en: The subscription duration unit. Valid values: Week and Month. The default value is Month.<br><b><font color='red'>This parameter is valid only when the billing method is Subscription.</font>
      zh-cn: The subscription duration unit. Valid values: Week and Month. The default value is Month.<b><font color='red'>This parameter is valid only when the billing method is Subscription.</font>
    Label:
      en: Subscription Duration Unit
      zh-cn: Subscription Duration Unit
    Default: Month
    AllowedValues:
      - Month
      - Year
    AssociationProperty: PayPeriodUnit
    AssociationPropertyMetadata:
      Visible:
        Condition:
          Fn::Not:
            Fn::Equals:
              - ${PayType}
              - PostPaid
  PayPeriod:
    Type: Number
    Label:
      en: Subscription Duration
      zh-cn: Subscription Duration
    Default: 1
    AllowedValues:
      - 1
      - 2
      - 3
      - 4
      - 5
      - 6
      - 7
      - 8
      - 9
    AssociationProperty: PayPeriod
    AssociationPropertyMetadata:
      Visible:
        Condition:
          Fn::Not:
            Fn::Equals:
              - ${PayType}
              - PostPaid
  LoadBalancerSpec:
    Type: String
    AssociationProperty: ALIYUN::SLB::Instance::InstanceType
    Label:
      en: SLB Instance Edition
      zh-cn: SLB Instance Edition
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
  Bandwidth:
    Description:
      zh-cn: Valid values: 0 to 1000. Unit: Mbps.
      en: 'Valid values: 0 to 1000. Unit: Mbps.'
    Default: 10
    MaxValue: 1000
    Label:
      zh-cn: EIP Bandwidth for SLB
      en: EIP Bandwidth for SLB
    MinValue: 1
    Type: Number
Resources:
  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: ZoneId
      CidrBlock:
        Ref: VSwitchCidrBlock
  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      SecurityGroupIngress:
        - PortRange: 80/80
          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
  WaitCondition:
    Type: ALIYUN::ROS::WaitCondition
    Properties:
      Count: 1
      Handle:
        Ref: WaitConditionHandle
      Timeout: 300
  WaitConditionHandle:
    Type: ALIYUN::ROS::WaitConditionHandle
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InstanceChargeType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
      IoOptimized: optimized
      SystemDiskCategory:
        Ref: SystemDiskCategory
      SystemDiskSize:
        Ref: SystemDiskSize
      DiskMappings:
        - Category:
            Ref: DataDiskCategory
          Size:
            Ref: DataDiskSize
      VpcId:
        Ref: Vpc
      SecurityGroupId:
        Ref: EcsSecurityGroup
      VSwitchId:
        Ref: VSwitch
      MaxAmount: 2
      ImageId: centos_7
      InstanceType:
        Ref: EcsInstanceType
      Password:
        Ref: InstancePassword
      AllocatePublicIP: false
      UserData:
        Fn::Sub:
          - |
            #!/bin/bash
            # Mount the disk to /disk1
            cat >> /root/InitDataDisk.sh << EOF
            #!/bin/bash
            echo "p
            n
            p
            w
            " |  fdisk -u /dev/vdb
            EOF
            /bin/bash /root/InitDataDisk.sh
            rm -f /root/InitDataDisk.sh
            rm -f InitDataDisk.sh
            mkfs -t ext4 /dev/vdb1
            cp /etc/fstab /etc/fstab.bak
            mkdir /disk1
            echo `blkid /dev/vdb1 | awk '{print $2}' | sed 's/\\\"//g'` /disk1 ext4 defaults 0 0 >> /etc/fstab
            mount -a
            # Configure the installation script
            yum install -y nginx
            # Configure the startup script
            systemctl start nginx.service
            # Send a success signal to WaitConditionHandle to end the wait of WaitCondition.
            ${CurlCli} -d "{\"Data\" : \"Success\", \"status\" : \"SUCCESS\"}"
          - CurlCli:
              Fn::GetAtt:
                - WaitConditionHandle
                - CurlCli
  Slb:
    Type: ALIYUN::SLB::LoadBalancer
    Properties:
      VpcId:
        Ref: Vpc
      VSwitchId:
        Ref: VSwitch
      LoadBalancerName:
        Fn::Sub: slb-${ALIYUN::StackName}
      PayType:
        Ref: PayType
      PricingCycle:
        Ref: PayPeriodUnit
      Duration:
        Ref: PayPeriod
      AddressType: intranet
      LoadBalancerSpec:
        Ref: LoadBalancerSpec
      AutoPay: true
  EipSlbAddress:
    Type: ALIYUN::VPC::EIP
    Properties:
      Name:
        Ref: ALIYUN::StackName
      InternetChargeType: PayByTraffic
      Bandwidth:
        Ref: Bandwidth
  EipSlbAddressAssociation:
    Type: ALIYUN::VPC::EIPAssociation
    Properties:
      InstanceId:
        Ref: Slb
      AllocationId:
        Ref: EipSlbAddress
  SlbBackendServerAttachment:
    DependsOn:
      - EcsInstanceGroup
    Type: ALIYUN::SLB::BackendServerAttachment
    Properties:
      BackendServerList:
        Fn::GetAtt:
          - EcsInstanceGroup
          - InstanceIds
      LoadBalancerId:
        Ref: Slb
      BackendServerWeightList:
        - 100
        - 100
  SlbListener:
    DependsOn:
      - Slb
    Type: ALIYUN::SLB::Listener
    Properties:
      Persistence:
        CookieTimeout: 60
        StickySession: 'on'
        PersistenceTimeout: 180
        XForwardedFor: 'off'
        StickySessionType: insert
      ListenerPort: 80
      Bandwidth: -1
      HealthCheck:
        HttpCode: http_2xx,http_3xx,http_4xx,http_5xx
        HealthCheckType: tcp
        UnhealthyThreshold: 3
        Timeout: 5
        HealthyThreshold: 3
        Port: 80
        URI: /
        Interval: 2
      LoadBalancerId:
        Ref: Slb
      BackendServerPort: 80
      Protocol: tcp
Outputs:
  Endpoint:
    Description:
      zh-cn: The public IP address.
      en: The public IP address.
    Value:
      Fn::Sub:
        - http://${ServerAddress}
        - ServerAddress:
            Fn::GetAtt:
              - EipSlbAddress
              - EipAddress

Add parameter groups and dynamically obtain parameter configurations

The EcsInstanceGroup resource's InstanceType and SystemDiskCategory properties and the Slb resource's LoadBalancerSpec property reference parameters. When you create stacks in different regions, you must provide different values for these properties for each deployment.

Add a Parameters section to the template to make it more flexible and reusable.

Add parameter groups

Use the Metadata section to group the parameters defined in the Parameters section and define labels for the parameter groups.

After you define the template resources and parameters, group the parameters based on their corresponding resources.

The following table shows how to group the resources for this example.

Parameter category

Resource name

Parameter name

Basic network configuration

Vpc, VSwitch, EcsSecurityGroup

ZoneId, VpcCidrBlock, VSwitchCidrBlock

SLB configuration

Slb, EipSlbAddress

LoadBalancerSpec, Bandwidth

ECS configuration

EcsInstanceGroup

PayType, PayPeriodUnit, PayPeriod, ECSInstanceType, ECSDiskSize, ECSDiskCategory, ECSInstancePassword

Dynamically obtain parameter configurations

Take EcsInstanceType as an example. To set filter conditions and dynamically select a configuration in the ROS console, find its supported AssociationProperty value. Based on the resource type ALIYUN::ECS::InstanceGroup, the value is ALIYUN::ECS::Instance::InstanceType. Then, query the AssociationPropertyMetadata values using filter conditions such as ZoneId and InstanceChargeType. For more information, see AssociationProperty and AssociationPropertyMetadata.

Complete sample template

ROSTemplateFormatVersion: '2015-09-01'
Description:
  en: Create one CLB instance and two ECS instances in a VPC and vSwitch, and attach all ECS instances to the CLB instance.
  zh-cn: Create one CLB instance and two ECS instances in a VPC and vSwitch, and attach all ECS instances to the CLB instance.
Parameters:
  ZoneId:
    Type: String
    AssociationProperty: ALIYUN::ECS::Instance::ZoneId
    Label:
      en: vSwitch Zone
      zh-cn: vSwitch Zone
  VpcCidrBlock:
    Default: 192.168.0.0/16
    Label:
      zh-cn: VPC CIDR Block
      en: VPC CIDR Block
    Type: String
    Description:
      zh-cn: The CIDR block for the new VPC. The following CIDR blocks are recommended<font color='green'>[10.0.0.0/8]</font><br><font color='green'>[172.16.0.0/12]</font><br><font color='green'>[192.168.0.0/16]</font>
      en: The CIDR block for the new VPC. The following CIDR blocks are recommended<br><font color='green'>[10.0.0.0/8]</font><br><font color='green'>[172.16.0.0/12]</font><br><font color='green'>[192.168.0.0/16]</font>
  VSwitchCidrBlock:
    Default: 192.168.0.0/24
    Type: String
    Description:
      zh-cn: Must be a subnet of the VPC and not used by other vSwitches.
      en: Must be a subnet of the VPC and not used by other vSwitches.
    Label:
      zh-cn: vSwitch CIDR Block
      en: vSwitch CIDR Block
  EcsInstanceType:
    Type: String
    Label:
      en: Instance Type
      zh-cn: Instance Type
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceChargeType: ${InstanceChargeType}
  SystemDiskCategory:
    Type: String
    Description:
      en: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]<br>[ephemeral_ssd: <font color=''green''>local SSD</font>]'
      zh-cn: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]<br>[ephemeral_ssd: <font color=''green''>local SSD</font>]'
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Label:
      en: System Disk Type
      zh-cn: System Disk Type
  SystemDiskSize:
    Default: 40
    Type: Number
    Description:
      zh-cn: 'The size of the system disk. Valid values: 40 to 500. Unit: GB.'
      en: 'The size of the system disk. Valid values: 40 to 500. Unit: GB.'
    Label:
      zh-cn: System Disk Size
      en: System Disk Size
  DataDiskCategory:
    AssociationProperty: ALIYUN::ECS::Disk::DataDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Type: String
    Description:
      zh-cn: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]'
      en: '<font color=''blue''><b>Valid values:</font>[cloud_efficiency: <font color=''green''>ultra disk</font>]<br>[cloud_ssd: <font color=''green''>standard SSD</font>]<br>[cloud_essd: <font color=''green''>enterprise SSD</font>]<br>[cloud: <font color=''green''>basic disk</font>]'
    Label:
      zh-cn: Data Disk Type
      en: Data Disk Type
  DataDiskSize:
    Description:
      zh-cn: 'The size of the data disk for the ECS instance. Unit: GiB. Valid values: 20 to 32768.'
      en: 'The size of the data disk for the ECS instance. Unit: GiB. Valid values: 20 to 32768.'
    Default: 100
    MaxValue: 32768
    MinValue: 20
    Label:
      zh-cn: Data Disk Size
      en: Data Disk Size
    Type: Number
  InstancePassword:
    NoEcho: true
    Type: String
    Description:
      en: The logon password for the server. The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
      zh-cn: The logon password for the server. The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
    AllowedPattern: '[0-9A-Za-z\_\-\&:;''<>,=%`~!@#\(\)\$\^\*\+\|\{\}\[\]\.\?\/]+$'
    Label:
      en: Instance Password
      zh-cn: Instance Password
    ConstraintDescription:
      en: The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
      zh-cn: The password 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 from the following set: ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/.
    MinLength: 8
    MaxLength: 30
    AssociationProperty: ALIYUN::ECS::Instance::Password
  PayType:
    Type: String
    Label:
      en: Billing Method
      zh-cn: Billing Method
    Default: PostPaid
    AllowedValues:
      - PostPaid
      - PrePaid
    AssociationProperty: ChargeType
    AssociationPropertyMetadata:
      LocaleKey: InstanceChargeType
  PayPeriodUnit:
    Type: String
    Description:
      en: The subscription duration unit. Valid values: Week and Month. The default value is Month.<br><b><font color='red'>This parameter is valid only when the billing method is Subscription.</font>
      zh-cn: The subscription duration unit. Valid values: Week and Month. The default value is Month.<b><font color='red'>This parameter is valid only when the billing method is Subscription.</font>
    Label:
      en: Subscription Duration Unit
      zh-cn: Subscription Duration Unit
    Default: Month
    AllowedValues:
      - Month
      - Year
    AssociationProperty: PayPeriodUnit
    AssociationPropertyMetadata:
      Visible:
        Condition:
          Fn::Not:
            Fn::Equals:
              - ${PayType}
              - PostPaid
  PayPeriod:
    Type: Number
    Label:
      en: Subscription Duration
      zh-cn: Subscription Duration
    Default: 1
    AllowedValues:
      - 1
      - 2
      - 3
      - 4
      - 5
      - 6
      - 7
      - 8
      - 9
    AssociationProperty: PayPeriod
    AssociationPropertyMetadata:
      Visible:
        Condition:
          Fn::Not:
            Fn::Equals:
              - ${PayType}
              - PostPaid
  LoadBalancerSpec:
    Type: String
    AssociationProperty: ALIYUN::SLB::Instance::InstanceType
    Label:
      en: SLB Instance Edition
      zh-cn: SLB Instance Edition
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
  Bandwidth:
    Description:
      zh-cn: 'Valid values: 0 to 1000. Unit: Mbps.'
      en: 'Valid values: 0 to 1000. Unit: Mbps.'
    Default: 10
    MaxValue: 1000
    Label:
      zh-cn: EIP Bandwidth for SLB
      en: EIP Bandwidth for SLB
    MinValue: 1
    Type: Number
Resources:
  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: ZoneId
      CidrBlock:
        Ref: VSwitchCidrBlock
  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: Vpc
      SecurityGroupIngress:
        - PortRange: 80/80
          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
  WaitCondition:
    Type: ALIYUN::ROS::WaitCondition
    Properties:
      Count: 1
      Handle:
        Ref: WaitConditionHandle
      Timeout: 300
  WaitConditionHandle:
    Type: ALIYUN::ROS::WaitConditionHandle
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InstanceChargeType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
      IoOptimized: optimized
      SystemDiskCategory:
        Ref: SystemDiskCategory
      SystemDiskSize:
        Ref: SystemDiskSize
      DiskMappings:
        - Category:
            Ref: DataDiskCategory
          Size:
            Ref: DataDiskSize
      VpcId:
        Ref: Vpc
      SecurityGroupId:
        Ref: EcsSecurityGroup
      VSwitchId:
        Ref: VSwitch
      MaxAmount: 2
      ImageId: centos_7
      InstanceType:
        Ref: EcsInstanceType
      Password:
        Ref: InstancePassword
      AllocatePublicIP: false
      UserData:
        Fn::Sub:
          - |
            #!/bin/bash
            # Mount the disk to /disk1
            cat >> /root/InitDataDisk.sh << EOF
            #!/bin/bash
            echo "p
            n
            p
            w
            " |  fdisk -u /dev/vdb
            EOF
            /bin/bash /root/InitDataDisk.sh
            rm -f /root/InitDataDisk.sh
            rm -f InitDataDisk.sh
            mkfs -t ext4 /dev/vdb1
            cp /etc/fstab /etc/fstab.bak
            mkdir /disk1
            echo `blkid /dev/vdb1 | awk '{print $2}' | sed 's/\\\"//g'` /disk1 ext4 defaults 0 0 >> /etc/fstab
            mount -a
            # Configure the installation script
            yum install -y nginx
            # Configure the startup script
            systemctl start nginx.service
            # Send a success signal to WaitConditionHandle to end the wait of WaitCondition.
            ${CurlCli} -d "{\"Data\" : \"Success\", \"status\" : \"SUCCESS\"}"
          - CurlCli:
              Fn::GetAtt:
                - WaitConditionHandle
                - CurlCli
  Slb:
    Type: ALIYUN::SLB::LoadBalancer
    Properties:
      VpcId:
        Ref: Vpc
      VSwitchId:
        Ref: VSwitch
      LoadBalancerName:
        Fn::Sub: slb-${ALIYUN::StackName}
      PayType:
        Ref: PayType
      PricingCycle:
        Ref: PayPeriodUnit
      Duration:
        Ref: PayPeriod
      AddressType: intranet
      LoadBalancerSpec:
        Ref: LoadBalancerSpec
      AutoPay: true
  EipSlbAddress:
    Type: ALIYUN::VPC::EIP
    Properties:
      Name:
        Ref: ALIYUN::StackName
      InternetChargeType: PayByTraffic
      Bandwidth:
        Ref: Bandwidth
  EipSlbAddressAssociation:
    Type: ALIYUN::VPC::EIPAssociation
    Properties:
      InstanceId:
        Ref: Slb
      AllocationId:
        Ref: EipSlbAddress
  SlbBackendServerAttachment:
    DependsOn:
      - EcsInstanceGroup
    Type: ALIYUN::SLB::BackendServerAttachment
    Properties:
      BackendServerList:
        Fn::GetAtt:
          - EcsInstanceGroup
          - InstanceIds
      LoadBalancerId:
        Ref: Slb
      BackendServerWeightList:
        - 100
        - 50
  SlbListener:
    DependsOn:
      - Slb
    Type: ALIYUN::SLB::Listener
    Properties:
      Persistence:
        CookieTimeout: 60
        StickySession: 'on'
        PersistenceTimeout: 180
        XForwardedFor: 'off'
        StickySessionType: insert
      ListenerPort: 80
      Bandwidth: -1
      HealthCheck:
        HttpCode: http_2xx,http_3xx,http_4xx,http_5xx
        HealthCheckType: tcp
        UnhealthyThreshold: 3
        Timeout: 5
        HealthyThreshold: 3
        Port: 80
        URI: /
        Interval: 2
      LoadBalancerId:
        Ref: Slb
      BackendServerPort: 80
      Protocol: tcp
Outputs:
  Endpoint:
    Description:
      zh-cn: The public IP address
      en: The public IP address
    Value:
      Fn::Sub:
        - http://${ServerAddress}
        - ServerAddress:
            Fn::GetAtt:
              - EipSlbAddress
              - EipAddress
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - ZoneId
          - VpcCidrBlock
          - VSwitchCidrBlock
        Label:
          default:
            zh-cn: Basic Network Configuration
            en: Basic Network Configuration
      - Parameters:
          - PayType
          - PayPeriodUnit
          - PayPeriod
        Label:
          default:
            en: Billing Method Configuration
            zh-cn: Billing Method Configuration
      - Parameters:
          - EcsInstanceType
          - SystemDiskCategory
          - SystemDiskSize
          - DataDiskCategory
          - DataDiskSize
          - InstancePassword
        Label:
          default:
            en: ECS Instance Configuration
            zh-cn: ECS Instance Configuration
      - Parameters:
          - LoadBalancerSpec
          - Bandwidth
        Label:
          default:
            en: SLB Configuration
            zh-cn: SLB Configuration