ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: 创建一个ECS实例与PolarDB数据库集群，支持付费方式、资源时长配置，自动设置安全组、系统盘类型与大小，并通过脚本初始化ECS连接数据库。
  en: Provision an ECS (Elastic Compute Service) instance along with a PolarDB database
    cluster, enabling selection of payment options and configuration of resource duration.
    Automatically configure security groups, system disk type, and disk size, and
    initialize the ECS to connect to the database via script.
Parameters:
  PayType:
    Type: String
    Label:
      en: ECS Instance Charge Type
      zh-cn: 付费类型
    Default: PostPaid
    AllowedValues:
      - PostPaid
      - PrePaid
    AssociationProperty: ChargeType
    AssociationPropertyMetadata:
      LocaleKey: InstanceChargeType
  PayPeriodUnit:
    Type: String
    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
    Description:
      en: When the resource purchase duration is Month, the value of Period ranges from 1 to 9, 12, 24, 36, 48, or 60. <br><b><font color='red'> When ECS instance types are PrePaid valid </b></font>
      zh-cn: 当购买资源时长为Month时，Period取值：1~9 <br><b><font color='red'>当ECS实例类型为PrePaid有效</b></font>
    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
  ZoneId:
    Type: String
    AssociationProperty: ALIYUN::ECS::Instance::ZoneId
    Label:
      en: VSwitch Availability Zone
      zh-cn: 交换机可用区
  VpcId:
    AssociationProperty: ALIYUN::ECS::VPC::VPCId
    Type: String
    Description:
      en: Please search the ID starting with (vpc-xxx) from console-Virtual Private Cloud
      zh-cn: 现有虚拟专有网络的实例ID
    Label:
      en: VPC ID
      zh-cn: 专有网络VPC实例ID
  VSwitchId:
    AssociationProperty: ALIYUN::ECS::VSwitch::VSwitchId
    AssociationPropertyMetadata:
      VpcId: ${VpcId}
      ZoneId: ${ZoneId}
    Type: String
    Description:
      en: Instance ID of existing business network switches, console-Virtual Private Cloud-VSwitches under query
      zh-cn: 现有业务网络交换机的实例ID
    Label:
      en: VSwitch ID
      zh-cn: 交换机实例ID
  EcsInstanceType:
    Type: String
    Label:
      en: Instance Type
      zh-cn: 实例类型
    AssociationProperty: ALIYUN::ECS::Instance::InstanceType
    AssociationPropertyMetadata:
      InstanceChargeType: ${PayType}
  SystemDiskCategory:
    Type: String
    AllowedValues:
      - cloud_efficiency
      - cloud_ssd
      - cloud
      - cloud_essd
    Label:
      en: System Disk Category
      zh-cn: 系统盘类型
    Default: cloud_essd
    AssociationPropertyMetadata:
      LocaleKey: DiskCategory
  SystemDiskSize:
    Default: 40
    Type: Number
    Label:
      zh-cn: 系统盘空间 (GB)
      en: System Disk Space (GB)
  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，必须包含三项（大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;<>,.?/ 中的特殊符号）
    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，必须包含三项（大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;<>,.?/ 中的特殊符号）
    AssociationProperty: ALIYUN::ECS::Instance::Password
    AllowedPattern: '^[a-zA-Z0-9-\(\)\`\~\!\@\#\$\%\^\&\*\_\-\+\=\|\{\}\[\]\:\;\<\>\,\.\?\/]*$'
    MinLength: 8
    MaxLength: 30
  InstanceCount:
    Type: Number
    Label:
      en: Instance Count
      zh-cn: Node节点数量
    Default: 1
  PolarDBNodeClass:
    Type: String
    Label: PolarDB Mysql资源规格大小
    Default: polar.mysql.x4.large
    AssociationProperty: ALIYUN::PolarDB::Instance::InstanceType
  PolarDBAccountName:
    Type: String
    Default: polar_root
    Label:
      zh-cn: polarDB 用户名
      en: polarDB Account Name
  PolarDBPassword:
    NoEcho: true
    Type: String
    Description:
      en: 'Length 8-32 characters, can contain size letters, Numbers and special symbols, including:! @ # $ % ^ & * ( ) _ + - ='
      zh-cn: 长度8-32个字符,可包含大小字母、数字及特殊符号（包含：!@#$%^&*()_+-=）
    Label:
      en: PolarDB Password
      zh-cn: PolarDB密码
    ConstraintDescription:
      en: '8-32 characters, can contain size letters, Numbers and special symbols, including:! @ # $ % ^ & * ( ) _ + - ='
      zh-cn: 8-32个字符,可包含大小字母、数字及特殊符号（包含：!@#$%^&*()_+-=）
    AllowedPattern: '^[a-zA-Z0-9-\!\@\#\$\%\^\&\*\-\+\=\_]*$'
    MinLength: 8
    MaxLength: 32
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - PayType
          - PayPeriodUnit
          - PayPeriod
        Label:
          default:
            en: PayType Configuration
            zh-cn: 付费类型配置
      - Parameters:
          - EcsInstanceType
          - SystemDiskCategory
          - SystemDiskSize
          - InstancePassword
          - InstanceCount
        Label:
          default:
            en: Instance
            zh-cn: ECS实例配置
      - Parameters:
          - PolarDBNodeClass
          - PolarDBAccountName
          - PolarDBPassword
        Label:
          default:
            en: Database
            zh-cn: PolarDB数据库配置
      - Parameters:
          - ZoneId
        Label:
          default:
            zh-cn: 可用区配置
            en: Zone Configuration
      - Parameters:
          - VpcId
          - VSwitchId
        Label:
          default:
            zh-cn: 选择已有基础资源配置
            en: Choose existing Infrastructure Configuration
