Tous les produits
Search
Centre de documentation

Resource Orchestration Service:Créer un groupe d'instances ECS et l'associer à une instance CLB

Dernière mise à jour :Aug 10, 2026

Découvrez comment modifier un modèle Resource Orchestration Service (ROS) pour créer un groupe d'instances Elastic Compute Service (ECS) et l'associer à une instance Classic Load Balancer (CLB).

Prérequis

Familiarisez-vous avec la syntaxe et la structure des modèles. Pour plus d'informations, consultez la rubrique Démarrage rapide.

Scénario d'exemple

Créez un groupe d'instances ECS dans un Virtual Private Cloud (VPC), déployez un service Nginx au sein de ce groupe, puis associez le groupe d'instances à une instance CLB.

1

Notes d'utilisation

Consultez les détails des propriétés pour chaque type de ressource. Pour plus d'informations, voir la rubrique Afficher les types de ressources.

Chaque type de ressource définit le type, les exigences et la politique de mise à jour de ses propriétés. Les propriétés requises doivent être déclarées dans la section Properties du bloc Resources. Il n'est pas nécessaire de déclarer les propriétés facultatives. Si une propriété autorise les mises à jour, vous pouvez la modifier dans un nouveau modèle, puis mettre à jour la pile pour appliquer les changements. Dans le cas contraire, la propriété ne peut pas être mise à jour.

Modifier le modèle

Recherchez les types de ressources requis dans l'index des types de ressources. Pour plus d'informations, consultez la rubrique Index des types de ressources.

Ce scénario nécessite les ressources suivantes : un VPC (ALIYUN::ECS::VPC), un groupe d'instances ECS (ALIYUN::ECS::InstanceGroup), une instance Server Load Balancer (SLB) (ALIYUN::SLB::LoadBalancer), un écouteur SLB (ALIYUN::SLB::Listener), une adresse IP élastique (EIP) (ALIYUN::VPC::EIP), un vSwitch (ALIYUN::ECS::VSwitch) et un groupe de sécurité (ALIYUN::ECS::SecurityGroup). Lors de la création du groupe d'instances ECS, vous pouvez utiliser le paramètre UserData de ALIYUN::ECS::InstanceGroup pour exécuter une commande d'initialisation. Vous pouvez utiliser une ressource de condition d'attente (ALIYUN::ROS::WaitCondition) et une ressource de handle de condition d'attente (ALIYUN::ROS::WaitConditionHandle) pour contrôler le flux d'exécution au sein du groupe d'instances ECS.

Définissez ces ressources dans la section Resources du modèle.

Définir les ressources du modèle et leurs dépendances

Définir les ressources réseau de base

Définissez les ressources réseau de base telles que Vpc, VSwitch et EcsSecurityGroup.

  • Utilisez la fonction Ref avec le pseudo-paramètre ALIYUN::StackName pour récupérer le nom de la pile et l'utiliser comme valeur pour une propriété de ressource. Par exemple, cette méthode est utilisée pour la propriété VpcName de la ressource Vpc et la propriété VSwitchName de la ressource VSwitch. Pour plus d'informations, consultez les rubriques Fonctions et ALIYUN::StackName.

  • Utilisez la fonction Ref pour récupérer la valeur de retour d'une ressource spécifiée. Par exemple, Ref: Vpc dans la ressource VSwitch récupère la valeur de retour VpcId de la ressource Vpc. La valeur de retour correspond généralement à l'ID de la ressource. Pour plus d'informations, consultez la rubrique Fonctions.

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

Définir l'instance SLB et les ressources EIP

Définissez l'instance SLB Slb, l'écouteur SLB SlbListener et la ressource EIP EipSlbAddress.

La fonction Fn::Sub concatène le pseudo-paramètre ALIYUN::StackName dans une nouvelle chaîne à utiliser comme valeur de propriété de ressource. Pour plus d'informations, consultez la rubrique 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

Définir le groupe d'instances ECS, la ressource de condition d'attente et la ressource de handle de condition d'attente

