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

 更新时间:2018年09月30日 14:23:30   投稿:laozhang  
在本文里我们给大家整理了关于通过API管理或定制开发ECS的相关实例内容,有需要的朋友们参考学习下。

弹性管理 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()

相关文章

  • centos系统升级python 2.7.3

    centos系统升级python 2.7.3

    CentOS上安装的python版本是2.6,不能满足我运行软件的要求,所以对python进行升级。Python的最新版本已经是3.3,但是Python3的兼容性可能还有一定的问题,所以还是升级到2.7较为保险。
    2014-07-07
  • Python中inplace、subset参数的意义及说明

    Python中inplace、subset参数的意义及说明

    这篇文章主要介绍了Python中inplace、subset参数的意义及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • python算法测试结果自动保存到excel表格的实现步骤

    python算法测试结果自动保存到excel表格的实现步骤

    我们在进行算法评估是通常会针对每个样本的算法处理结果进行统计,例如每个样本正确预测数量、漏检数量和误检数量、精度等,本文小编将给大家介绍python算法测试结果自动保存到excel表格的实现步骤,感兴趣的朋友可以参考下
    2023-12-12
  • python typing模块--类型提示支持

    python typing模块--类型提示支持

    这篇文章主要介绍python typing模块类型提示支持, typing 模块只有在python3.5以上的版本中才可以使用,pycharm目前支持typing检查,下面进入文章一起了解详细内容吧
    2021-10-10
  • python爬取一组小姐姐图片实例

    python爬取一组小姐姐图片实例

    大家好,本篇文章主要讲的是python爬取一组小姐姐图片实例,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • Python中pandas dataframe删除一行或一列:drop函数详解

    Python中pandas dataframe删除一行或一列:drop函数详解

    今天小编就为大家分享一篇Python中pandas dataframe删除一行或一列:drop函数详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • python的描述器descriptor详解

    python的描述器descriptor详解

    这篇文章主要介绍了python的描述器descriptor详解,描述器可以用于控制属性的读取、写入和删除等操作,同时还可以用于实现计算属性、类属性、属性别名等高级功能,需要的朋友可以参考下
    2023-07-07
  • python中numpy包使用教程之数组和相关操作详解

    python中numpy包使用教程之数组和相关操作详解

    这篇文章主要给大家介绍了关于python中numpy包的使用教程,包含数组和相关操作等内容,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来跟着小编一起学习学习吧。
    2017-07-07
  • Python实现数据清洗的示例详解

    Python实现数据清洗的示例详解

    这篇文章主要通过五个示例带大家深入了解下Python实现数据清洗的具体方法,文中的示例代码讲解详细,对我们学习Python有一定帮助,需要的可以参考一下
    2022-08-08
  • Python 集合之set详解

    Python 集合之set详解

    这篇文章主要介绍了python基础之set集合详解,文中有非常详细的代码示例,对正在学习python的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-09-09

最新评论