ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: 部署1台ECS实例与MongoDB数据库，支持付费类型选择，自动配置安全组与公网访问，集成数据连接至ECS。
  en: Deploy one ECS instance coupled with a MongoDB database, offering the flexibility
    to choose payment options, automatically configuring security groups and enabling
    public network access, with integrated data connectivity to the ECS instance.
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:
      ZoneId: ${ZoneId}
      InstanceChargeType: ${InstanceChargeType}
  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
  # 实例规格
  DBInstanceClass:
    Type: String
    Description:
      en: The DDS Instance type
      zh-cn: 实例规格
    Label:
      en: The Instance type
      zh-cn: 实例规格
    Default: dds.mongo.mid
    AllowedValues:
      - dds.mongo.mid
      - dds.mongo.standard
      - dds.mongo.large
      - dds.mongo.xlarge
      - dds.mongo.2xlarge
      - dds.mongo.4xlarge
  # 实例存储空间
  DBInstanceStorage:
    Type: Number
    Description:
      en: The storage space
      zh-cn: 实例存储空间
    ConstraintDescription:
      en: The storage space. Incrementing in every 5G.
      zh-cn: 存储空间。每 5G 增加一次。
    Label:
      zh-cn: 存储空间
      en: DB Instance Storage
    Default: 10
    MaxValue: 1000
    MinValue: 5
# 资源配置
Resources:
  MongoDB:
    Type: ALIYUN::MONGODB::Instance
    Properties:
      DBInstanceClass:
        Ref: DBInstanceClass
      DBInstanceStorage:
        Ref: DBInstanceStorage
      SecurityIPArray: '0.0.0.0/0'
      ZoneId:
        Ref: ZoneId
      VpcId:
        Ref: VpcId
      VSwitchId:
        Ref: VSwitchId
      StorageEngine: 'WiredTiger'
      NetworkType: 'VPC'
      # 版本不能使用默认的3.4，否则可能会导致资源创建失败
      EngineVersion: '4.0'
  EcsSecurityGroup:
    Type: ALIYUN::ECS::SecurityGroup
    Properties:
      SecurityGroupName:
        Ref: ALIYUN::StackName
      VpcId:
        Ref: VpcId
      # 安全组入端口
      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
  EcsInstanceGroup:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      # 实例名
      InstanceName:
        Fn::Join:
          - '-'
          - - Ref: ALIYUN::StackName
            - '[1,4]'
      IoOptimized: optimized
      # 付费类型
      InstanceChargeType:
        Ref: PayType
      PeriodUnit:
        Ref: PayPeriodUnit
      Period:
        Ref: PayPeriod
      # 网络配置
      VpcId:
        Ref: VpcId
      ZoneId:
        Ref: ZoneId
      VSwitchId:
        Ref: VSwitchId
      SecurityGroupId:
        Ref: EcsSecurityGroup
      # 磁盘类型和大小
      SystemDiskCategory: cloud_essd
      SystemDiskSize: 200
      DiskMappings:
        - Category: cloud_essd
          Size: 200
      MaxAmount: 1
      # 镜像
      ImageId: centos_7
      # 实例类型
      InstanceType:
        Ref: EcsInstanceType
      Password:
        Ref: InstancePassword
      # 公网开启
      AllocatePublicIP: true
      # 公网带宽
      InternetMaxBandwidthOut: 100
      # 启动脚本
      # cloud-init执行用户命令
      # /var/log/cloud-init.log /var/log/cloud-init-output.log 可以看到执行日志
      # /var/lib/cloud/instance/scripts/part-001 为具体的脚本 可以sh 执行来排查问题
      UserData:
        Fn::Sub:
          - |
            #!/bin/bash
            cat >> /root/conf.txt << "EOF"
            DBConnectString=${DBConnectString}
            EOF
            # 安装mongoDB 
            # 1.wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.9.tgz
            # 2.tar -zxvf mongodb-linux-x86_64-4.0.9.tgz
            # 3.mv mongodb-linux-x86_64-4.0.9 /usr/local/mongodb
            # 4.cd /usr/local/mongodb
            # 5.vim /etc/profile
            # 6.source /etc/profile
            # 7.echo $PATH
            
            # 在安装有MongoDB的客户端（本地服务器或ECS服务器）上连接云数据库MongoDB单节点实例
            # mongo --host <host> --port <port> -u <username> -p --authenticationDatabase <authenticationDatabase>
            # 例子：mongo --host dds-bp1ea17b41abecf43****.mongodb.rds.aliyuncs.com --port 3717 -u test -p --authenticationDatabase admin
            # 返回：MongoDB shell version v4.0.9
          - DBConnectString:
              Fn::GetAtt:
                - MongoDB
                - ConnectionURI
# 定义输出
Outputs:
  # 将公网ip做为http返回的地址显示在控制台
  Endpoint:
    Description:
      zh-cn: 对外暴露的公网IP地址
      en: Public IP Addresses
    Value:
      Fn::Sub:
        - http://${ServerAddress}
        - ServerAddress:
            Fn::Select:
              - 0
              - Fn::GetAtt:
                 - EcsInstanceGroup
                 - PublicIps
Metadata:
  ALIYUN::ROS::Interface:
    # 分组信息
    ParameterGroups:
      - Parameters:
          - PayType
          - PayPeriodUnit
          - PayPeriod
        Label:
          default:
            en: PayType Configuration
            zh-cn: 付费类型配置
      - Parameters:
          - ZoneId
        Label:
          default:
            zh-cn: 可用区配置
            en: Zone Configuration
      - Parameters:
          - VpcId
          - VSwitchId
        Label:
          default:
            zh-cn: 选择已有基础资源配置
            en: Choose existing Infrastructure Configuration
      - Parameters:
          - EcsInstanceType
          - InstancePassword
        Label:
          default:
            en: Instance Configuration
            zh-cn: ECS实例配置
      - Parameters:
          - DBInstanceClass
          - DBInstanceStorage
        Label:
          default:
            en: Mongodb Configuration
            zh-cn: Mongodb配置
