All Products
Search
Document Center

Elastic Compute Service:Use ECS SDK V2.0 for Python

Last Updated:Jan 30, 2026

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

  1. The AccessKey of an Alibaba Cloud account provides full access to your resources, which poses a high security risk if the AccessKey is leaked. We recommend that you create a Resource Access Management (RAM) user and grant the RAM user only the required permissions. Then, use the AccessKey of the RAM user to call API operations. For more information, see Create an AccessKey.

  2. You have granted the RAM user permissions to manage ECS resources. The example code in this topic shows a query operation. In this example, the AliyunECSReadonlyAccess system policy is used. You can grant custom permissions as needed.

    1. Use custom policies.

      For more information about how to create custom policies, see Create a custom policy and Authorization information.

      ECS provides custom policy examples based on best practices. You can use these examples to quickly create custom policies that meet your business needs. For more information, see Custom policies.

    2. Use system policies.

      For information about all system policies that ECS supports and their permission descriptions, see System policies for ECS.

  3. Configure the AccessKey using environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

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.

Note

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 settings.

Note

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.