This topic describes how to install Elastic Compute Service (ECS) SDK V2.0 for Python and provides an example on how to use the SDK to call ECS API operations. In the example, ECS SDK V2.0 for Python is used to call the DescribeInstances operation to query information about ECS instances.
Prerequisites
A Resource Access Management (RAM) user with the minimum required permissions is logged on using its AccessKey pair. We do not recommend that you use Alibaba Cloud account because it has full permissions and its AccessKey pair is a significant security risk if compromised. For more information about creating an AccessKey pair, see Create an AccessKey pair.
The RAM user is authorized to manage ECS resources. This example requires read-only access, and the AliyunECSReadonlyAccess system policy is used. Authorize permissions according to your business requirements.
Create a custom policy.
For guidance on creating a custom policy, see Create custom policies and RAM authorization.
ECS offers custom policy templates based on best practices. Refer to those policy templates to quickly establish policies based on your needs. For more information, see Custom policies for ECS.
Use system policies.
For more information about ECS-supported system policies and their permissions, see System policies for ECS.
An AccessKey pair is configured in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.
Install ECS SDK V2.0 for Python
For information about how to install ECS SDK V2.0 for Python, visit SDK Center. You can copy the following command and run the command in the terminal to install ECS SDK V2.0 for Python:
pip install alibabacloud_ecs20140526
Use ECS SDK V2.0 for Python
1. Initialize a client.
Alibaba Cloud SDKs support multiple access credentials, such as AccessKey pairs and Security Token Service (STS) tokens, to initialize clients. For more information, see Manage access credentials. In this example, an AccessKey pair is used to initialize a client.
import os
from alibabacloud_tea_openapi.models import Config
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Ecs20140526Client:
config = Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint='ecs.cn-hangzhou.aliyuncs.com'
)
return Ecs20140526Client(config)
2. Create a request object for the API operation.
Before you create a request object, view the parameters of the API operation that you want to call. In this example, the DescribeInstances operation is used. You can view the parameters of the DescribeInstances operation in DescribeInstances.
The name of a request object is in the {Operation name}Request format. For example, the request object for the DescribeInstances operation is named DescribeInstancesRequest.
3. Create a request object.
describe_instances_request = ecs_20140526_models.DescribeInstancesRequest(
region_id='cn-hangzhou'
)
3. Call the API operation.
When you call an API operation from a client, you can specify runtime parameters, such as timeout parameters and proxy parameters. For more information, see Advanced configuration.
The name of a response object is in the {Operation name}Response format. For example, the response object for the DescribeInstances operation is named DescribeInstancesResponse.
# Specify runtime parameters.
runtime = util_models.RuntimeOptions()
# Call the DescribeInstances operation.
describe_instances_response = client.describe_instances_with_options(describe_instances_request, runtime)
4. Handle exceptions.
ECS SDK for Python classifies exceptions into the following types:
UnretryableException: This type of exception is caused by network issues. In most cases, an UnretryableException exception is thrown when the maximum number of retries is reached.
TeaException: In most cases, this type of exception is caused by business errors.
We recommend that you properly handle exceptions by performing operations, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.
5. Complete sample code.
import os
from Tea.exceptions import UnretryableException, TeaException
from alibabacloud_tea_openapi.models import Config
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
from alibabacloud_tea_util import models as util_models
from alibabacloud_ecs20140526 import models as ecs_20140526_models
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Ecs20140526Client:
config = Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint='ecs.cn-hangzhou.aliyuncs.com'
)
return Ecs20140526Client(config)
@staticmethod
def main():
client = Sample.create_client()
# Create a request object.
describe_instances_request = ecs_20140526_models.DescribeInstancesRequest(
region_id='cn-hangzhou'
)
# Specify runtime parameters.
runtime = util_models.RuntimeOptions()
try:
# Call the DescribeInstances operation.
describe_instances_response = client.describe_instances_with_options(describe_instances_request, runtime)
print(describe_instances_response.body)
except UnretryableException as e:
# Network exceptions. Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided only for reference.
print(e)
except TeaException as e:
# Business exceptions. Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided only for reference.
print(e)
except Exception as e:
# Other exceptions. Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided only for reference.
print(e)
if __name__ == '__main__':
Sample.main()
References
You can also use ECS SDK V2.0 for Python to perform generic calls to ECS API operations. For more information, see Generic calls.
If you use ECS SDK V1.0 for Python, see V1.0 Python SDK for information about the SDK.