详解通过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实现一个简单的MySQL类
Jan 07 Python
Python编程实现两个文件夹里文件的对比功能示例【包含内容的对比】
Jun 20 Python
Python实现mysql数据库更新表数据接口的功能
Nov 19 Python
selenium+python 对输入框的输入处理方法
Oct 11 Python
Python中按值来获取指定的键
Mar 04 Python
解决django服务器重启端口被占用的问题
Jul 26 Python
python定位xpath 节点位置的方法
Aug 27 Python
python队列原理及实现方法示例
Nov 27 Python
python 爬取马蜂窝景点翻页文字评论的实现
Jan 20 Python
Python应用实现处理excel数据过程解析
Jun 19 Python
Python 实现绘制子图及子图刻度的变换等问题
May 31 Python
Python自动化工具之实现Excel转Markdown表格
Apr 08 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
PHP-CGI进程CPU 100% 与 file_get_contents 函数的关系分析
2011/08/15 PHP
php重定向的三种方法分享
2012/02/22 PHP
ThinkPHP框架安全实现分析
2016/03/14 PHP
Zend Framework动作控制器用法示例
2016/12/09 PHP
php记录搜索引擎爬行记录的实现代码
2018/03/02 PHP
学习YUI.Ext 第三天
2007/03/10 Javascript
简单的前端js+ajax 购物车框架(入门篇)
2011/10/29 Javascript
jQuery中$.fn的用法示例介绍
2013/11/05 Javascript
JS+CSS实现实用的单击输入框弹出选择框的方法
2015/02/28 Javascript
setTimeout内不支持jquery的选择器的解决方案
2015/04/28 Javascript
js图片轮播手动切换特效
2017/01/12 Javascript
利用Node.js检测端口是否被占用的方法
2017/12/07 Javascript
关于ES6尾调用优化的使用
2020/09/11 Javascript
浅谈插入排序算法在Python程序中的实现及简单改进
2016/05/04 Python
浅析Python中的for 循环
2016/06/09 Python
Python脚本实现自动将数据库备份到 Dropbox
2017/02/06 Python
将TensorFlow的模型网络导出为单个文件的方法
2018/04/23 Python
python实现requests发送/上传多个文件的示例
2018/06/04 Python
python实现批量图片格式转换
2020/06/16 Python
使用python语言,比较两个字符串是否相同的实例
2018/06/29 Python
python如何创建TCP服务端和客户端
2018/08/26 Python
Python3爬虫教程之利用Python实现发送天气预报邮件
2018/12/16 Python
详解Python数据分析--Pandas知识点
2019/03/23 Python
python实现雪花飘落效果实例讲解
2019/06/18 Python
利用Tensorflow的队列多线程读取数据方式
2020/02/05 Python
keras tensorflow 实现在python下多进程运行
2020/02/06 Python
CSS实现进度条和订单进度条的示例
2020/11/05 HTML / CSS
美国瑜伽品牌:Gaiam
2017/10/31 全球购物
Cole Haan官方网站:美国时尚潮流品牌
2017/12/06 全球购物
Servlet都有哪些方法?主要作用是什么?
2014/03/04 面试题
工作中个人的自我评价
2013/12/31 职场文书
争先创优心得体会
2014/09/12 职场文书
办公室领导干部作风整顿个人整改措施
2014/09/17 职场文书
表扬稿表扬信的格式及范文
2019/06/24 职场文书
MySQL 8.0 之不可见列的基本操作
2021/05/20 MySQL
Spring Boot DevTools 全局配置学习指南
2022/03/31 Java/Android