ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: 该模板用于创建一个包含ECS实例、安全组、Greenplum数据库实例以及执行初始化脚本的资源栈。支持预付费和按量付费模式选择，自定义实例规格、系统盘配置、网络设置及数据库账户安全设置。
  en: This template is designed to provision a resource stack comprising an Elastic
    Compute Service (ECS) instance, security group, Greenplum Database instance, and
    the execution of initialization scripts. It accommodates both prepaid and pay-as-you-go
    payment models, with options for customizing instance specifications, system disk
    configurations, network setups, as well as security settings for database accounts.
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::Or':
            - 'Fn::Equals':
                - '${PayType}'
                - PrePaid
            - 'Fn::Equals':
                - '${PayType}'
                - undefined
  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)
  InstanceCount:
    Type: Number
    Label:
      en: Instance Count
      zh-cn: Node节点数量
    Default: 1
  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
  DBMasterUserName:
    Type: String
    Description:
      en: Primary account name of the database instance.
      zh-cn: 数据库实例的主账号名称。
    ConstraintDescription:
      en: Consist of 2 to 16 characters of lowercase letters, underline. Must begin with a letter and be end with an alphanumeric character
      zh-cn: 由 2 到 16 个小写字母组成，下划线。必须以字母开头，以字母数字字符结尾
    Label:
      zh-cn: 数据库账号名称
      en: DB Username
    Default: rdsuser
    MaxLength: 16
    MinLength: 2
  DBMasterPassword:
    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，必须包含三项（大写字母、小写字母、数字、 ()`~!@#$%^&*_-+=|{}[]:;<>,.?/ 中的特殊符号）
    AllowedPattern: '^[a-zA-Z0-9-\(\)\`\~\!\@\#\$\%\^\&\*\_\-\+\=\|\{\}\[\]\:\;\<\>\,\.\?\/]*$'
    MinLength: 8
    MaxLength: 30
    Default: 'pleasechangeThis'
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
  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
      Password:
        Ref: InstancePassword
      ImageId: centos_7
      InstanceType:
        Ref: EcsInstanceType
      AllocatePublicIP: true
      # 公网带宽
      InternetMaxBandwidthOut: 20
  GPDB:
    Type: ALIYUN::GPDB::ElasticDBInstance
    Properties:
      MasterNodeNum:  1
      SegNodeNum: 4
      InstanceSpec: 8C32G
      EngineVersion: '6.0'
      ZoneId:
        Ref: ZoneId
      VPCId:
        Ref: VpcId
      PayType:
        Ref: PayType
      VSwitchId:
        Ref: VSwitchId
      Period:
        Ref: PayPeriod
      PeriodUnit:
        Ref: PayPeriodUnit
      DBInstanceCategory: Basic
      SegStorageType: cloud_essd
      StorageSize: 400
      SecurityIPList:
        Fn::Join:
          - ','
          - Fn::GetAtt:
              - InstanceGroup
              - PrivateIps
  GPDBAccount:
    Type: ALIYUN::GPDB::Account
    Properties:
      DBInstanceId:
        Fn::GetAtt:
          - GPDB
          - DBInstanceId
      AccountPassword:
        Ref: DBMasterPassword
      AccountName:
        Ref: DBMasterUserName
  WaitCondition:
    Type: ALIYUN::ROS::WaitCondition
    DependsOn:
      - GPDB
      - GPDBAccount
    Properties:
      Count: 1
      Handle:
        Ref: WaitConditionHandle
      Timeout: 300
  WaitConditionHandle:
    Type: ALIYUN::ROS::WaitConditionHandle
  InstanceRunCommand:
    Type: ALIYUN::ECS::RunCommand
    Properties:
      CommandContent:
        'Fn::Sub':
          - |
            #!/bin/bash
            cat >> /root/conf.txt << "EOF"
            ConnectionString=${DBConnectString}
            echo ${DBMasterUserName} ${DBMasterPassword} ${DBConnectString}
            EOF
            
            # 安装资源rpm
            yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
            # 安装postgresql11客户端，服务端
            yum install -y postgresql11
            yum install -y postgresql11-server
            # 连接数据库
            # psql -h ${DBConnectString} -p 5432 -U ${DBMasterUsername}
            # 输入密码即可连接
            # ${DBMasterPassword}

            # 执行成功回调WaitCondition结束waitCondition的等待
            ${CurlCli} -d "{\"Data\" : \"Success\", \"status\" : \"SUCCESS\"}"
          # 获取到waitConditionHandle的地址放到 ${CurlCli}变量里
          - DBMasterUsername:
              Ref: DBMasterUserName
            DBMasterPassword:
              Ref: DBMasterPassword
            # 从Database的Output中拿到内网连接串
            DBConnectString:
              Fn::GetAtt:
                - GPDB
                - ConnectionString
            CurlCli:
              Fn::GetAtt:
                - WaitConditionHandle
                - CurlCli
      Type: RunShellScript
      InstanceIds:
        'Fn::GetAtt':
          - InstanceGroup
          - InstanceIds
      Timeout: '300'

# 定义输出
Outputs:
  # 将数据库连接地址显示在控制台
  ConnectionAddress:
    Value:
      Fn::Sub:
        - https://gpdbnext.console.aliyun.com/gpdb/cn-hangzhou/list/nav/${DBClusterId}/storageelastic/basic
        - DBClusterId:
            Fn::GetAtt:
              - GPDB
              - DBInstanceId

Metadata:
  'ALIYUN::ROS::Interface':
    ParameterGroups:
      - Parameters:
          - VpcId
          - ZoneId
          - VSwitchId
        Label:
          default:
            zh-cn: 选择已有基础资源配置
            en: Choose existing Infrastructure Configuration
      - Parameters:
          - PayType
          - PayPeriodUnit
          - PayPeriod
        Label:
          default:
            en: PayType Configuration
            zh-cn: 付费类型配置
      - Parameters:
          - EcsInstanceType
          - SystemDiskCategory
          - SystemDiskSize
          - InstanceCount
          - InstancePassword
        Label:
          default:
            en: Instance
            zh-cn: ECS实例配置
      - Parameters:
          - DBMasterUserName
          - DBMasterPassword
        Label:
          default:
            en: Database
            zh-cn: ADB