All Products
Search
Document Center

Resource Orchestration Service:SDK call example

Last Updated:Apr 21, 2025

Alibaba Cloud SDKs simplify the process of using programming languages in Resource Orchestration Service (ROS) to define and deploy cloud resources. The programming languages include Java, TypeScript, Go, Python, PHP, C++, C#, Node.js, and Swift. This topic describes how to use Alibaba Cloud SDKs to call ROS API operations.

Note

For more information, see Alibaba Cloud SDKs.

View the API documentation

Before you call an API operation, we recommend that you read the API documentation to familiarize yourself with the parameters and permissions that are required to call the API operation. For more information, see List of operations by function.

Before you begin

  1. Obtain the information about the AccessKey pair.

    Obtain the information about the AccessKey pair of the current account to configure credentials. For more information, see View the information about AccessKey pairs of a RAM user. If no AccessKey pair is created within the account, create an AccessKey pair. For more information, see Create an AccessKey pair for a RAM user.

    Important

    To prevent security risks caused by AccessKey pair leaks of your Alibaba Cloud account, we recommend that you create a Resource Access Management (RAM) user, grant the RAM user the access permissions on ROS, and then use the AccessKey pair of the RAM user to call SDKs. For more information, see Grant permissions to a RAM role.

    If you are not familiar with AccessKey pairs and want to use SDKs, you can create and grant permissions to a RAM user that is used only to call API operations.

    1. Create a RAM user.

      1. Go to the Users page in the RAM console and click Create User.

      2. Specify the Logon Name parameter and set the Access Mode parameter to Using permanent AccessKey to access.

      3. Click OK and save the values in the AccessKey ID and AccessKey Secret columns.

        Important

        The AccessKey secret of a RAM user is displayed only when the RAM user is created. You cannot view the AccessKey secret after the RAM user is created. Store the AccessKey secret in a secure location.

      image

    2. Grant permissions to the RAM user.

      1. Go to the Users page, find the created RAM user, and then click Add Permissions in the Actions column on the right side.

      2. In the Policy section, enter ROS in the search box to search for the AliyunROSFullAccess policy.

        Important

        If system policies do not meet your requirements, we recommend that you create a custom policy based on the principle of least privilege. For more information, see Create a custom policy on the Visual editor tab.

        image

        • AliyunROSFullAccess: This policy grants the management permissions on ROS.

        • AliyunROSReadOnlyAccess: This policy grants the read-only permissions on ROS.

      3. Click Grant permissions.

  2. Configure a credential.

    To prevent security risks caused by the hard coding of AccessKey pairs into your business code, we recommend that you manage AccessKey pairs by using a specific method. In this example, environment variables are configured to manage an AccessKey pair.

    Linux and macOS

    Use the export command

    Important

    The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of your OS.

    • Configure the environment variables of your AccessKey ID and AccessKey secret.

      # Replace <ACCESS_KEY_ID> with your AccessKey ID. 
      export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
      # Replace <ACCESS_KEY_SECRET> with your AccessKey secret. 
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>
    • Check whether the environment variables are configured.

      Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the valid AccessKey ID is returned, the environment variables are configured.

    Windows

    Use GUI
    • Procedure

      If you want to use GUI to configure environment variables in Windows 10, perform the following steps:

      On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.

      Variable

      Example

      AccessKey ID

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

      • Variable value: LTAI****************

      AccessKey Secret

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

      • Variable value: yourAccessKeySecret

    • Check whether the configuration is successful.

      On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

Install the runtime environment and SDK dependencies

To meet the runtime environment, you must install the required version of the programming language and configure the ROS SDK dependencies.

You can configure the environment and SDK dependencies based on your programming language in OpenAPI Explorer. The following figure shows the sample operations.

image

Use Alibaba Cloud SDKs

This section provides an example on how to use Alibaba Cloud SDKs to call ROS API operations. In this example, the ListStacks operation that you can call to query stacks is used.

Generate or write code

Generate code

You can use OpenAPI Explorer to generate code and download the code to call the API operation.

  1. Go to the ROS API debugging page in OpenAPI Explorer.

  2. Select the API operation that you want to use, specify the parameters, and then click Initiate Call. In this example, the ListStacks operation is selected.

  3. On the SDK Sample Code tab, select Python as the language. Click Download Project to download the sample code package of the SDK for Python.

  4. Decompress the sample code package on your computer and go to the alibabacloud_sample directory.

image

Write code

You can refer to the ListStacks API documentation to write custom code and call the API operation.

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
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_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> ROS20190910Client:
        """
        Use your AccessKey ID and AccessKey secret to initialize a client.
        @return: Client
        @throws Exception
        """
        # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is provided for reference only.
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is specified in the code. ,
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is specified in the code. ,
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # Specify the endpoint of ROS. For more information, see https://api.aliyun.com/product/ROS.
        config.endpoint = f'ros.aliyuncs.com'
        return ROS20190910Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        list_stacks_request = ros20190910_models.ListStacksRequest(
            region_id='cn-hangzhou'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # Print the return values of the API operation based on your business requirements after you copy and run the code.
            client.list_stacks_with_options(list_stacks_request, runtime)
        except Exception as error:
            # Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, an error message is printed for reference only. 
            # Print an error message.
            print(error.message)
            # Display information for troubleshooting.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        list_stacks_request = ros20190910_models.ListStacksRequest(
            region_id='cn-hangzhou'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # Print the return values of the API operation based on your business requirements after you copy and run the code.
            await client.list_stacks_with_options_async(list_stacks_request, runtime)
        except Exception as error:
            # Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, an error message is printed for reference only. 
            # Print an error message.
            print(error.message)
            # Display information for troubleshooting.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:]) 

Run code

After you run the code, the following output is returned:

{
  "TotalCount": 1,
  "PageSize": 10,
  "RequestId": "692E6895-AEFC-550C-B968-AE929BB68891",
  "PageNumber": 1,
  "Stacks": [
    {
      "Status": "IMPORT_CREATE_COMPLETE",
      "OperationInfo": {},
      "ResourceGroupId": "rg-acfmz7hmshz****",
      "ServiceManaged": false,
      "StatusReason": "Stack IMPORT_CREATE completed successfully",
      "CreateTime": "2023-06-26T09:40:26",
      "StackType": "ROS",
      "RegionId": "cn-hangzhou",
      "DisableRollback": false,
      "StackName": "TemplateScratch-ResourceImport-wffTp****",
      "Tags": [
        {
          "Value": "rg-acfmz7hmshzcriy",
          "Key": "acs:rm:rgId"
        }
      ],
      "TimeoutInMinutes": 60,
      "StackId": "814d2113-348c-41f1-adb2-85d3aadf****"
    }
  ]
}