全部產品
Search
文件中心

:Python SDK使用樣本

更新時間:Jan 05, 2024

本文為您介紹Resource Orchestration Service服務ROS(Resource Orchestration Service)的Python SDK安裝方法和範例程式碼。以查詢可用地區列表、建立資源棧、查詢資源棧、刪除資源棧等操作為例,協助您快速掌握Resource Orchestration Service介面的使用方法。

安裝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
      from alibabacloud_credentials.client import Client as CredClient
    2. 初始化SDK用戶端對象。

      def create_client(
      ) -> ROS20190910Client:
          """
          初始化帳號Client。
          @return: Client
          @throws Exception
          """
          cred = CredClient()
          config = open_api_models.Config(
              credential=cred
          )
          # 訪問的網域名稱。
          config.endpoint = 'ros.aliyuncs.com'
      
          return ROS20190910Client(config)
      
      
      client = create_client()

樣本

  • 查詢可用地區列表示例

    通過調用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:建立的資源棧所需要的參數。需要同時指定parameter_key和parameter_value。

    參數設定的範例程式碼如下所示。

    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

    在本樣本中,指定了以下參數:

    • region_id:資源棧所屬的地區ID。

    • stack_id:資源棧ID。

  • 參數設定的範例程式碼如下所示。

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

    在本樣本中,指定了以下參數:

    • region_id:資源棧所屬的地區ID。

    • stack_id:資源棧ID。

  • 參數設定的範例程式碼如下所示。

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
  • 完整樣本

    以下為查詢可用地區列表、建立資源棧、查詢資源棧和刪除資源棧的完整操作樣本。

    說明

    調用介面前,需先配置環境變數,通過環境變數讀取存取憑證。更多資訊,請參見配置訪問憑證

    AccessKey ID和AccessKey Secret的環境變數名:ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_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'  # 例如:'cn-beijing'、'cn-hangzhou'。
    
    
    def create_client(
    ) -> ROS20190910Client:
        """
        初始化帳號Client。
        @return: Client
        @throws Exception
        """
        cred = CredClient()
        config = open_api_models.Config(
            credential=cred
        )
        # 訪問的網域名稱。
        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,
            # 若模板較大,建議使用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)