本文为您介绍资源编排服务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客户端对象。
      AK = '<yourAccessKeyId>'
      SECRET = '<yourAccessKeySecrect>'
      Region = '<yourRegionId>'
      client = AcsClient(AK, SECRET, Region) 

示例

  • 查询可用地域列表示例

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

    def describe_region():
        """describe regions list """
        request = DescribeRegionsRequest()
        request.set_connect_timeout(10000)
        request.set_read_timeout(10000)
        request.set_accept_format("json")
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
  • 创建资源栈示例

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

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

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

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

    stack_name = "MyStack"
    timeout = 10
    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"
                }
              }
            }
          }
        }
    """
    params = [
        {
            "ParameterValue": "192.168.0.0/16",
            "ParameterKey": "CidrBlock"
        },
        {
            "ParameterValue": "TestVpc",
            "ParameterKey": "VpcName"
        }
    ]
    创建资源栈的示例代码如下:
    def create_stack():
        """create stack"""
        request = CreateStackRequest()
        request.set_accept_format("json")
        request.set_StackName(stack_name)
        request.set_TimeoutInMinutes(timeout)
        # 如果模板较大,建议使用TemplateURL参数。
        # 您也可以使用Body Param + HTTP POST的方式传递模板内容,避免因URL过长,而导致请求失败。
        # request.set_method("POST")
        # request.add_body_params("TemplateBody", template_body)
        request.set_TemplateBody(template_body)
        request.set_Parameterss(params)
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
  • 查询资源栈信息示例

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

    def get_stack():
        """get descriptions of the stack"""
        request = GetStackRequest()
        request.set_accept_format("json")
        request.set_StackId(stack_id)
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
  • 删除资源栈示例

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

    def delete_stack():
        """delete stack"""
        request = DeleteStackRequest()
        request.set_accept_format("json")
        request.set_StackId(stack_id)
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
  • 完整示例

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

    import json
    from time import sleep
    from aliyunsdkcore.client import AcsClient
    from aliyunsdkros.request.v20190910.CreateStackRequest import CreateStackRequest
    from aliyunsdkros.request.v20190910.GetStackRequest import GetStackRequest
    from aliyunsdkros.request.v20190910.DeleteStackRequest import DeleteStackRequest
    from aliyunsdkros.request.v20190910.DescribeRegionsRequest import DescribeRegionsRequest
    from aliyunsdkros.request.v20190910.ListStacksRequest import ListStacksRequest
    
    
    AK = '<yourAccessKeyId>'
    SECRET = '<yourAccessKeySecret>'
    Region = '<yourRegionId>'  # 例如:'cn-beijing'、'cn-hangzhou'。
    
    client = AcsClient(AK, SECRET, Region)
    
    
    def describe_region():
        """describe regions list """
        request = DescribeRegionsRequest()
        request.set_connect_timeout(10000)
        request.set_read_timeout(10000)
        request.set_accept_format("json")
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
    
    
    def create_stack(stack_name, timeout, template_body, params=[]):
        """create stack"""
        request = CreateStackRequest()
        request.set_accept_format("json")
        request.set_StackName(stack_name)
        request.set_TimeoutInMinutes(timeout)
        # 如果模板较大,建议使用TemplateURL参数。
        # 您也可以使用Body Param + HTTP POST的方式传递模板内容,避免因URL过长,而导致请求失败。
        # request.set_method("POST")
        # request.add_body_params("TemplateBody", template_body)
        request.set_TemplateBody(template_body)
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
    
    
    def get_stack(stack_id):
        """get descriptions of the stack"""
        request = GetStackRequest()
        request.set_accept_format("json")
        request.set_StackId(stack_id)
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
    
    
    def delete_stack(stack_id):
        """delete stack"""
        request = DeleteStackRequest()
        request.set_accept_format("json")
        request.set_StackId(stack_id)
        response = client.do_action_with_exception(request)
    
        return response.decode("utf-8")
    
    
    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 = [
            {"ParameterKey": "CidrBlock", "ParameterValue": "192.168.0.0/16"},
            {"ParameterKey": "VpcName", "ParameterValue": "TestVpc"}
        ]
    
        describe_region()
        stack = create_stack('MyStack', 10, test_template, parameters)
        get_stack(json.loads(stack)["StackId"])
        sleep(3)  # 等待创建资源栈任务执行完毕。
        delete_stack(json.loads(stack)["StackId"])