This topic describes how to use Resource Orchestration Service (ROS) CDK for Python to create an Object Storage Service (OSS) bucket.

Prerequisites

Make sure that the Python version is 3.6 or later.

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 within an independent project directory. The application uses the dependencies of the modules in the directory. Therefore, you must create a project directory and initialize the project before you create an application.
    mkdir cdk_demo
    cd cdk_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 every 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. Enter the configuration information.
    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 the stack is deployed. Default value: cn-hangzhou.
    • Authenticate mode: the authentication method. In this example, an AccessKey pair is used for authentication. You must specify the accessKeyId and accessKeySecret parameters.

Step 3: Install dependencies

  1. Modify the requirements.txt file to add the Elastic Compute Service (ECS) SDK dependency.
    ros-cdk-core
    ros-cdk-ecs
  2. Run the following command to install the dependency:
    pip install -r requirements.txt

Step 4: Create resources

  1. Modify the demo_stack.py file to create an OSS bucket.
    import ros_cdk_core as core
    import ros_cdk_oss as oss
    
    
    class CdkDemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
            # create the ros parameters
            oss_bucket_name = core.RosParameter(
                self, "OssBucketName",
                type=core.RosParameterType.STRING,
                description="3 to 63 characters, not beginning and ending with a hyphen (-), can contain lowercase letters, Numbers and hyphens (-)"
            )
            oss_access_control = core.RosParameter(
                self, "OssAccessControl",
                type=core.RosParameterType.STRING,
                description="Set the access permission of the bucket",
                allowed_values=["private", "public-read", "public-read-write"],
                default_value="private"
            )
    
            # define the resource
    
            oss_bucket = oss.Bucket(self, "OSSBucket", props=oss.BucketProps(
                bucket_name=oss_bucket_name,
                access_control=oss_access_control,
            ))
    
            # define the outputs
            out_bucket_domain_name = core.RosOutput(
                self, "BucketDomainName", value=oss_bucket.attr_domain_name)
  2. Run the following command to generate a template file:
    ros-cdk synth --json

    The following content is returned after you run the command:

    {
      "ROSTemplateFormatVersion": "2015-09-01",
      "Parameters": {
        "OssBucketName": {
          "Type": "String",
          "Description": "3 to 63 characters, not beginning and ending with a hyphen (-), can contain lowercase letters, Numbers and hyphens (-)"
        },
        "OssAccessControl": {
          "Type": "String",
          "Default": "private",
          "AllowedValues": [
            "private",
            "public-read",
            "public-read-write"
          ],
          "Description": "Set the access permission of the bucket"
        }
      },
      "Resources": {
        "OSSBucket": {
          "Type": "ALIYUN::OSS::Bucket",
          "Properties": {
            "BucketName": {
              "Ref": "OssBucketName"
            },
            "AccessControl": {
              "Ref": "OssAccessControl"
            },
            "DeletionForce": false
          }
        }
      },
      "Outputs": {
        "BucketDomainName": {
          "Value": {
            "Fn::GetAtt": [
              "OSSBucket",
              "DomainName"
            ]
          }
        }
      }
    }

Step 5: Perform a unit test

  1. Modify the test/cdk_demo.test.ts file to check whether an OSS bucket can be created by using a stack.
    # !/usr/bin/env python3
    import unittest
    import ros_cdk_core as core
    from cdk_demo.cdk_demo_stack import CdkDemoStack
    
    
    class TestStack(unittest.TestCase):
        def setUp(self):
            pass
    
        def test_stack(self):
            app = core.App()
            stack = CdkDemoStack(app, "testcdk-demo")
            artifact = app.synth().get_stack_artifact(stack.artifact_id).template
            expect = {
                "ROSTemplateFormatVersion": "2015-09-01",
                "Parameters": {
                    "OssBucketName": {
                        "Type": "String",
                        "Description": "3 to 63 characters, not beginning and ending with a hyphen (-), can contain lowercase letters, Numbers and hyphens (-)"
                    },
                    "OssAccessControl": {
                        "Type": "String",
                        "Default": "private",
                        "AllowedValues": [
                            "private",
                            "public-read",
                            "public-read-write"
                        ],
                        "Description": "Set the access permission of the bucket"
                    }
                },
                "Resources": {
                    "OSSBucket": {
                        "Type": "ALIYUN::OSS::Bucket",
                        "Properties": {
                            "BucketName": {
                                "Ref": "OssBucketName"
                            },
                            "AccessControl": {
                                "Ref": "OssAccessControl"
                            },
                            "DeletionForce": False
                        }
                    }
                },
                "Outputs": {
                    "BucketDomainName": {
                        "Value": {
                            "Fn::GetAtt": [
                                "OSSBucket",
                                "DomainName"
                            ]
                        }
                    }
                }
            }
            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

    The following content is returned after you run the command:

    test_stack (test.test_cdk_demo.TestStack) ... ok
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.057s
    
    OK

Step 6: Manage stacks

You can create, query, or delete stacks by running ROS CDK commands.

  • Create a stack

    Run the following command to create a stack and specify the OssBucketName and OssAccessControl parameters.

    ros-cdk deploy --parameters OssBucketName=bestros  --parameters OssAccessControl=private

    The following content is returned after you run the command:

     ✅  The deployment(create stack) has completed!
    RequestedId: BC963C80-054D-41A0-87E7-001E0AB7B1BA
    StackId: 218f0db0-7992-4e70-a586-12****
  • Query information about a stack

    Run the following command to query information about a stack:

    ros-cdk list-stacks

    The following content is returned after you run the command:

    ✅ The Stacks list is:
     [
            {
                    "Status": "CREATE_COMPLETE",
                    "StackType": "ROS",
                    "ResourceGroupId": "rg-acfm2xwmxv*****",
                    "StatusReason": "Stack CREATE completed successfully",
                    "CreateTime": "2021-06-16T06:53:54",
                    "RegionId": "cn-beijing",
                    "StackName": "CdkDemoStack",
                    "DisableRollback": false,
                    "Tags": [
                            {
                                    "Value": "rg-acfm2xwmdg****",
                                    "Key": "acs:rm:rgId"
                            }
                    ],
                    "StackId": "218f0db0-7992-4e70-a586-12****",
                    "TimeoutInMinutes": 20
            }
    ]
  • Query output information of a stack

    Run the following command to query output information of a stack:

    ros-cdk output CdkDemoStack

    The following content is returned after you run the command:

      ✅ The Stack CdkDemoStack 
     Output is: 
     [
            {
                    "Description": "No description given",
                    "OutputKey": "BucketDomainName",
                    "OutputValue": "bestros.oss-cn-beijing.aliyuncs.com"
            }
    ]
  • Delete a stack
    1. Run the following command to delete a stack:
      ros-cdk destroy
    2. Confirm the deletion operation.
      Please confirm.(Y/N)
      y

      The following content is returned after you run the command:

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