创建ECS实例组并挂载到CLB实例

本文以创建ECS实例组并挂载到传统型负载均衡(CLB)实例为例,由简入难的向您介绍如何编辑ROS模板。

前提条件

请您提前了解模板语法和结构。更多信息,请参见模板快速入门

场景示例

在阿里云专有网络中创建ECS实例组,并在ECS实例组中部署Nginx服务,然后将创建的ECS实例组挂载到CLB实例上。

1

使用须知

您可以访问对应的资源类型查看属性详情。具体操作,请参见查看资源类型

资源类型为每个属性定义了类型、是否必须、是否允许更新等信息。如果为必须,则要求必须在模板Resources的Properties中声明该属性;反之,则为非必须。如果为允许更新,则可以在新模板中修改该属性,然后使用修改后的模板更新资源栈以达到更新云资源属性的目的;反之,则不允许更新。

编辑模板

您可以通过资源类型索引文档查找所需的资源类型。更多信息,请参见资源类型索引

例如:当前场景中需要创建专有网络(ALIYUN::ECS::VPC)、ECS实例组(ALIYUN::ECS::InstanceGroup)、负载均衡实例(ALIYUN::SLB::LoadBalancer)、负载均衡监听(ALIYUN::SLB::Listener)、弹性公网IP(ALIYUN::VPC::EIP),交换机(ALIYUN::ECS::VSwitch)、安全组(ALIYUN::ECS::InstanceGroup)。在创建ECS实例组时,需要使用ALIYUN::ECS::InstanceGroup中的UserData参数执行数据初始化命令,并使用等待信号的资源(ALIYUN::ROS::WaitCondition)和接受信号的资源(ALIYUN::ROS::WaitConditionHandle)控制ECS实例组内部的执行流程。

根据以上信息,您可以在模板中定义需要创建的资源(Resources)。

定义模板资源及其依赖关系

定义基础网络资源

