本文为您介绍资源编排服务ROS(Resource Orchestration Service)的Python SDK安装方法和示例代码。

安装Python SDK

  1. 下载及安装Python SDK。
    说明 Python SDK下载和使用说明,请参见SDK概览
  2. 初始化SDK。
    1. 导入相关的软件包。
      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
    2. 初始化SDK客户端对象。
      def create_client(
              access_key_id: str,
              access_key_secret: str,
      ) -> ROS20190910Client:
          """
          使用AccessKey初始化账号Client。
          @param access_key_id:
          @param access_key_secret:
          @return: Client
          @throws Exception
          """
          config = open_api_models.Config(
              # 您的AccessKey ID。
              access_key_id=access_key_id,
              # 您的AccessKey Secret。
              access_key_secret=access_key_secret,
          )
          # 访问的域名。
          config.endpoint = 'ros.aliyuncs.com'
          return ROS20190910Client(config)
      
      
      client = create_client(AK, SECRET) 

示例

  • 查询可用地域列表示例

    通过调用DescribeRegions接口查询可用地域列表。关于DescribeRegions接口的详情,请参见DescribeRegions

    def describe_region():
        """describe regions list """
        describe_regions_request = ros20190910_models.DescribeRegionsRequest()
        response = client.describe_regions(describe_regions_request)
    
        return response
  • 创建资源栈示例

    通过调用CreateStack接口创建资源栈。关于CreateStack接口的详情,请参见CreateStack

    在本示例中,指定了以下参数:

    • region_id:资源栈所属的地域ID。
    • stack_name:资源栈名称。同一阿里云账号中资源栈名称不能重复。
    • timeout_in_minutes:创建资源栈的超时时间,单位为分钟。如果在指定时间内不能完成创建,则资源栈创建失败。
    • template_body:模板的主体结构。
    • parameters:创建的资源栈所需要的参数。需要同时指定ParameterKey和ParameterValue。

    参数设置的示例代码如下:

    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'
            )
        ]
    创建资源栈的示例代码如下:
    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,
            # 若模板较大,建议使用TemplateURL参数,避免URL过长,调用失败。
            # 您也可以使用Body Param + HTTP POST的方式传递模板内容。
            template_body=template_body,
            timeout_in_minutes=timeout_in_minutes,
            parameters=parameters,
            disable_rollback=True
        )
        response = client.create_stack(create_stack_request)
    
        return response
  • 查询资源栈信息示例

    通过调用GetStack接口查询资源栈信息。关于GetStack接口的详情,请参见GetStack

    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
  • 删除资源栈示例

    通过调用DeleteStack接口删除资源栈。关于DeleteStack接口的详情,请参见DeleteStack

    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
  • 完整示例

    以下为查询可用地域列表、创建资源栈、查询资源栈和删除资源栈的完整操作示例。

    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
    
    AK = '<yourAccessKeyId>'
    SECRET = '<yourAccessKeySecret>'
    REGION = '<yourRegionId>'  # 例如:'cn-beijing'、'cn-hangzhou'。
    
    def create_client(
            access_key_id: str,
            access_key_secret: str,
    ) -> ROS20190910Client:
        """
        使用AccessKey初始化账号Client。
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 您的AccessKey ID。
            access_key_id=access_key_id,
            # 您的AccessKey Secret。
            access_key_secret=access_key_secret,
        )
        # 访问的域名。
        config.endpoint = 'ros.aliyuncs.com'
        return ROS20190910Client(config)
    
    
    client = create_client(AK, SECRET)
    
    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,
            # 若模板较大,建议使用TemplateURL参数,避免URL过长,调用失败。
            # 您也可以使用Body Param + HTTP POST的方式传递模板内容。
            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状态:{}'.format(stack.stack_id, stack_status))
            # 等待创建资源栈任务执行完毕。
            if stack_status == 'CREATE_COMPLETE':
                break
            sleep(3)
        delete_stack(region_id, stack.stack_id)