杰瑞科技汇

Python如何连接阿里云ECS?

Of course! Using Python with Alibaba Cloud Elastic Compute Service (ECS) is a common and powerful way to automate your cloud infrastructure. The primary tool for this is the Alibaba Cloud Python SDK, which allows you to programmatically create, manage, and monitor your ECS instances, disks, VPCs, and more.

Python如何连接阿里云ECS?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything from setup to practical examples.


Prerequisites

Before you start, make sure you have the following:

  1. Alibaba Cloud Account: An active account on the Alibaba Cloud platform.
  2. AccessKey Pair: This is your programmatic identity for API access.
    • Go to the RAM (Resource Access Management) Console.
    • Create a new user if you haven't already.
    • Generate an AccessKey ID and AccessKey Secret. Treat your AccessKey Secret like a password and never expose it in client-side code or commit it to version control.
  3. Python Environment: Python 3.6 or higher installed on your machine.
  4. Region ID: The ID of the Alibaba Cloud region where you want to create resources (e.g., cn-hangzhou, us-west-1).

Installation

First, you need to install the Alibaba Cloud Python SDK. The core library is aliyun-python-sdk-core, and for ECS, you'll need aliyun-python-sdk-ecs.

Open your terminal or command prompt and run:

Python如何连接阿里云ECS?-图2
(图片来源网络,侵删)
pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-ecs

Configuration and Authentication

The SDK needs to know your credentials and the region you're working with. The recommended way is to use an environment file.

Create a file named .env in your project directory:

.env

ALIYUN_ACCESS_KEY_ID=your_access_key_id
ALIYUN_ACCESS_KEY_SECRET=your_access_key_secret
ALIYUN_REGION_ID=cn-hangzhou

Now, you can write a small helper function to initialize the AcsClient (the main client for interacting with Alibaba Cloud services).

Python如何连接阿里云ECS?-图3
(图片来源网络,侵删)
# config.py
import os
from aliyunsdkcore.client import AcsClient
def get_client():
    """Initializes and returns an AcsClient."""
    access_key_id = os.getenv("ALIYUN_ACCESS_KEY_ID")
    access_key_secret = os.getenv("ALIYUN_ACCESS_KEY_SECRET")
    region_id = os.getenv("ALIYUN_REGION_ID")
    if not all([access_key_id, access_key_secret, region_id]):
        raise ValueError("Missing one or more required environment variables: ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET, ALIYUN_REGION_ID")
    return AcsClient(access_key_id, access_key_secret, region_id)

Practical Examples

Let's dive into common tasks. Each example will follow this pattern:

  1. Import necessary modules.
  2. Create an AcsClient.
  3. Create a request object.
  4. Set parameters on the request object.
  5. Send the request and get a response.

Example 1: List All ECS Instances

This is a great starting point to verify your setup.

# list_instances.py
from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import json
# Initialize the client
client = AcsClient(
    "<your-access-key-id>",
    "<your-access-key-secret>",
    "cn-hangzhou"  # Replace with your region
)
# Create a CommonRequest object
request = CommonRequest()
request.set_product("Ecs")
request.set_domain("ecs.cn-hangzhou.aliyuncs.com") # Region-specific domain
request.set_version("2025-05-26")
request.set_action_name("DescribeInstances")
# Optional: Add parameters to filter the results
# request.add_query_param("RegionId", "cn-hangzhou")
# request.add_query_param("InstanceType", "ecs.g6.large")
try:
    # Send the request and get the response
    response = client.do_action_with_exception(request)
    # The response is a JSON string, so we parse it
    response_dict = json.loads(response.decode('utf-8'))
    # Print the instance IDs and names
    if "Instances" in response_dict and "Instance" in response_dict["Instances"]:
        instances = response_dict["Instances"]["Instance"]
        print(f"Found {len(instances)} instance(s):")
        for instance in instances:
            print(f"  - ID: {instance['InstanceId']}, Name: {instance['InstanceName']}, Status: {instance['Status']}")
    else:
        print("No instances found.")
except ServerException as e:
    print(f"Server Error: {e}")
except ClientException as e:
    print(f"Client Error: {e}")

Example 2: Create a New ECS Instance

