All Products
Search
Document Center

Resource Orchestration Service:Example of ROS CDK for TypeScript

Last Updated:Jan 17, 2024

If you do not want to follow the syntax of JSON or YAML templates to orchestrate resources, you can use Cloud Development Toolkit (CDK) of Resource Orchestration Service (ROS). This topic describes how to use ROS CDK for TypeScript to create and manage an Alibaba Cloud virtual private cloud (VPC).

Step 1: Initialize a project

Each ROS CDK application must be created in a separate project directory. The application uses the dependencies of modules in the directory. Before you create an application, you must create a project directory and initialize the project.

Run the following commands to create a project directory and initialize the project:

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

Step 2: Configure an Alibaba Cloud credential

  1. Run the following command to configure an Alibaba Cloud credential:

    ros-cdk config
  2. Follow on-screen instructions to configure the credential parameters.

    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!

    Parameter description:

    • endpoint: the endpoint of ROS. Default value: https://ros.aliyuncs.com.

    • defaultRegionId: the ID of the region where you want to deploy the ROS stack. Default value: cn-hangzhou.

    • Authenticate mode: the authentication method. In this example, an AccessKey pair is used for authentication. In this case, you must specify the AccessKey ID and the AccessKey secret. For more information about how to obtain an AccessKey pair, see Configure a credential in interactive mode (fast).

Step 3: (Optional) Preview the project structure

Run the following command to preview the project structure:

tree .

After you run the command, the following output is returned:

.
├── bin
│   └── demo.ts
├── cdk.json
├── jest.config.js
├── lib
│   └── demo-stack.ts
├── package.json
├── README.md
├── test
│   └── demo.test.ts
└── tsconfig.json

3 directories, 8 files

The following section describes the project structure:

  • bin/demo.ts: the launch file of the project.

    Note

    A project can contain only one application.

    In this example, an application of the ros. App type and a stack that is named DemoStack and is of the DemoStack type are created. The stack is added to the application. The demo.ts file contains the following content:

    #!/usr/bin/env node
    import * as ros from '@alicloud/ros-cdk-core';
    import { DemoStack } from '../lib/demo-stack';
    
    const app = new ros.App({outdir: './cdk.out'});
    new DemoStack(app, 'DemoStack');
    app.synth();
  • lib/demo-stack.ts: the definition file of the stack.

    You can add resources to the stack to dynamically create the stack. When the stack is created, the generated code contains only the description of the stack. The demo-stack.ts file contains the following content:

    import * as ros from '@alicloud/ros-cdk-core';
    
    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
     }
    }
  • test/demo.test.ts: the unit test file.

    The file is used to check whether the created stack follows the expected logic. The demo.test.ts file contains the following content:

    import { expect as expectCDK, matchTemplate, MatchStyle } from '@alicloud/ros-cdk-assert';
    import * as ros from '@alicloud/ros-cdk-core';
    import * as Demo from '../lib/demo-stack';
    
    test('Stack with version.', () => {
     const app = new ros.App();
     // WHEN
     const stack = new Demo.DemoStack(app, 'MyTestStack');
     // THEN
     expectCDK(stack).to(
      matchTemplate(
       {
        ROSTemplateFormatVersion: '2015-09-01',
        Description: "This is the simple ros cdk app example.",
        Metadata: {
          "ALIYUN::ROS::Interface": {
            "TemplateTags" : [
              "Create by ROS CDK"
            ]
          }
        }
       },
       MatchStyle.EXACT,
      ),
     );
    });

Step 4: Install dependencies

  1. Modify the package.json file to add the dependency package of Elastic Compute Service (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.11",
        "@alicloud/ros-cdk-ecs": "^1.0.9"   
      }
    }
  2. Run the following command to install the dependencies:

    npm install

Step 5: Create a resource

  1. Modify the lib/demo-stack.ts file to create a VPC. For more information about how to obtain resource parameters, visit the CDK page.

    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
        new ecs.Vpc(this, 'vpc-from-ros-cdk', {
          vpcName: 'test-ros-cdk',
          cidrBlock: '10.0.0.0/8',
          description: 'This is ros cdk test'
       });
      }
    }
  2. Run the following command to generate a template file:

    ros-cdk synth --json

    After you run the command, the following output is returned:

    {
     "Description": "This is the simple ros cdk app example.",
     "Metadata": {
      "ALIYUN::ROS::Interface": {
       "TemplateTags": [
        "Create by ROS CDK"
       ]
      }
     },
     "ROSTemplateFormatVersion": "2015-09-01",
     "Resources": {
      "vpc-from-ros-cdk": {
       "Type": "ALIYUN::ECS::VPC",
       "Properties": {
        "CidrBlock": "10.0.0.0/8",
        "Description": "This is ros cdk test",
        "EnableIpv6": false,
        "VpcName": "test-ros-cdk"
       }
      }
     }
    }

Step 6: Perform a unit test

  1. Modify the test/demo.test.ts file to check whether a VPC can be created for the stack.

    import {expect as expectCDK, matchTemplate, MatchStyle} from '@alicloud/ros-cdk-assert';
    import * as ros from '@alicloud/ros-cdk-core';
    import * as Demo from '../lib/demo-stack';
    
    test('Stack with version.', () => {
        const app = new ros.App();
        // WHEN
        const stack = new Demo.DemoStack(app, 'MyDemoStack');
        // THEN
        expectCDK(stack).to(
            matchTemplate(
                {
                    "Description": "This is the simple ros cdk app example.",
                    "Metadata": {
                        "ALIYUN::ROS::Interface": {
                            "TemplateTags": [
                                "Create by ROS CDK"
                            ]
                        }
                    },
                    "ROSTemplateFormatVersion": "2015-09-01",
                    "Resources": {
                        "vpc-from-ros-cdk": {
                            "Type": "ALIYUN::ECS::VPC",
                            "Properties": {
                                "CidrBlock": "10.0.0.0/8",
                                "Description": "This is ros cdk test",
                                "EnableIpv6": false,
                                "VpcName": "test-ros-cdk"
                            }
                        }
                    }
                },
                MatchStyle.EXACT,
            ),
        );
    });
  2. Run the following command to perform a unit test:

    npm test

    After you run the command, the following output is returned:

    > demo@0.1.0 test /root/demo
    > jest
    
     PASS  test/demo.test.ts
      ✓ Stack with version. (136ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        2.988s, estimated 3s
    Ran all test suites.

Step 7: Manage a stack

You can run ROS CDK commands to create, query, and delete a stack.

  • Create a stack

    Run the following command to create a stack:

    ros-cdk deploy

    After you run the command, the following output is returned:

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

    Run the following command to query a stack:

    ros-cdk list-stacks

    After you run the command, the following output is returned:

     ✅ 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": "DemoStack",
                    "Tags": [],
                    "StackId": "218f0db0-7992-4e70-a586-15d****",
                    "TimeoutInMinutes": 20
            }
    ]
  • Delete a stack

    1. Run the following command to delete a stack:

      ros-cdk destroy
    2. Follow on-screen instructions to confirm the deletion operation.

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

      After you run the command, the following output is returned:

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