欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解通过API管理或定制开发ECS实例

程序员文章站 2022-06-20 23:28:13
弹性管理 ecs 实例 获取 ram 子账号 ak 密钥 使用api管理ecs实例,您需要能访问ecs资源的api密钥(accesskey id 和 accessk...

弹性管理 ecs 实例

获取 ram 子账号 ak 密钥

使用api管理ecs实例,您需要能访问ecs资源的api密钥(accesskey id 和 accesskey secret)。为了保证云服务的安全,您需要创建一个能访问ecs资源的ram用户,获取该用户的accesskey密钥,并使用这个ram用户和api管理ecs实例。

以下是获取ram用户accesskey密钥的操作步骤:

创建ram用户并获取accesskey密钥。

直接给ram用户授权,授予ram用户 管理云服务器服务(ecs)的权限。

安装 ecs python sdk

首先确保您已经具备python的runtime,本文中使用的python版本为2.7+。

pip install aliyun-python-sdk-ecs

如果提示您没有权限,请切换sudo继续执行。

sudo pip install aliyun-python-sdk-ecs

本文使用的sdk版本为 2.1.2。

hello alibaba cloud

创建文件 hello_ecs_api.py。为了使用sdk,首先实例化acsclient对象,这里需要ram用户的accesskey id和accesskey secret。

accesskey id和accesskey secret是ram用户访问阿里云ecs服务api的密钥,具有该账户完全的权限,请妥善保管。

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')

完成实例化后可以进行第一个应用的开发。查询当前账号支持的地域列表。具体的文档参见 查询可用地域列表。

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()

在命令行运行 python hello_ecs_api.py 会得到当前支持的 region列表。类似的输出如下:

[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']

查询当前的 region 下的 ecs 实例列表

查询实例列表和查询 region 列表非常类似,替换入参对象为describeinstancesrequest 即可,更多的查询参数参考 查询实例列表。

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

输出结果为如下:

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

更多的api参考 ecs api 概览,您可以尝试作一个 查询磁盘列表,将实例的参数替换为 describedisksrequest。

完整代码示例

以上操作完整的代码示例如下所示。

# 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()