search
HomeOperation and MaintenanceLinux Operation and MaintenanceHow to manage or custom develop ECS instances via API

The content of this article is about how to manage or customize the development of ECS instances through API. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Elastically manage ECS instances

Get the RAM sub-account AK key

To use the API to manage ECS instances, you need to be able to API keys (AccessKey ID and AccessKey Secret) for accessing ECS ​​resources. To ensure the security of cloud services, you need to create a RAM user that can access ECS resources, obtain the user's AccessKey, and use this RAM user and API to manage ECS instances.

The following are the steps to obtain the RAM user AccessKey:

Create a RAM user and obtain the AccessKey.

Directly authorize RAM users and grant RAM users permission to manage cloud server services (ECS).

Install ECS Python SDK

First make sure you have Python's Runtime. The Python version used in this article is 2.7.

pip install aliyun-python-sdk-ecs

If you are prompted that you do not have permission, please switch to sudo to continue execution.

sudo pip install aliyun-python-sdk-ecs

The SDK version used in this article is 2.1.2.

Hello Alibaba Cloud

Create the file hello_ecs_api.py. In order to use the SDK, first instantiate the AcsClient object, which requires the AccessKey ID and AccessKey Secret of the RAM user.

AccessKey ID and AccessKey Secret are the keys for RAM users to access the Alibaba Cloud ECS service API. They have full permissions for the account, so please keep them properly.

from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.DescribeRegionsRequest import DescribeRegionsRequest
clt = client.AcsClient('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing')

After the instantiation is completed, the first application can be developed. Query the list of regions supported by the current account. For specific documentation, see Query the list of available regions.

def hello_aliyun_regions():
    request = DescribeRegionsRequest()
    response = _send_request(request)
    region_list = response.get('Regions').get('Region')
    assert response is not None
    assert region_list is not None
    result = map(_print_region_id, region_list)
    logging.info("region list: %s", result)
def _print_region_id(item):
    region_id = item.get("RegionId")
    return region_id
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)
hello_aliyun_regions()

Run python hello_ecs_api.py on the command line to get the currently supported Region list. Similar output is as follows:

[u'cn-shenzhen', u'ap-southeast-1', u'cn-qingdao', u'cn-beijing', u'cn-shanghai', 
u'us-east-1', u'cn-hongkong', u'me-east-1', u'ap-southeast-2', u'cn-hangzhou', u'eu-central-1',
 u'ap-northeast-1', u'us-west-1']

Query the ECS instance list under the current Region

Querying the instance list is very similar to querying the Region list. Replace The input parameter object is DescribeInstancesRequest. For more query parameters, please refer to the query instance list.

def list_instances():
    request = DescribeInstancesRequest()
    response = _send_request(request)
    if response is not None:
        instance_list = response.get('Instances').get('Instance')
        result = map(_print_instance_id, instance_list)
        logging.info("current region include instance %s", result)
def _print_instance_id(item):
    instance_id = item.get('InstanceId');
    return instance_id

The output result is as follows:

