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


Posted in Python onSeptember 30, 2018

弹性管理 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()
Python 相关文章推荐
一篇不错的Python入门教程
Feb 08 Python
wxpython 学习笔记 第一天
Feb 09 Python
零基础写python爬虫之urllib2中的两个重要概念:Openers和Handlers
Nov 05 Python
Python处理文本文件中控制字符的方法
Feb 07 Python
Python中list查询及所需时间计算操作示例
Jun 21 Python
Python使用pyodbc访问数据库操作方法详解
Jul 05 Python
解决django前后端分离csrf验证的问题
Feb 03 Python
Django自带的加密算法及加密模块详解
Dec 03 Python
python接口自动化如何封装获取常量的类
Dec 24 Python
python新式类和经典类的区别实例分析
Mar 23 Python
Python基于xlrd模块处理合并单元格
Jul 28 Python
python 使用tkinter+you-get实现视频下载器
Nov 17 Python
Python 使用类写装饰器的小技巧
Sep 30 #Python
浅谈django三种缓存模式的使用及注意点
Sep 30 #Python
使用Python实现租车计费系统的两种方法
Sep 29 #Python
Python实现App自动签到领取积分功能
Sep 29 #Python
10个Python小技巧你值得拥有
Sep 29 #Python
实例分析python3实现并发访问水平切分表
Sep 29 #Python
3个用于数据科学的顶级Python库
Sep 29 #Python
You might like
DC漫画《蝙蝠侠和猫女》图透 猫女怀孕老爷当爹
2020/04/09 欧美动漫
php统计文章排行示例
2014/03/04 PHP
DEDECMS首页调用图片集里的多张图片
2015/06/05 PHP
php无限级分类实现评论及回复功能
2019/02/18 PHP
php设计模式之观察者模式实例详解【星际争霸游戏案例】
2020/03/30 PHP
让页面上两个div中的滚动条(滑块)同步运动示例
2013/08/07 Javascript
js文件Cookie存取值示例代码
2014/02/20 Javascript
详解在vue-cli项目中安装node-sass
2017/06/21 Javascript
微信小程序实现分享朋友圈的图片功能示例
2019/01/18 Javascript
Vue拖拽组件列表实现动态页面配置功能
2019/06/17 Javascript
Vue.js+cube-ui(Scroll组件)实现类似头条效果的横向滚动导航条
2019/06/24 Javascript
vue父子组件通信的高级用法示例
2019/08/29 Javascript
vue项目实现设置根据路由高亮对应的菜单项操作
2020/08/06 Javascript
Nest.js散列与加密实例详解
2021/02/24 Javascript
Python+OpenCV实现车牌字符分割和识别
2018/03/31 Python
Python Dataframe 指定多列去重、求差集的方法
2018/07/10 Python
pycharm 取消默认的右击运行unittest的方法
2018/11/29 Python
python内置模块collections知识点总结
2019/12/19 Python
python FTP批量下载/删除/上传实例
2019/12/22 Python
Python3使用xlrd、xlwt处理Excel方法数据
2020/02/28 Python
如何真正的了解python装饰器
2020/08/14 Python
CSS3制作文字半透明倒影效果的两种实现方式
2014/08/08 HTML / CSS
发现世界上最好的珠宝设计师:JewelStreet
2017/12/17 全球购物
2013年员工自我评价范文
2013/12/27 职场文书
违反工作纪律检讨书
2014/02/15 职场文书
美容院经理岗位职责
2014/04/03 职场文书
小学生感恩演讲稿
2014/04/25 职场文书
三年级班级文化建设方案
2014/05/04 职场文书
优秀党务工作者先进事迹材料
2014/12/25 职场文书
八年级英语教学计划
2015/01/23 职场文书
护理工作个人总结
2015/03/03 职场文书
2016年度员工工作表现评语
2015/12/02 职场文书
表扬信范文
2019/04/22 职场文书
python使用glob检索文件的操作
2021/05/20 Python
MySQL 8.0 Online DDL快速加列的相关总结
2021/06/02 MySQL
postgres之jsonb属性的使用操作
2021/06/23 PostgreSQL