All Products
Search
Document Center

Resource Orchestration Service:Use ROS SDK for Python

Last Updated:Jan 05, 2024

This topic describes how to install Resource Orchestration Service (ROS) SDK for Python. This topic also provides sample code that you can run to use ROS SDK for Python. The sample code provides examples on how to query a list of available regions, and create, query, and delete a stack by using specific ROS API operations. This way, you can quickly familiarize yourself with the method to use the ROS API operations.

Install ROS SDK for Python

  1. Download and install ROS SDK for Python.

    Note

    For more information about how to download and use ROS SDK for Python, see SDK overview.

  2. Initialize ROS SDK for Python.

    1. Import the required software packages.

      import sys
      from typing import List
      from alibabacloud_ros20190910.client import Client as ROS20190910Client
      from alibabacloud_tea_openapi import models as open_api_models
      from alibabacloud_ros20190910 import models as ros20190910_models
      from alibabacloud_credentials.client import Client as CredClient
    2. Initialize the SDK client.

      def create_client(
      ) -> ROS20190910Client:
          """
          Initialize the client. 
          @return: Client
          @throws Exception
          """
          cred = CredClient()
          config = open_api_models.Config(
              credential=cred
          )
          # Specify the endpoint of ROS. 
          config.endpoint = 'ros.aliyuncs.com'
      
          return ROS20190910Client(config)
      
      
      client = create_client()

Examples

  • Query a list of available regions

    You can call the DescribeRegions operation to query a list of available regions. For more information, see DescribeRegions.

    def describe_region():
        """describe regions list """
        describe_regions_request = ros20190910_models.DescribeRegionsRequest()
        response = client.describe_regions(describe_regions_request)
    
        return response
  • Create a stack

    You can call the CreateStack operation to create a stack. For more information, see CreateStack.

    In this example, the following parameters are specified:

    • region_id: the region ID of the stack.

    • stack_name: the stack name. The name must be unique within an Alibaba Cloud account.

    • timeout_in_minutes: the timeout period for creating the stack. Unit: minutes. If a stack is not created within the specified period of time, the stack fails to be created.

    • template_body: the template body.

    • parameters: the parameters that are required to create the stack. You must specify parameter_key and parameter_value.

    The following sample code provides an example on how to specify the parameters:

    stack_name = "MyStack"
    region_id = "cn-shenzhen"
    timeout = 60
    template_body = """
        {
          "ROSTemplateFormatVersion": "2015-09-01",
          "Parameters": {
            "VpcName": {
              "Type": "String",
              "Description": "Vpc Name",
              "Label": "Vpc Name"
            },
            "CidrBlock": {
              "Type": "String",
              "Description": "Vpc CidrBlock",
              "Label": "Vpc CidrBlock"
             }
            },
          "Resources": {
            "Vpc": {
              "Type": "ALIYUN::ECS::VPC",
              "Properties": {
                "CidrBlock": {
                  "Ref": "CidrBlock"
                },
                "VpcName": {
                  "Ref": "VpcName"
                }
              }
            }
          }
        }
    """
    parameters = [
            ros20190910_models.CreateStackRequestParameters(
                parameter_key='CidrBlock',
                parameter_value='192.168.0.0/16'
            ),
            ros20190910_models.CreateStackRequestParameters(
                parameter_key='VpcName',
                parameter_value='TestVpc'
            )
        ]

    The following sample code provides an example on how to create a stack:

    def create_stack(region_id, stack_name, template_body, timeout_in_minutes=40, parameters=[]):
        """create stack"""
        create_stack_request = ros20190910_models.CreateStackRequest(
            region_id=region_id,
            stack_name=stack_name,
            # If the length of the template body exceeds the upper limit, we recommend that you use the TemplateURL parameter to prevent request failures caused by excessively long URLs. 
            # You can also add parameters to the HTTP POST request body. 
            template_body=template_body,
            timeout_in_minutes=timeout_in_minutes,
            parameters=parameters,
            disable_rollback=True
        )
        response = client.create_stack(create_stack_request)
    
        return response
  • Query the information about a stack

    You can call the GetStack operation to query information about a stack. For more information, see GetStack.

    In this example, the following parameters are specified:

    • region_id: the region ID of the stack.

    • stack_id: the stack ID.

  • The following sample code provides an example on how to query the information about a stack:

