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.
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
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.
ImportantTo 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.
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
ImportantThe 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%
andecho %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.
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.
Go to the ROS API debugging page in OpenAPI Explorer.
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.
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.
Decompress the sample code package on your computer and go to the alibabacloud_sample directory.
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****"
}
]
}