您可以通过模板定义基础网络资源VpcVSwitchEcsSecurityGroup

  • 使用Ref与伪参数ALIYUN::StackName获取资源栈名称作为资源属性的属性值。例如:Vpc中的VpcNameVSwitch中的VSwitchName。更多信息,请参见函数(Functions)ALIYUN::StackName

  • 使用Ref获取返回指定参数的值。例如:VSwitch中的Ref: Vpc,获取的是Vpc资源的返回值VpcId。一般返回指定参数的值都为资源ID。更多信息,请参见函数(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

定义负载均衡实例和弹性公网资源

您可以通过模板定义负载均衡实例Slb、负载均衡监听SlbListener和弹性公网IP资源EipSlbAddress

使用Fn::Sub与伪参数ALIYUN::StackName获取资源栈名称进行拼接成新的字符串作为资源属性的属性值。更多信息,请参见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

定义ECS实例、等待信号资源和接收信号资源

您可以通过模板定义ECS实例组EcsInstanceGroup、等待信号资源WaitCondition和接收信号资源WaitConditionHandle

  • 使用Fn::GetAtt函数获取返回模板中资源的属性值。例如:WaitConditionHandle的返回值CurlCli。更多信息,请参见函数(Functions)

  • 使用Fn::Sub函数用于拼接命令操作字符串及将输入字符串中的变量替换为您指定的值。例如:EcsInstanceGroup中的UserData,使用CurlCli替换${CurlCli}。更多信息,请参见函数(Functions)

  • 控制ECS实例内部初始化的资源组合如下。

    1. 创建一个等待信号资源(ALIYUN::ROS::WaitCondition)。

    2. 创建一个接收信号资源(ALIYUN::ROS::WaitConditionHandle)。

    3. 在ECS内部UserData中执行脚本并发送信息。例如:EcsInstanceGroup中的UserData内容,UserData中可以传入ECS的初始化脚本,最后执行成功回调WaitConditionHandle资源并结束WaitCondition的等待。

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
            # 挂盘到/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
            # 这里配置安装脚本
            yum install -y nginx
            # 配置启动脚本
            systemctl start nginx.service
            # 执行成功回调WaitConditionHandle,结束WaitCondition的等待。
            ${CurlCli} -d "{\"Data\" : \"Success\", \"status\" : \"SUCCESS\"}"
          - CurlCli:
              Fn::GetAtt:
                - WaitConditionHandle
                - CurlCli
      

定义ECS实例、负载均衡实例和添加后端服务器依赖关系

您可以通过模板定义ECS实例组EcsInstanceGroup、负载均衡SlbSlbBackendServerAttachment

  • 通过SlbBackendServerAttachment将ECS实例组挂载到CLB实例上。更多信息,请参见ALIYUN::SLB::BackendServerAttachment

    在ALIYUN::SLB::BackendServerAttachment中,如果不指定BackendServerWeightList的值,则BackendServerList中所有ECS实例权重都是100;当BackendServerWeightList长度小于BackendServerList时,则使用BackendServerWeightList中的最后一个值配置BackendServerList中剩余ECS实例的权重。

  • 设置DependsOn属性可以指定资源紧跟在另一个资源后创建。为某个资源添加DependsOn属性后,该资源仅在DependsOn属性中指定的资源后创建。更多信息,请参见DependsOn

  • 使用Fn::GetAtt函数获取资源输出属性值。例如:EcsInstanceGroup中的InstanceIds。更多信息,请参见函数(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

完整模板示例

ROSTemplateFormatVersion: '2015-09-01'
Description:
  en: Create new VPC and vSWitch, create one CLB, two ECS instances, and bind all ECS instances to the CLB.
  zh-cn: 新建VPC、vSWitch,创建1个CLB、2个ECS实例,并将所有ECS实例绑定到CLB上。
Parameters:
  ZoneId:
    Type: String
    AssociationProperty: ALIYUN::ECS::Instance::ZoneId
    Label:
      en: vSwitch Availability Zone
      zh-cn: 交换机可用区
  VpcCidrBlock:
    Default: 192.168.0.0/16
    Label:
      zh-cn: 专有网络网段
      en: VPC CIDR Block
    Type: String
    Description:
      zh-cn: 新建专有网络IP地址段范围,推荐使用以下的IP地址段<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>
      en: New proprietary network IP address segment range, recommended use of the following IP address segments<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: 必须是所属专有网络的子网段,并且没有被其他交换机占用。
      en: Must be a sub-network segment of the proprietary network and is not occupied by other vSwitches.
    Label:
      zh-cn: 交换机网段
      en: vSwitch CIDR Block
  EcsInstanceType:
    Type: String
    Label:
      en: Instance Type
      zh-cn: 实例类型
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceChargeType: ${InstanceChargeType}
  SystemDiskCategory:
    Type: String
    Description:
      en: '<font color=''blue''><b>Optional values:</b></font><br>[cloud_efficiency: <font color=''green''>Efficient Cloud Disk</font>]<br>[cloud_ssd: <font color=''green''>SSD Cloud Disk</font>]<br>[cloud_essd: <font color=''green''>ESSD Cloud Disk</font>]<br>[cloud: <font color=''green''>Cloud Disk</font>]<br>[ephemeral_ssd: <font color=''green''>Local SSD Cloud Disk</font>]'
      zh-cn: '<font color=''blue''><b>可选值:</b></font><br>[cloud_efficiency: <font color=''green''>高效云盘</font>]<br>[cloud_ssd: <font color=''green''>SSD云盘</font>]<br>[cloud_essd: <font color=''green''>ESSD云盘</font>]<br>[cloud: <font color=''green''>普通云盘</font>]<br>[ephemeral_ssd: <font color=''green''>本地SSD盘</font>]'
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Label:
      en: System Disk Type
      zh-cn: 系统盘类型
  SystemDiskSize:
    Default: 40
    Type: Number
    Description:
      zh-cn: 系统盘大小, 取值范围:[40, 500], 单位:GB。
    Label:
      zh-cn: 系统盘空间
      en: System Disk Space
  DataDiskCategory:
    AssociationProperty: ALIYUN::ECS::Disk::DataDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Type: String
    Description:
      zh-cn: '<font color=''blue''><b>可选值:</b></font><br>[cloud_efficiency: <font color=''green''>高效云盘</font>]<br>[cloud_ssd: <font color=''green''>SSD云盘</font>]<br>[cloud_essd: <font color=''green''>ESSD云盘</font>]<br>[cloud: <font color=''green''>普通云盘</font>]'
      en: '<font color=''blue''><b>Optional values:</b></font><br>[cloud_efficiency: <font color=''green''>Efficient Cloud Disk</font>]<br>[cloud_ssd: <font color=''green''>SSD Cloud Disk</font>]<br>[cloud_essd: <font color=''green''>ESSD Cloud Disk</font>]<br>[cloud: <font color=''green''>Cloud Disk</font>]'
    Label:
      zh-cn: 数据盘类型
      en: Data Disk Type
  DataDiskSize:
    Description:
      zh-cn: ECS实例数据盘大小,单位为GiB。取值范围:20~32768。
    Default: 100
    MaxValue: 32768
    MinValue: 20
    Label:
      zh-cn: 数据盘空间
      en: Data Disk Space
    Type: Number
  InstancePassword:
    NoEcho: true
    Type: String
    Description:
      en: Server login password, Length 8~30, must contain three(Capital letters, lowercase letters, numbers, ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ Special symbol in).。
      zh-cn: 服务器登录密码,长度8~30,必须包含三项(大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ 中的特殊符号)。
    AllowedPattern: '[0-9A-Za-z\_\-\&:;''<>,=%`~!@#\(\)\$\^\*\+\|\{\}\[\]\.\?\/]+$'
    Label:
      en: Instance Password
      zh-cn: 实例密码
    ConstraintDescription:
      en: Length 8~30, must contain three(Capital letters, lowercase letters, numbers, ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ Special symbol in).
      zh-cn: 长度8~30,必须包含三项(大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ 中的特殊符号)。
    MinLength: 8
    MaxLength: 30
    AssociationProperty: ALIYUN::ECS::Instance::Password
  PayType:
    Type: String
    Label:
      en: ECS Instance Charge Type
      zh-cn: 付费类型
    Default: PostPaid
    AllowedValues:
      - PostPaid
      - PrePaid
    AssociationProperty: ChargeType
    AssociationPropertyMetadata:
      LocaleKey: InstanceChargeType
  PayPeriodUnit:
    Type: String
    Description:
      en: The long cycle of purchasing resources. <br>Week is a Week and Month is a Month. <br> The default value is month.<br><b><font color='red'> When ECS instance types are PrePaid valid.</b></font>
      zh-cn: 购买资源时长的周期。<br>Week为周,Month为月<br>默认值为月<br><b><font color='red'>当ECS实例类型为PrePaid有效。</b></font>
    Label:
      en: Pay Period Unit
      zh-cn: 购买资源时长周期
    Default: Month
    AllowedValues:
      - Month
      - Year
    AssociationProperty: PayPeriodUnit
    AssociationPropertyMetadata:
      Visible:
        Condition:
          Fn::Not:
            Fn::Equals:
              - ${PayType}
              - PostPaid
  PayPeriod:
    Type: Number
    Label:
      en: Period
      zh-cn: 购买资源时长
    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: LoadBalancer Specifications
      zh-cn: 负载均衡实例规格
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
  Bandwidth:
    Description:
      zh-cn: 取值范围:[0, 1000],单位:Mbps。
      en: 'Value range: [0, 1000], Unit: Mbps.'
    Default: 10
    MaxValue: 1000
    Label:
      zh-cn: 负载均衡的弹性公网IP带宽
      en: CLB Elastic IP Bandwidth
    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
            # 挂盘到/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
            # 这里配置安装脚本
            yum install -y nginx
            # 配置启动脚本
            systemctl start nginx.service
            # 执行成功回调WaitConditionHandle,结束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: 对外暴露的公网IP地址。
      en: Public IP Addresses.
    Value:
      Fn::Sub:
        - http://${ServerAddress}
        - ServerAddress:
            Fn::GetAtt:
              - EipSlbAddress
              - EipAddress

添加模板参数分组与动态获取参数配置

在以上模板中您完成了对多种资源及其依赖关系的定义,此时模板中EcsInstanceGroup资源的InstanceTypeSystemDiskCategory属性值与Slb资源的LoadBalancerSpec属性值为引用参数。当您在不同地域创建资源栈时,需要多次调整模板变更资源属性值以达到部署资源栈的目的。

您可以对模板添加参数Parameters,从而提高模板的灵活性和可复用性。

添加模板参数分组

您可以在模板中使用元数据(Metadata)对Parameters中定义的参数进行分组,并定义参数分组标签。

当您完成对模板资源和参数的定义后,可以按照不同资源和资源对应的参数进行分组。

以当前模板为例,您可以将资源按如下结果划分。

资源参数分类

资源名称

参数名称

基础网络配置

VpcVSwitchEcsSecurityGroup

ZoneIdVpcCidrBlockVSwitchCidrBlock

负载均衡配置

SlbEipSlbAddress

LoadBalancerSpecBandwidth

云服务器ECS配置

EcsInstanceGroup

PayTypePayPeriodUnitPayPeriodECSInstanceTypeECSDiskSizeECSDiskCategoryEcsInstancePassword

动态获取参数配置

ECSInstanceType参数为例,当你需要在ROS控制台上对参数设置筛选条件并动态选择参数配置时,可以根据参数对应的资源类型(ALIYUN::ECS::InstanceGroup)在AssociationProperty和AssociationPropertyMetadata文档中查询到该参数支持的AssociationProperty取值(ALIYUN::ECS::Instance::InstanceType),然后对筛选到的AssociationProperty查询过滤条件为ZoneIdInstanceChargeType的AssociationPropertyMetadata取值。更多信息,请参见AssociationProperty和AssociationPropertyMetadata

完整模板示例

ROSTemplateFormatVersion: '2015-09-01'
Description:
  en: Create new VPC and vSWitch,, create one CLB, two ECS instances, and bind all ECS instances to the CLB.
  zh-cn: 新建已有VPC、vSWitch,创建1个CLB、2个ECS实例,并将所有ECS实例绑定到CLB上。
Parameters:
  ZoneId:
    Type: String
    AssociationProperty: ALIYUN::ECS::Instance::ZoneId
    Label:
      en: vSwitch Availability Zone
      zh-cn: 交换机可用区
  VpcCidrBlock:
    Default: 192.168.0.0/16
    Label:
      zh-cn: 专有网络网段
      en: VPC CIDR Block
    Type: String
    Description:
      zh-cn: 新建专有网络IP地址段范围,推荐使用以下的IP地址段<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>
      en: New proprietary network IP address segment range, recommended use of the following IP address segments<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: 必须是所属专有网络的子网段,并且没有被其他交换机占用。
      en: Must be a sub-network segment of the proprietary network and is not occupied by other vSwitches.
    Label:
      zh-cn: 交换机网段
      en: vSwitch CIDR Block
  EcsInstanceType:
    Type: String
    Label:
      en: Instance Type
      zh-cn: 实例类型
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceChargeType: ${InstanceChargeType}
  SystemDiskCategory:
    Type: String
    Description:
      en: '<font color=''blue''><b>Optional values:</b></font><br>[cloud_efficiency: <font color=''green''>Efficient Cloud Disk</font>]<br>[cloud_ssd: <font color=''green''>SSD Cloud Disk</font>]<br>[cloud_essd: <font color=''green''>ESSD Cloud Disk</font>]<br>[cloud: <font color=''green''>Cloud Disk</font>]<br>[ephemeral_ssd: <font color=''green''>Local SSD Cloud Disk</font>]'
      zh-cn: '<font color=''blue''><b>可选值:</b></font><br>[cloud_efficiency: <font color=''green''>高效云盘</font>]<br>[cloud_ssd: <font color=''green''>SSD云盘</font>]<br>[cloud_essd: <font color=''green''>ESSD云盘</font>]<br>[cloud: <font color=''green''>普通云盘</font>]<br>[ephemeral_ssd: <font color=''green''>本地SSD盘</font>]'
    AssociationProperty: ALIYUN::ECS::Disk::SystemDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Label:
      en: System Disk Type
      zh-cn: 系统盘类型
  SystemDiskSize:
    Default: 40
    Type: Number
    Description:
      zh-cn: 系统盘大小, 取值范围:[40, 500], 单位:GB。
      en: 'System disk size, range of values: 40-500, units: GB.'
    Label:
      zh-cn: 系统盘空间
      en: System Disk Space
  DataDiskCategory:
    AssociationProperty: ALIYUN::ECS::Disk::DataDiskCategory
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
      InstanceType: ${EcsInstanceType}
    Type: String
    Description:
      zh-cn: '<font color=''blue''><b>可选值:</b></font><br>[cloud_efficiency: <font color=''green''>高效云盘</font>]<br>[cloud_ssd: <font color=''green''>SSD云盘</font>]<br>[cloud_essd: <font color=''green''>ESSD云盘</font>]<br>[cloud: <font color=''green''>普通云盘</font>]'
      en: '<font color=''blue''><b>Optional values:</b></font><br>[cloud_efficiency: <font color=''green''>Efficient Cloud Disk</font>]<br>[cloud_ssd: <font color=''green''>SSD Cloud Disk</font>]<br>[cloud_essd: <font color=''green''>ESSD Cloud Disk</font>]<br>[cloud: <font color=''green''>Cloud Disk</font>]'
    Label:
      zh-cn: 数据盘盘类型
      en: Data Disk Type
  DataDiskSize:
    Description:
      zh-cn: ECS实例数据盘大小,单位为GiB。取值范围:20~32768。
      en: 'ECS Instance disk size, range of values: 20-32768, units: GB.'
    Default: 100
    MaxValue: 32768
    MinValue: 20
    Label:
      zh-cn: 数据盘空间
      en: Data Disk Space
    Type: Number
  InstancePassword:
    NoEcho: true
    Type: String
    Description:
      en: Server login password, Length 8~30, must contain three(Capital letters, lowercase letters, numbers, ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ Special symbol in).
      zh-cn: 服务器登录密码,长度8~30,必须包含三项(大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ 中的特殊符号)。
    AllowedPattern: '[0-9A-Za-z\_\-\&:;''<>,=%`~!@#\(\)\$\^\*\+\|\{\}\[\]\.\?\/]+$'
    Label:
      en: Instance Password
      zh-cn: 实例密码
    ConstraintDescription:
      en: Length 8~30, must contain three(Capital letters, lowercase letters, numbers, ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ Special symbol in).
      zh-cn: 长度8~30,必须包含三项(大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;'<>,.?/ 中的特殊符号)。
    MinLength: 8
    MaxLength: 30
    AssociationProperty: ALIYUN::ECS::Instance::Password
  PayType:
    Type: String
    Label:
      en: ECS Instance Charge Type
      zh-cn: 付费类型
    Default: PostPaid
    AllowedValues:
      - PostPaid
      - PrePaid
    AssociationProperty: ChargeType
    AssociationPropertyMetadata:
      LocaleKey: InstanceChargeType
  PayPeriodUnit:
    Type: String
    Description:
      en: The long cycle of purchasing resources. <br>Week is a Week and Month is a Month. <br> The default value is month.<br><b><font color='red'> When ECS instance types are PrePaid valid.</b></font>
      zh-cn: 购买资源时长的周期。<br>Week为周,Month为月<br>默认值为月<br><b><font color='red'>当ECS实例类型为PrePaid有效。</b></font>
    Label:
      en: Pay Period Unit
      zh-cn: 购买资源时长周期
    Default: Month
    AllowedValues:
      - Month
      - Year
    AssociationProperty: PayPeriodUnit
    AssociationPropertyMetadata:
      Visible:
        Condition:
          Fn::Not:
            Fn::Equals:
              - ${PayType}
              - PostPaid
  PayPeriod:
    Type: Number
    Label:
      en: Period
      zh-cn: 购买资源时长
    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: LoadBalancer Specifications
      zh-cn: 负载均衡实例规格
    AssociationPropertyMetadata:
      ZoneId: ${ZoneId}
  Bandwidth:
    Description:
      zh-cn: 取值范围:[0, 1000],单位:Mbps。
      en: 'Value range: [0, 1000], Unit: Mbps.'
    Default: 10
    MaxValue: 1000
    Label:
      zh-cn: 负载均衡的弹性公网IP带宽
      en: CLB Elastic IP Bandwidth
    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
            # 挂盘到/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
            # 这里配置安装脚本
            yum install -y nginx
            # 配置启动脚本
            systemctl start nginx.service
            # 执行成功回调WaitConditionHandle,结束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: 对外暴露的公网IP地址
      en: Public IP Addresses
    Value:
      Fn::Sub:
        - http://${ServerAddress}
        - ServerAddress:
            Fn::GetAtt:
              - EipSlbAddress
              - EipAddress
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - ZoneId
          - VpcCidrBlock
          - VSwitchCidrBlock
        Label:
          default:
            zh-cn: 基础网络配置
            en: Basic Network Configuration
      - Parameters:
          - PayType
          - PayPeriodUnit
          - PayPeriod
        Label:
          default:
            en: PayType Configuration
            zh-cn: 付费类型
      - Parameters:
          - EcsInstanceType
          - SystemDiskCategory
          - SystemDiskSize
          - DataDiskCategory
          - DataDiskSize
          - InstancePassword
        Label:
          default:
            en: Instance Configure
            zh-cn: ECS实例配置
      - Parameters:
          - LoadBalancerSpec
          - Bandwidth
        Label:
          default:
            en: CLB Configure
            zh-cn: 负载均衡配置