


How 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.
