All Products
Search
Document Center

:Python example

Last Updated:Feb 29, 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), which is a command-line interface (CLI) tool provided by Resource Orchestration Service (ROS). This topic describes how to use ROS CDK for Python to create and manage a resource. In this example, a virtual private cloud (VPC) is used.

Prerequisites

Python 3.7 or later is available.

Step 1: Initialize a project

  1. Run the following commands to create a project directory and initialize the 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.

    mkdir demo
    cd demo
    ros-cdk init --language=python --generate-only=true
  2. Run the following command to create a virtual environment that belongs to the current project.

    This operation is necessary because a virtual environment is required for the execution of a Python project.

    python3 -m venv .venv
  3. Run the following command to go to the virtual environment:

    source .venv/bin/activate

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:

.
├── README.md
├── account.config.json
├── app.py
├── cdk.json
├── demo
│   ├── __init__.py
│   └── demo_stack.py
├── requirements.txt
├── setup.py
├── source.bat
└── test
    ├── __init__.py
    └── test_demo.py

2 directories, 11 files

The following section describes the project structure:

  • app.py: the launch file of the project.

    Note

    A project can contain only one application.

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

    #!/usr/bin/env python3
    
    import ros_cdk_core as core
    
    from demo.demo_stack import DemoStack
    
    
    app = core.App()
    
    DemoStack(app, "demo")
    
    app.synth()
  • demo/demo_stack.py: 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.py file contains the following content:

    import ros_cdk_core as core
    
    
    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
  • test/test_demo.py: the unit test file.

    The file is used to check whether the logic for creating the stack meets expectations. The test_demo.py file contains the following content:

    #!/usr/bin/env python3
    import unittest
    import ros_cdk_core as core
    from demo.demo_stack import DemoStack
    
    
    class TestStack(unittest.TestCase):
        def setUp(self):
            pass
    
        def test_stack(self):
            app = core.App()
            stack = DemoStack(app, "testdemo")
            artifact = app.synth().get_stack_artifact(stack.artifact_id).template
            expect = {
                       "Metadata": {
                         "ALIYUN::ROS::Interface": {
                           "TemplateTags": [
                             "Create by ROS CDK"
                           ]
                         }
                       },
                       "ROSTemplateFormatVersion": "2015-09-01"
                     }
            self.assertDictContainsSubset(artifact, expect)
    
        def tearDown(self):
            pass
    
    
    if __name__ == '__main__':
        unittest.main()

Step 4: Install dependencies

  1. Modify the requirements.txt file to add the dependency package of Elastic Compute Service (ECS) SDK.

    ros-cdk-core
    ros-cdk-ecs
  2. Use one of the following methods to install the dependencies:

    • Method 1:

      pip install -r requirements.txt
    • Method 2:

      pip install ros-cdk-core ros-cdk-ecs

Step 5: Create a resource

  1. Modify the demo_stack.py file to create a VPC. For more information about how to obtain resource parameters, visit the CDK page.

    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
            ecs.Vpc(self, "VPC", ecs.VPCProps(
                cidr_block='10.0.0.0/8',
                vpc_name='test-ros-cdk',
                description='This is ros python 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:

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

Step 6: Perform a unit test

  1. Modify the test_demo.py file to check whether a VPC can be created for the stack.

    #!/usr/bin/env python3
    import unittest
    import ros_cdk_core as core
    from demo.demo_stack import DemoStack
    
    
    class TestStack(unittest.TestCase):
        def setUp(self):
            pass
    
        def test_stack(self):
            app = core.App()
            stack = DemoStack(app, "testdemo")
            artifact = app.synth().get_stack_artifact(stack.artifact_id).template
            expect = {
                "Metadata": {
                    "ALIYUN::ROS::Interface": {
                        "TemplateTags": [
                            "Create by ROS CDK"
                        ]
                    }
                },
                "ROSTemplateFormatVersion": "2015-09-01",
                "Resources": {
                    "VPC": {
                        "Type": "ALIYUN::ECS::VPC",
                        "Properties": {
                            "CidrBlock": "10.0.0.0/8",
                            "Description": "This is ros python cdk test",
                            "EnableIpv6": False,
                            "VpcName": "test-ros-cdk"
                        }
                    }
                }
            }
            self.assertDictEqual(artifact, expect)
    
        def tearDown(self):
            pass
    
    
    if __name__ == '__main__':
        unittest.main()
    
  2. Run the following command to perform a unit test:

    python -m unittest  -v

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

    test_stack (test.test_demo.TestStack) ... ok
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.052s
    
    OK

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: 218f0db0-7992-4e70-a586-12****
  • 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-152es****",
                    "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