current region include instance [u'i-****', u'i-****'']

For more APIs, refer to the ECS API Overview. You can try to query the disk list and replace the instance parameters with DescribeDisksRequest.

Complete code example

The complete code example for the above operation is as follows.

#  coding=utf-8
# if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
# if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
# make sure the sdk version is 2.1.2, you can use command 'pip show aliyun-python-sdk-ecs' to check
import json
import logging
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.DescribeRegionsRequest import DescribeRegionsRequest
# configuration the log output formatter, if you want to save the output to file,
# append ",filename='ecs_invoke.log'" after datefmt.
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')
clt = client.AcsClient('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing')
# sample api to list aliyun open api.
def hello_aliyun_regions():
    request = DescribeRegionsRequest()
    response = _send_request(request)
    if response is not None:
        region_list = response.get('Regions').get('Region')
        assert response is not None
        assert region_list is not None
        result = map(_print_region_id, region_list)
        logging.info("region list: %s", result)
# output the instance owned in current region.
def list_instances():
    request = DescribeInstancesRequest()
    response = _send_request(request)
    if response is not None:
        instance_list = response.get('Instances').get('Instance')
        result = map(_print_instance_id, instance_list)
        logging.info("current region include instance %s", result)
def _print_instance_id(item):
    instance_id = item.get('InstanceId');
    return instance_id
def _print_region_id(item):
    region_id = item.get("RegionId")
    return region_id
# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)
if __name__ == '__main__':
    logging.info("Hello Aliyun OpenApi!")
    hello_aliyun_regions()
    list_instances()

The above is the detailed content of How to manage or custom develop ECS instances via API. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:阿里云. If there is any infringement, please contact admin@php.cn delete
The Building Blocks of Linux: Key Components ExplainedThe Building Blocks of Linux: Key Components ExplainedApr 30, 2025 am 12:26 AM

The core components of the Linux system include the kernel, file system, and user space. 1. The kernel manages hardware resources and provides basic services. 2. The file system is responsible for data storage and organization. 3. Run user programs and services in the user space.

Using Maintenance Mode: Troubleshooting and Repairing LinuxUsing Maintenance Mode: Troubleshooting and Repairing LinuxApr 29, 2025 am 12:28 AM

Maintenance mode is a special operating level entered in Linux systems through single-user mode or rescue mode, and is used for system maintenance and repair. 1. Enter maintenance mode and use the command "sudosystemctlisolaterscue.target". 2. In maintenance mode, you can check and repair the file system and use the command "fsck/dev/sda1". 3. Advanced usage includes resetting the root user password, mounting the file system in read and write mode and editing the password file.

Linux Maintenance Mode: Understanding the PurposeLinux Maintenance Mode: Understanding the PurposeApr 28, 2025 am 12:01 AM

Maintenance mode is used for system maintenance and repair, allowing administrators to work in a simplified environment. 1. System Repair: Repair corrupt file system and boot loader. 2. Password reset: reset the root user password. 3. Package management: Install, update or delete software packages. By modifying the GRUB configuration or entering maintenance mode with specific keys, you can safely exit after performing maintenance tasks.

Linux Operations: Networking and Network ConfigurationLinux Operations: Networking and Network ConfigurationApr 27, 2025 am 12:09 AM

Linux network configuration can be completed through the following steps: 1. Configure the network interface, use the ip command to temporarily set or edit the configuration file persistence settings. 2. Set up a static IP, suitable for devices that require a fixed IP. 3. Manage the firewall and use the iptables or firewalld tools to control network traffic.

Maintenance Mode in Linux: A System Administrator's GuideMaintenance Mode in Linux: A System Administrator's GuideApr 26, 2025 am 12:20 AM

Maintenance mode plays a key role in Linux system management, helping to repair, upgrade and configuration changes. 1. Enter maintenance mode. You can select it through the GRUB menu or use the command "sudosystemctlisolaterscue.target". 2. In maintenance mode, you can perform file system repair and system update operations. 3. Advanced usage includes tasks such as resetting the root password. 4. Common errors such as not being able to enter maintenance mode or mount the file system, can be fixed by checking the GRUB configuration and using the fsck command.

Maintenance Mode in Linux: When and Why to Use ItMaintenance Mode in Linux: When and Why to Use ItApr 25, 2025 am 12:15 AM

The timing and reasons for using Linux maintenance mode: 1) When the system starts up, 2) When performing major system updates or upgrades, 3) When performing file system maintenance. Maintenance mode provides a safe and controlled environment, ensuring operational safety and efficiency, reducing impact on users, and enhancing system security.

Linux: Essential Commands and OperationsLinux: Essential Commands and OperationsApr 24, 2025 am 12:20 AM

Indispensable commands in Linux include: 1.ls: list directory contents; 2.cd: change working directory; 3.mkdir: create a new directory; 4.rm: delete file or directory; 5.cp: copy file or directory; 6.mv: move or rename file or directory. These commands help users manage files and systems efficiently by interacting with the kernel.

Linux Operations: Managing Files, Directories, and PermissionsLinux Operations: Managing Files, Directories, and PermissionsApr 23, 2025 am 12:19 AM

In Linux, file and directory management uses ls, cd, mkdir, rm, cp, mv commands, and permission management uses chmod, chown, and chgrp commands. 1. File and directory management commands such as ls-l list detailed information, mkdir-p recursively create directories. 2. Permission management commands such as chmod755file set file permissions, chownuserfile changes file owner, and chgrpgroupfile changes file group. These commands are based on file system structure and user and group systems, and operate and control through system calls and metadata.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.