def get_stack(region_id, stack_id):
    """get descriptions of the stack"""
    get_stack_request = ros20190910_models.GetStackRequest(
        region_id=region_id,
        stack_id=stack_id,
    )
    response = client.get_stack(get_stack_request)
    return response
  • Delete a stack

    You can call the DeleteStack operation to delete a stack. For more information, see DeleteStack.

    In this example, the following parameters are specified:

    • region_id: the region ID of the stack.

    • stack_id: the stack ID.

  • The following sample code provides an example on how to delete a stack:

def delete_stack(region_id, stack_id):
    """delete stack"""
    delete_stack_request = ros20190910_models.DeleteStackRequest(
        region_id=region_id,
        stack_id=stack_id,
    )
    response = client.delete_stack(delete_stack_request)
    return response
  • Complete sample code

    The following sample code provides an example on how to query a list of available regions and how to create, query, and delete a stack:

    Note

    Before you call the operation, you must configure environment variables and obtain access credentials from the environment variables. For more information, see Configure access credentials.

    The environment variables of the AccessKey ID and the AccessKey secret are ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.

    from time import sleep
    from alibabacloud_ros20190910.client import Client as ROS20190910Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_ros20190910 import models as ros20190910_models
    from alibabacloud_credentials.client import Client as CredClient
    
    REGION = 'cn-shenzhen'  # Examples: 'cn-beijing' and 'cn-hangzhou'. 
    
    
    def create_client(
    ) -> ROS20190910Client:
        """
        Initialize the client. 
        @return: Client
        @throws Exception
        """
        cred = CredClient()
        config = open_api_models.Config(
            credential=cred
        )
        # Specify the endpoint of ROS. 
        config.endpoint = 'ros.aliyuncs.com'
    
        return ROS20190910Client(config)
    
    
    client = create_client()
    
    
    def describe_region():
        """describe regions list """
        describe_regions_request = ros20190910_models.DescribeRegionsRequest()
        response = client.describe_regions(describe_regions_request)
    
        return response
    
    
    def create_stack(region_id, stack_name, template_body, timeout_in_minutes=40, parameters=[]):
        """create stack"""
        create_stack_request = ros20190910_models.CreateStackRequest(
            region_id=region_id,
            stack_name=stack_name,
            # If the length of the template body exceeds the upper limit, we recommend that you use the TemplateURL parameter to prevent request failures caused by excessively long URLs. 
            # You can also add parameters to the HTTP POST request body. 
            template_body=template_body,
            timeout_in_minutes=timeout_in_minutes,
            parameters=parameters,
            disable_rollback=True
        )
        response = client.create_stack(create_stack_request)
    
        return response.body
    
    
    def get_stack(region_id, stack_id):
        """get descriptions of the stack"""
        get_stack_request = ros20190910_models.GetStackRequest(
            region_id=region_id,
            stack_id=stack_id,
        )
        response = client.get_stack(get_stack_request)
        return response.body
    
    
    def delete_stack(region_id, stack_id):
        """delete stack"""
        delete_stack_request = ros20190910_models.DeleteStackRequest(
            region_id=region_id,
            stack_id=stack_id,
        )
        response = client.delete_stack(delete_stack_request)
        return response.body
    
    
    if __name__ == '__main__':
        test_template = """
            {
              "ROSTemplateFormatVersion": "2015-09-01",
              "Parameters": {
                "VpcName": {
                  "Type": "String",
                  "Description": "Vpc Name",
                  "Label": "Vpc Name"
                },
                "CidrBlock": {
                  "Type": "String",
                  "Description": "Vpc CidrBlock",
                  "Label": "Vpc CidrBlock"
                 }
                },
              "Resources": {
                "Vpc": {
                  "Type": "ALIYUN::ECS::VPC",
                  "Properties": {
                    "CidrBlock": {
                      "Ref": "CidrBlock"
                    },
                    "VpcName": {
                      "Ref": "VpcName"
                    }
                  }
                }
              }
            }
        """
    
        parameters = [
            ros20190910_models.CreateStackRequestParameters(
                parameter_key='CidrBlock',
                parameter_value='192.168.0.0/16'
            ),
            ros20190910_models.CreateStackRequestParameters(
                parameter_key='VpcName',
                parameter_value='TestVpc'
            )
        ]
        region_id = REGION
        describe_region()
        stack = create_stack(region_id, 'MyStack', test_template, parameters=parameters, timeout_in_minutes=60)
        stack_status = None
        while True:
            stack_info = get_stack(region_id, stack.stack_id)
            stack_status = stack_info.status
            print('Stack Id: {}, Stack status: {}'.format(stack.stack_id, stack_status))
            # Wait until the stack is created. 
            if stack_status == 'CREATE_COMPLETE':
                break
            sleep(3)
        delete_stack(region_id, stack.stack_id)