您可以在TypeScript语言环境使用ROS CDK,创建安全组并添加多条安全组规则。

步骤一:初始化工程

每个ROS CDK应用都要求创建在一个独立的工程目录下,且该应用需要使用独立工程目录中模块的依赖项。所以在创建应用之前,需要先创建一个工程目录并进行初始化。

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

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

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

  1. 执行以下命令,配置阿里云凭证信息。
    ros-cdk config
  2. 根据界面提示输入配置信息。
    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!

    配置内容说明如下:

    • endpoint:ROS服务地址。默认值为https://ros.aliyuncs.com。
    • defaultRegionId:ROS资源栈部署的地域。默认值为cn-hangzhou。
    • Authenticate mode:鉴权方式。本示例的鉴权方式为AccessKey,您需要输入accessKeyId和accessKeySecret。

步骤三:安装依赖

  1. 修改package.json文件,添加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.0",
        "@alicloud/ros-cdk-ecs": "^1.0.0"   
      }
    }
  2. 执行以下命令,安装依赖。
    npm install

步骤四:创建资源

  1. 修改lib/demo-stack.ts文件,创建安全组并添加多条安全组规则。
    import * as ros from '@alicloud/ros-cdk-core';
    import * as ecs from '@alicloud/ros-cdk-ecs';
    
    export class CdkDemoStack 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);
        }
      }
    }
    说明 示例代码通过for循环创建SecurityGroupIngress(安全组入方向的访问规则),极大地减少了代码量。
  2. 执行以下命令,生成模板文件。
    ros-cdk synth --json

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

    {
      "Description": "This is the simple ros cdk app example.",
      "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"
          }
        }
      }
    }

步骤五:单元测试

  1. 修改test/demo.test.ts文件,验证资源栈创建安全组并添加多条安全组规则的可行性。
    import { expect as expectCDK, matchTemplate, MatchStyle } from '@alicloud/ros-cdk-assert';
    import * as ros from '@alicloud/ros-cdk-core';
    import * as CdkDemo from '../lib/cdk_demo-stack';
    
    test('Stack with version.', () => {
      const app = new ros.App();
      // WHEN
      const stack = new CdkDemo.CdkDemoStack(app, 'MyTestStack');
      // THEN
      expectCDK(stack).to(
        matchTemplate(
          {
            "Description": "This is the simple ros cdk app example.",
            "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"
                }
              }
            }
          },
          MatchStyle.EXACT,
        ),
      );
    });
  2. 执行以下命令,进行单元测试。
    npm test

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

    > cdk_demo@0.1.0 test /home/cdk_demo
    > jest
    
     PASS  test/cdk_demo.test.ts
      ✓ Stack with version. (249ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        4.685s
    Ran all test suites.

步骤六:管理资源栈

您可以使用ROS CDK命令,创建、查询或删除资源栈。

  • 创建资源栈

    执行以下命令,创建资源栈。

    ros-cdk deploy

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

    ✅ The deployment(create stack) has completed!
    RequestedId: BC963C80-054D-41A0-87E7-001E0AB7B1BA
    StackId: 0714be3a-0713-4b7d-b7aa-1564adef****
  • 查询资源栈

    执行以下命令,查询资源栈。

    ros-cdk list-stacks

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

     ✅ The Stacks list is:
     [
            {
                    "Status": "CREATE_COMPLETE",
                    "StackType": "ROS",
                    "StatusReason": "Stack CREATE completed successfully",
                    "CreateTime": "2021-01-26T12:58:05",
                    "RegionId": "cn-beijing",
                    "DisableRollback": false,
                    "StackName": "CdkDemoStack",
                    "Tags": [],
                    "StackId": "218f0db0-7992-4e70-a586-15d****",
                    "TimeoutInMinutes": 20
            }
    ]
  • 删除资源栈
    1. 执行以下命令,删除资源栈。
      ros-cdk destroy
    2. 根据界面提示,确认删除。
      The following stack(s) will be destroyed(Only deployed stacks will be displayed).
      CdkDemoStack
      
      Please confirm.(Y/N)
      Y

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

       ✅ Deleted
      RequestedId: 1BF864E1-7965-4148-A302-E6ABFF806641