This is a more complex example as it requires several parameters. Warning: Creating an instance will incur costs.

# create_instance.py
from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import json
# Initialize the client
client = AcsClient(
    "<your-access-key-id>",
    "<your-access-key-secret>",
    "cn-hangzhou"
)
# Create a CommonRequest object
request = CommonRequest()
request.set_product("Ecs")
request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
request.set_version("2025-05-26")
request.set_action_name("RunInstances")
# --- Set parameters for the instance ---
# You can find these values in the Alibaba Cloud Console
request.add_query_param("RegionId", "cn-hangzhou")
request.add_query_param("ImageId", "ubuntu_20_04_x64_20G_alibase_20251221.vhd") # An Ubuntu 20.04 image ID
request.add_query_param("InstanceType", "ecs.g6.large") # Instance type
request.add_query_param("SecurityGroupId", "sg-xxxxxxxxxxxxx") # Your security group ID
request.add_query_param("VSwitchId", "vsw-xxxxxxxxxxxxx") # Your VSwitch ID
request.add_query_param("InternetMaxBandwidthOut", "10") # Bandwidth in Mbps
request.add_query_param("InstanceName", "My-Python-Created-Instance")
request.add_query_param("Password", "YourStrongPassword123!") # Password for the instance
try:
    response = client.do_action_with_exception(request)
    response_dict = json.loads(response.decode('utf-8'))
    instance_id = response_dict['InstanceId']
    print(f"Successfully created instance with ID: {instance_id}")
    print("Please wait a few minutes for the instance to enter the 'Running' state.")
except ServerException as e:
    print(f"Server Error: {e}")
except ClientException as e:
    print(f"Client Error: {e}")

Example 3: Start, Stop, and Delete an Instance

# manage_instance.py
from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import json
# Initialize the client
client = AcsClient(
    "<your-access-key-id>",
    "<your-access-key-secret>",
    "cn-hangzhou"
)
# --- Function to manage instance state ---
def manage_instance(instance_id, action):
    request = CommonRequest()
    request.set_product("Ecs")
    request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
    request.set_version("2025-05-26")
    request.set_action_name(action) # "StartInstance", "StopInstance", or "DeleteInstance"
    request.add_query_param("RegionId", "cn-hangzhou")
    request.add_query_param("InstanceId", instance_id)
    try:
        response = client.do_action_with_exception(request)
        response_dict = json.loads(response.decode('utf-8'))
        print(f"Successfully initiated {action} for instance {instance_id}.")
        print(f"Request ID: {response_dict.get('RequestId')}")
    except (ServerException, ClientException) as e:
        print(f"Error during {action}: {e}")
# --- Main execution ---
INSTANCE_ID = "i-xxxxxxxxxxxxx" # Replace with your instance ID
if __name__ == "__main__":
    print("Starting instance...")
    manage_instance(INSTANCE_ID, "StartInstance")
    print("\nStopping instance...")
    manage_instance(INSTANCE_ID, "StopInstance")
    print("\nDeleting instance...")
    manage_instance(INSTANCE_ID, "DeleteInstance")

Best Practices

  1. Use Environment Variables: Never hardcode your AccessKey ID and Secret. Use the python-dotenv library for a cleaner way to manage your .env file.

    pip install python-dotenv

    Then in your script:

    from dotenv import load_dotenv
    import os
    load_dotenv() # Load variables from .env file
    access_key_id = os.getenv("ALIYUN_ACCESS_KEY_ID")
  2. Use Infrastructure as Code (IaC): For complex deployments, consider using a dedicated IaC tool like Terraform or Ansible. They provide a more declarative and maintainable way to manage your cloud resources. The Python SDK is excellent for custom automation scripts, while IaC tools are better for defining entire environments.

  3. Error Handling: Always wrap your API calls in try...except blocks to handle potential ServerException (e.g., insufficient permissions) and ClientException (e.g., invalid parameter).

  4. Pagination: The Describe* API calls often return results in pages. If you have many resources, you'll need to handle pagination by using the NextToken parameter in subsequent requests. The SDK provides a RoaRequest object that can simplify this, but for CommonRequest, you must implement it manually.


Official Resources

分享:
扫描分享到社交APP
上一篇
下一篇