文档

使用ROS CDK批量创建多个资源

更新时间:

本文以TypeScript语言为例,为您介绍如何使用ROS CDK批量创建多个资源。

步骤一:初始化工程

执行以下命令,创建工程目录并初始化工程。

mkdir demo
cd demo
ros-cdk init --language=typescript --generate-only=true

步骤二:配置阿里云凭证信息

  1. 执行以下命令,配置阿里云凭证信息。

    ros-cdk config
  2. 根据界面提示输入配置信息。

    ros-cdk config
    endpoint(optional, default:https://ros.aliyuncs.com):
    defaultRegionId(optional, default:cn-hangzhou):cn-beijing
    
    [1] AK
    [2] StsToken
    [3] RamRoleArn
    [4] EcsRamRole
    [0] CANCEL
    
    Authenticate mode [1...4 / 0]: 1
    accessKeyId:************************
    accessKeySecret:******************************
    
     ✅ Your cdk configuration has been saved successfully!

步骤三:安装依赖

  1. 修改package.json文件,添加ECS依赖包(ros-cdk-ecs)。

    {
      "name": "demo",
      "version": "0.1.0",
      "bin": {
        "demo": "bin/demo.js"
      },
      "scripts": {
        "build": "tsc",
        "test": "jest"
      },
      "devDependencies": {
        "@types/jest": "^25.2.1",
        "@types/node": "10.17.5",
        "typescript": "^3.9.7",
        "jest": "^25.5.0",
        "ts-jest": "^25.3.1",
        "ts-node": "^8.1.0",
        "babel-jest": "^26.6.3",
        "@babel/core": "^7.12.9",
        "@babel/preset-env": "7.12.7",
        "@babel/preset-typescript": "^7.12.7",
        "@alicloud/ros-cdk-assert": "^1.0.0"
      },
      "dependencies": {
        "@alicloud/ros-cdk-core": "^1.0.5",
        "@alicloud/ros-cdk-ecs": "^1.0.3"
      }
    }
  2. 执行以下命令,安装依赖。

    npm install

步骤四:管理资源栈

  1. 修改lib/demo-stack.ts文件,创建安全组。

    通过for循环创建安全组入方向的访问规则(SecurityGroupIngress),实现了批量创建多个资源的诉求,并且代码更为精简。下列提供多语言的示例代码供您参考。

    TypeScript示例

    import * as ros from '@alicloud/ros-cdk-core';
    import * as ecs from '@alicloud/ros-cdk-ecs';
    
    export class DemoStack extends ros.Stack {
      constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
    
        const sg = new ecs.SecurityGroup(this, 'ros-cdk-test-sg');
    
        let PortList= ['22','3389','80'];
        for (let port of PortList) {
           new ecs.SecurityGroupIngress(this, `ros-cdk-test-sg-ingress-${port}`, {
            portRange: `${port}/${port}`,
            nicType: 'intranet',
            sourceCidrIp: '0.0.0.0/0',
            ipProtocol: 'tcp',
            securityGroupId: sg.attrSecurityGroupId
          },true);
        }
      }
    }

    Java示例

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    
    import com.aliyun.ros.cdk.ecs.*;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
            List<String> port_list = new ArrayList<>();
            port_list.add("22");
            port_list.add("3389");
            port_list.add("80");
            SecurityGroup sg = SecurityGroup.Builder.create(this, "sg").build();
            for (String element : port_list) {
                SecurityGroupIngress.Builder.create(this, "ros-cdk-test-sg-ingress-" + element).
                        nicType("intranet").sourceCidrIp("0.0.0.0/0").ipProtocol("tcp").securityGroupId(sg.getAttrSecurityGroupId()).portRange(element + "/" + element).build();
            }
    
        }
    }

    Python示例

    import ros_cdk_core as core
    import ros_cdk_ecs as ecs
    
    
    class DemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
    
            # The code that defines your stack goes here
            sg = ecs.SecurityGroup(self, "ros-cdk-test-sg")
    
            prot_list = ["22", "3389", "80"]
    
            for i in prot_list:
                ecs.SecurityGroupIngress(self, "ros-cdk-test-sg-ingress-" + i,
                                         ecs.SecurityGroupIngressProps(port_range=i + "/" + i, nic_type="intranet",
                                                                       source_cidr_ip="0.0.0.0/0",
                                                                       ip_protocol="tcp",
                                                                       security_group_id=sg.attr_security_group_id))

    C#示例

    using AlibabaCloud.SDK.ROS.CDK.Core;
    using AlibabaCloud.SDK.ROS.CDK.Ecs;
    
    namespace Demo
    {
        public class DemoStack : Stack
        {
            public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            {
                // The code that defines your stack goes here
    
                var sg = new SecurityGroup(this, "ros-cdk-test-sg");
                
                object[] portArray = new object[3] {"22", "3389", "80"};
    
                foreach (var port in  portArray)
                {
                    new SecurityGroupIngress(this, "ros-cdk-test-sg-ingress-" + port, new SecurityGroupIngressProps
                    {
                        PortRange = port+ "/" + port,
                        NicType = "intranet",
                        SourceCidrIp = "0.0.0.0/0",
                        IpProtocol = "tcp",
                        SecurityGroupId = sg.AttrSecurityGroupId
                    });
                }
                
            }
        }
    }
    

  2. 执行以下命令,生成模板文件。

    ros-cdk synth --json

    执行命令后,输出以下内容:

    {
      "Description": "This is the simple ros cdk app example.",
      "Metadata": {
        "ALIYUN::ROS::Interface": {
          "TemplateTags": [
            "Create by ROS CDK"
          ]
        }
      },
      "ROSTemplateFormatVersion": "2015-09-01",
      "Resources": {
        "ros-cdk-test-sg": {
          "Type": "ALIYUN::ECS::SecurityGroup"
        },
        "ros-cdk-test-sg-ingress-22": {
          "Type": "ALIYUN::ECS::SecurityGroupIngress",
          "Properties": {
            "IpProtocol": "tcp",
            "PortRange": "22/22",
            "NicType": "intranet",
            "Priority": 1,
            "SecurityGroupId": {
              "Fn::GetAtt": [
                "ros-cdk-test-sg",
                "SecurityGroupId"
              ]
            },
            "SourceCidrIp": "0.0.0.0/0"
          }
        },
        "ros-cdk-test-sg-ingress-3389": {
          "Type": "ALIYUN::ECS::SecurityGroupIngress",
          "Properties": {
            "IpProtocol": "tcp",
            "PortRange": "3389/3389",
            "NicType": "intranet",
            "Priority": 1,
            "SecurityGroupId": {
              "Fn::GetAtt": [
                "ros-cdk-test-sg",
                "SecurityGroupId"
              ]
            },
            "SourceCidrIp": "0.0.0.0/0"
          }
        },
        "ros-cdk-test-sg-ingress-80": {
          "Type": "ALIYUN::ECS::SecurityGroupIngress",
          "Properties": {
            "IpProtocol": "tcp",
            "PortRange": "80/80",
            "NicType": "intranet",
            "Priority": 1,
            "SecurityGroupId": {
              "Fn::GetAtt": [
                "ros-cdk-test-sg",
                "SecurityGroupId"
              ]
            },
            "SourceCidrIp": "0.0.0.0/0"
          }
        }
      }
    }
  3. 执行以下命令,创建资源栈。

    ros-cdk deploy --sync=true

    执行命令后,输出以下内容:

    DemoStack: deploying...
    |DemoStack               |2021-12-28T09:17:54 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress | sg-2ze7gbyb0sngx7et**** | ros-cdk-test-sg-ingress-22
    
    |DemoStack               |2021-12-28T09:17:54 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress | sg-2ze7gbyb0sngx73a**** | ros-cdk-test-sg-ingress-80
    
    |DemoStack               |2021-12-28T09:17:54 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroup | sg-2ze7gbyb0sngx7r4**** | ros-cdk-test-sg
    
    |DemoStack               |2021-12-28T09:17:54 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress | sg-2ze7gbyb0snget3**** | ros-cdk-test-sg-ingress-3389
    
    
     ✅ The deployment(sync deploy stack) has finished!
    status: CREATE_COMPLETE
    StatusReason: Stack CREATE completed successfully
    StackId: a6f1fd14-c985-4dd2-9913-1e7bbeef****
  4. 可选:删除资源栈。

    1. 执行以下命令:

      ros-cdk destroy --sync=true
    2. 根据界面提示,确认删除。

      The following stack(s) will be destroyed(Only deployed stacks will be displayed).
      
      DemoStack
      
      Please confirm.(Y/N)
      y

      执行命令后,输出以下内容:

      DemoStack: destroying...
      |DemoStack               | DELETE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress |  | ros-cdk-test-sg-ingress-22
      
      |DemoStack               | DELETE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress |  | ros-cdk-test-sg-ingress-80
      
      |DemoStack               | DELETE_COMPLETE      | ALIYUN::ECS::SecurityGroup |  | ros-cdk-test-sg
      
      |DemoStack               | DELETE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress |  | ros-cdk-test-sg-ingress-3389
      
       
      ✅ The task(sync destroy stack) has finished!
      status: DELETE_COMPLETE
      StatusReason: Stack DELETE completed successfully
      StackId: a6f1fd14-c985-4dd2-9913-1e7bbeef****
  • 本页导读 (1)