All Products
Search
Document Center

Resource Orchestration Service:SDK call example

Last Updated:Aug 20, 2026

The Alibaba Cloud SDK for Resource Orchestration Service (ROS) simplifies defining and deploying cloud resources by using programming languages such as Java, TypeScript, Go, Python, PHP, C++, C#, Node.js, and Swift. This topic explains how to use an Alibaba Cloud SDK to call ROS API operations.

Note

For more information about Alibaba Cloud SDKs, see What is Alibaba Cloud SDK?

API documentation

Before you call an API operation, review its documentation to understand the required parameters and permissions. For more information, see API overview.

Before you begin

  1. Obtain an AccessKey pair.

    Obtain the AccessKey information for the current account to configure credentials. If you have not created an AccessKey, see Create an AccessKey.

    Important

    To prevent security risks from a leaked AccessKey pair for your Alibaba Cloud account, we recommend creating a RAM user, granting it permissions for ROS, and then using the RAM user's AccessKey pair for API calls. For more information, see Manage permissions for a RAM role.

    If you are unfamiliar with AccessKey pairs and want to start using the SDK quickly, follow these steps to create a RAM user and grant it the necessary permissions.

    1. Create a RAM user.

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

      2. Specify the Logon Name. For Access Mode, select Using permanent AccessKey to access.

      3. Click OK to create the RAM user, and then save the AccessKey ID and AccessKey Secret.

        Important

        The AccessKey Secret for a RAM user is displayed only upon creation and cannot be retrieved later. Make sure to save it in a secure location.

    2. Grant permissions.

      1. Go to the Users page. Find the target RAM user and click Add Permissions in the Actions column.

      2. In the Policy section, enter the keyword ROS in the search box, and then select the AliyunROSFullAccess policy.

        Important

        If a system policy does not meet your requirements, create a custom policy based on the principle of least privilege. For more information, see Create a custom policy in the visual editor.

        • AliyunROSFullAccess: Grants full management permissions on Resource Orchestration Service (ROS).

        • AliyunROSReadOnlyAccess: Grants read-only permissions on Resource Orchestration Service (ROS).

      3. Click OK to complete the authorization.

  2. Configure credentials.

    Hard-coding an AccessKey pair into your code is a security risk. To avoid this, use environment variables to manage your credentials. This section provides an example of how to set them.

    Linux and macOS

    Configure environment variables using the export command

    Important

    Environment variables configured with the export command are temporary and valid only for the current session. After the session ends, the environment variables are lost. To make them permanent, add the export commands to your shell's startup configuration file.

    • Configure the 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>
    • Verify the configuration.

      Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If your AccessKey ID is returned, the environment variable is configured successfully.

    Windows

    Use the graphical user interface (GUI)
    • Procedure

      The following steps describe how to set environment variables using the GUI in Windows 10.

      On your desktop, right-click This PC and choose Properties > Advanced system settings > Environment Variables > New under System variables or User variables. Then, complete the configuration.

      Variable

      Example value

      AccessKey ID

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

      • Variable value: yourAccessKeyID

      AccessKey Secret

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

      • Variable value: yourAccessKeySecret

    • Test the configuration

      Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Install runtime and SDK dependencies

To set up the runtime environment, install the correct version of your programming language and configure the ROS SDK dependencies.

Follow the instructions in OpenAPI Explorer to configure the environment and SDK dependencies for your programming language.

On the SDK > Installation page, select SDK generation version V2.0, and choose the Python language tab. The environment requires Python 3.6 or later. Run the following command to install the SDK from PyPI: pip install alibabacloud_ros20190910==3.4.3.

Use an Alibaba Cloud SDK

This section uses the ListStacks API operation to demonstrate how to call a ROS API operation with an Alibaba Cloud SDK.

Generate or write code

Generate code

You can use OpenAPI Explorer to generate and download the sample code.

  1. Log in to the ROS API debugging page.

  2. Select the desired API operation, specify the parameters, and click Initiate Call. This example uses the ListStacks operation. After the call succeeds, select the SDK Sample Code tab on the right side of the response. Choose your programming language to view the generated SDK code, and then click the Download Files button above the code to download the code.

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

  4. Extract the sample code package on your local machine and navigate to the alibabacloud_sample directory.

Write code

Alternatively, write your own code for the API call by referring to the API documentation.

# -*- 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:
        """
        Initializes a client by using an AccessKey pair.
        @return: Client
        @throws Exception
        """
        # Hard-coding your AccessKey pair in your code can lead to security risks. We recommend using environment variables or a credential management system. This sample code is for reference only.
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # For more information about the endpoint, visit https://api.alibabacloud.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:
            # When you copy and run the code, print the API return value.
            client.list_stacks_with_options(list_stacks_request, runtime)
        except Exception as error:
            # The following code is for demonstration purposes only. In a production environment, handle exceptions with care and do not ignore them.
            # Error message
            print(error.message)
            # Troubleshooting URL
            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:
            # When you copy and run the code, print the API return value.
            await client.list_stacks_with_options_async(list_stacks_request, runtime)
        except Exception as error:
            # The following code is for demonstration purposes only. In a production environment, handle exceptions with care and do not ignore them.
            # Error message
            print(error.message)
            # Troubleshooting URL
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

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

Run code

Running the code produces the following output.

{
  "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****"
    }
  ]
}