All Products
Search
Document Center

Resource Orchestration Service:SDK call examples

Last Updated:Jun 02, 2026

Alibaba Cloud SDKs for ROS simplify defining and deploying cloud resources using programming languages such as Java, TypeScript, Go, Python, PHP, C++, C#, Node.js, and Swift. Learn how to call ROS APIs with an Alibaba Cloud SDK.

Note

Alibaba Cloud SDK overview: What is an Alibaba Cloud SDK?

View OpenAPI documents

Before calling an API, review the corresponding API overview for required parameters and permissions.

Preparations

  1. Obtain AccessKey information.

    Obtain the AccessKey information for your Alibaba Cloud account to configure credentials. If you do not have an AccessKey pair, follow Create an AccessKey pair.

    Important

    To avoid security risks from leaking your root account AccessKey, create a Resource Access Management (RAM) user with ROS permissions, and use its AccessKey to call the SDK. Manage the permissions of a RAM role.

    Create and authorize a RAM user to call OpenAPI

    1. Create a RAM user.

      1. Go to the RAM user list page and click Create User.

      2. Set Logon Name, and for Access Mode, select Use Permanent AccessKey for Access.

      3. Click OK. After the RAM user is created, save the AccessKey ID and AccessKey Secret.

        Important

        The AccessKey secret for a RAM user is displayed only at the time of creation and cannot be retrieved later. Be sure to save it.

      image

    2. Grant permissions.

      1. Go to the RAM user list page. In the Actions column for the target RAM user, click Add Permissions.

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

        Important

        If the system policy does not meet your requirements, create a custom policy following the Principle of Least Privilege (PoLP). Create a custom policy on the visual editor tab.

        image

        • AliyunROSFullAccess: Grants full permissions to manage Resource Orchestration Service (ROS).

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

      3. Click OK.

  2. Configure credentials.

    To avoid hard-coding your AccessKey pair, configure environment variables instead. The following example uses environment variables.

    Linux and macOS systems

    Configure environment variables using the export command

    Important

    Environment variables set with the export command are temporary and valid only for the current session. For persistence, add the export command to your OS 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 echo $ALIBABA_CLOUD_ACCESS_KEY_ID. If the correct AccessKey ID is returned, the configuration is successful.

    Windows system

    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 the runtime environment and SDK dependencies

Install the required language runtime and configure ROS SDK dependencies.

Configure the environment and SDK dependencies for your programming language in the OpenAPI Portal.

image

Use an Alibaba Cloud SDK

The following example calls the ListStacks API using an Alibaba Cloud SDK.

Generate or write code

Generate code

Generate and download API call code from the OpenAPI Portal.

  1. Go to the API Debugging List for Resource Orchestration Service.

  2. Select an API, specify the parameters, and click Initiate Call. This example uses the ListStacks API.

  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.

image

Code Writing

Write your own code based on the API document.

# -*- 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 with an AccessKey pair.
        @return: Client
        @throws Exception
        """
        # Leaking the project code may cause the AccessKey pair to be leaked, which threatens the security of all resources in your account. The following code is for reference only.
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # For more information about the endpoint, 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:
            # When you copy the code to run, print the return value of the API.
            client.list_stacks_with_options(list_stacks_request, runtime)
        except Exception as error:
            # This is for printing and display purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
            # Error message
            print(error.message)
            # Diagnosis address
            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 the code to run, print the return value of the API.
            await client.list_stacks_with_options_async(list_stacks_request, runtime)
        except Exception as error:
            # This is for printing and display purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
            # Error message
            print(error.message)
            # Diagnosis address
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


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

Run the code

Run the code. Sample 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****"
    }
  ]
}