Mappings: {}
Conditions: {}
Outputs: {}
Resources:
  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: VpcId
      SecurityGroupEgress:
        - PortRange: '-1/-1'
          Priority: 1
          IpProtocol: all
          DestCidrIp: 0.0.0.0/0
          NicType: intranet
  Database:
    Type: ALIYUN::POLARDB::DBCluster
    Properties:
      ZoneId:
        Ref: ZoneId
      VpcId:
        Ref: VpcId
      VSwitchId:
        Ref: VSwitchId
      DBType: MySQL
      DBVersion: '5.7'
      DBNodeClass:
        Ref: PolarDBNodeClass
      SecurityIPList:
        Fn::Join:
          - ','
          - Fn::GetAtt:
              - InstanceGroup
              - PrivateIps
      PayType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
  PolarDBAccount:
    Type: ALIYUN::POLARDB::Account
    DependsOn:
      - Database
    Properties:
      DBClusterId:
        Ref: Database
      AccountDescription: PolarDB数据库管理账号
      AccountName:
        Ref: PolarDBAccountName
      AccountType: Super
      AccountPassword:
        Ref: PolarDBPassword
  InstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InstanceName:
        Fn::Join:
          - '-'
          - - Ref: ALIYUN::StackName
            - '[1,4]'
      IoOptimized: optimized
      InstanceChargeType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
      ZoneId:
        Ref: ZoneId
      VpcId:
        Ref: VpcId
      VSwitchId:
        Ref: VSwitchId
      SecurityGroupId:
        Ref: EcsSecurityGroup
      SystemDiskCategory:
        Ref: SystemDiskCategory
      SystemDiskSize:
        Ref: SystemDiskSize
      MaxAmount:
        Ref: InstanceCount
      ImageId: centos_7
      InstanceType:
        Ref: EcsInstanceType
      Password:
        Ref: InstancePassword
      AllocatePublicIP: false
      UserData: '-|'
  WaitCondition:
    Type: ALIYUN::ROS::WaitCondition
    DependsOn:
      - Database
      - InstanceGroup
      - PolarDBAccount
    Properties:
      Count: 1
      Handle:
        Ref: WaitConditionHandle
      Timeout: 300
  WaitConditionHandle:
    Type: ALIYUN::ROS::WaitConditionHandle
  InstanceRunCommand:
    Type: ALIYUN::ECS::RunCommand
    DependsOn:
      - Database
      - PolarDBAccount
    Properties:
      CommandContent:
        Fn::Sub:
          - |
            #!/bin/bash
            cat >> /root/conf.txt << "EOF"
            PolarDBAccountName=${PolarDBAccountName}
            PolarDBPassword=${PolarDBPassword}
            PolarDBConnectString=${PolarDBConnectString}
            EOF
            # 继续进行初始化 在这里补上自己的代码 数据库的初始化可以用shell mysqldump完成
            # init.sh /root/conf.txt
            # init.sh ${PolarDBAccountName} ${PolarDBPassword} ${PolarDBConnectString} 也是可以的

            # 执行成功回调WaitCondition结束waitCondition的等待
            ${CurlCli} -d "{\"Data\" : \"Success\", \"status\" : \"SUCCESS\"}"
          - PolarDBAccountName:
              Ref: PolarDBAccountName
            PolarDBPassword:
              Ref: PolarDBPassword
            PolarDBConnectString:
              Fn::GetAtt:
                - Database
                - ClusterConnectionString
            CurlCli:
              Fn::GetAtt:
                - WaitConditionHandle
                - CurlCli
      Type: RunShellScript
      InstanceIds:
        Fn::GetAtt:
          - InstanceGroup
          - InstanceIds
      Timeout: '300'
