Home >Operation and Maintenance >Linux Operation and Maintenance >How to manage or custom develop ECS instances via API

How to manage or custom develop ECS instances via API

坏嘻嘻
坏嘻嘻forward
2018-09-30 13:56:222281browse

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:aliyun.com. If there is any infringement, please contact admin@php.cn delete