详解通过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 相关文章推荐
wxpython学习笔记(推荐查看)
Jun 09 Python
Python中生成Epoch的方法
Apr 26 Python
python中requests小技巧
May 10 Python
Django REST为文件属性输出完整URL的方法
Dec 18 Python
Python批量提取PDF文件中文本的脚本
Mar 14 Python
python检测主机的连通性并记录到文件的实例
Jun 21 Python
把csv文件转化为数组及数组的切片方法
Jul 04 Python
pandas使用apply多列生成一列数据的实例
Nov 28 Python
对python产生随机的二维数组实例详解
Dec 13 Python
python实现代码统计器
Sep 19 Python
基于python检查SSL证书到期情况代码实例
Apr 04 Python
详解Python+Selenium+ChromeDriver的配置和问题解决
Jan 19 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
smarty中先strip_tags过滤html标签后truncate截取文章运用
2010/10/25 PHP
PHP学习之整理字符串
2011/04/17 PHP
php UBB 解析实现代码
2011/11/27 PHP
Codeigniter+PHPExcel实现导出数据到Excel文件
2014/06/12 PHP
ThinkPHP实现递归无级分类――代码少
2015/07/29 PHP
PHP实现微信退款功能
2018/10/02 PHP
Thinkphp 框架扩展之应用模式实现方法分析
2020/04/27 PHP
初窥JQuery(一)jquery选择符 必备知识点
2010/11/25 Javascript
JavaScript高级程序设计 阅读笔记(四) ECMAScript中的类型转换
2012/02/27 Javascript
jQuery中阻止冒泡事件的方法介绍
2014/04/12 Javascript
通过jquery 获取URL参数并进行转码
2014/08/18 Javascript
深入理解JavaScript系列(48):对象创建模式(下篇)
2015/03/04 Javascript
jQuery事件绑定on()、bind()与delegate() 方法详解
2015/06/03 Javascript
ECMAScript6函数默认参数
2015/06/12 Javascript
js实现延时加载Flash的方法
2015/11/26 Javascript
怎么限制input的text里输入的值只能是数字(正则、js)
2016/05/16 Javascript
JS查找字符串中出现次数最多的字符
2016/09/05 Javascript
JS中用EL表达式获取上下文参数值的方法
2018/03/28 Javascript
jQuery+ajax实现动态添加表格tr td功能示例
2018/04/23 jQuery
Node.js 路由的实现方法
2019/06/05 Javascript
[16:56]heroes英雄教学 司夜刺客
2014/09/18 DOTA
python实现自动登录人人网并采集信息的方法
2015/06/28 Python
视觉直观感受若干常用排序算法
2017/04/13 Python
详解重置Django migration的常见方式
2019/02/15 Python
python 批量解压压缩文件的实例代码
2019/06/27 Python
Django中使用MySQL5.5的教程
2019/12/18 Python
Pytorch.nn.conv2d 过程验证方式(单,多通道卷积过程)
2020/01/03 Python
python 工具 字符串转numpy浮点数组的实现
2020/03/14 Python
python try...finally...的实现方法
2020/11/25 Python
Python3利用openpyxl读写Excel文件的方法实例
2021/02/03 Python
手把手教你用Django执行原生SQL的方法
2021/02/18 Python
大学生入党思想汇报
2014/01/01 职场文书
分家协议书
2014/04/21 职场文书
2016暑期校本培训心得体会
2016/01/08 职场文书
redis 限制内存使用大小的实现
2021/05/08 Redis
springboot读取resources下文件的方式详解
2022/06/21 Java/Android