Définissez le groupe d'instances ECS EcsInstanceGroup, la ressource de condition d'attente WaitCondition et la ressource de handle de condition d'attente WaitConditionHandle.

  • Utilisez la fonction Fn::GetAtt pour récupérer la valeur d'un attribut d'une ressource dans le modèle. Par exemple, vous pouvez récupérer la valeur de retour CurlCli de la ressource WaitConditionHandle. Pour plus d'informations, consultez la rubrique Fonctions.

  • Utilisez la fonction Fn::Sub pour construire une chaîne de commande et substituer les variables d'une chaîne d'entrée par des valeurs spécifiées. Par exemple, dans la propriété UserData de la ressource EcsInstanceGroup, ${CurlCli} est remplacé par la valeur de CurlCli. Pour plus d'informations, consultez la rubrique Fonctions.

  • La combinaison de ressources suivante contrôle le processus d'initialisation au sein des instances ECS.

    1. Créez une ressource de condition d'attente (ALIYUN::ROS::WaitCondition).

    2. Créez une ressource de handle de condition d'attente (ALIYUN::ROS::WaitConditionHandle).

    3. Dans le UserData de l'instance ECS, exécutez un script et envoyez un signal. Par exemple, le contenu UserData de la ressource EcsInstanceGroup contient un script d'initialisation pour l'instance ECS. Une fois le script exécuté avec succès, il envoie un rappel à la ressource WaitConditionHandle. Cela met fin à l'état d'attente de la ressource 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
            # 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
      

Définir les dépendances pour le groupe d'instances ECS, l'instance SLB et l'association du serveur backend

Définissez le groupe d'instances ECS EcsInstanceGroup, l'instance SLB Slb et l'association du serveur backend SlbBackendServerAttachment.

  • Utilisez SlbBackendServerAttachment pour associer le groupe d'instances ECS à l'instance CLB. Pour plus d'informations, consultez la rubrique ALIYUN::SLB::BackendServerAttachment.

    Dans ALIYUN::SLB::BackendServerAttachment, si vous ne spécifiez pas de valeur pour BackendServerWeightList, le poids de toutes les instances ECS dans BackendServerList est par défaut de 100. Si BackendServerWeightList contient moins d'entrées que BackendServerList, la dernière valeur de poids dans BackendServerWeightList est appliquée à toutes les instances ECS restantes dans BackendServerList.

  • Utilisez la propriété DependsOn pour spécifier qu'une ressource est créée uniquement après la création d'une autre ressource. Pour plus d'informations, consultez la rubrique DependsOn.

  • Utilisez la fonction Fn::GetAtt pour récupérer la valeur d'une propriété de sortie d'une ressource. Par exemple, vous pouvez récupérer les InstanceIds de la ressource EcsInstanceGroup. Pour plus d'informations, consultez la rubrique Fonctions.

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

Modèle d'exemple complet

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

Ajouter des groupes de paramètres et obtenir dynamiquement les configurations de paramètres

Les propriétés InstanceType et SystemDiskCategory de la ressource EcsInstanceGroup ainsi que la propriété LoadBalancerSpec de la ressource Slb font référence à des paramètres. Lorsque vous créez des piles dans différentes régions, vous devez fournir des valeurs différentes pour ces propriétés pour chaque déploiement.

Ajoutez une section Parameters au modèle pour le rendre plus flexible et réutilisable.

Ajouter des groupes de paramètres

Utilisez la section Metadata pour regrouper les paramètres définis dans la section Parameters et définir des libellés pour les groupes de paramètres.

Après avoir défini les ressources et les paramètres du modèle, regroupez les paramètres en fonction des ressources auxquelles ils correspondent.

Le tableau suivant montre comment regrouper les ressources pour cet exemple.

Catégorie de paramètres

Nom de la ressource

Nom du paramètre

Configuration réseau de base

Vpc, VSwitch, EcsSecurityGroup

ZoneId, VpcCidrBlock, VSwitchCidrBlock

Configuration SLB

Slb, EipSlbAddress

LoadBalancerSpec, Bandwidth

Configuration ECS

EcsInstanceGroup

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

Obtenir dynamiquement les configurations de paramètres

Prenons EcsInstanceType comme exemple. Pour définir des conditions de filtre et sélectionner dynamiquement une configuration dans la console ROS, trouvez sa valeur AssociationProperty prise en charge. Sur la base du type de ressource ALIYUN::ECS::InstanceGroup, la valeur est ALIYUN::ECS::Instance::InstanceType. Ensuite, interrogez les valeurs AssociationPropertyMetadata en utilisant des conditions de filtre telles que ZoneId et InstanceChargeType. Pour plus d'informations, consultez la rubrique AssociationProperty et AssociationPropertyMetadata.

Modèle d'exemple complet

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