详解通过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 18 Python
python如何统计序列中元素
Jul 31 Python
Django框架多表查询实例分析
Jul 04 Python
TensorFlow用expand_dim()来增加维度的方法
Jul 26 Python
Opencv+Python实现图像运动模糊和高斯模糊的示例
Apr 11 Python
Python中list的交、并、差集获取方法示例
Aug 01 Python
Python目录和文件处理总结详解
Sep 02 Python
Django 多对多字段的更新和插入数据实例
Mar 31 Python
keras topN显示,自编写代码案例
Jul 03 Python
python try...finally...的实现方法
Nov 25 Python
Python爬虫爬取ts碎片视频+验证码登录功能
Feb 22 Python
Pytorch可视化的几种实现方法
Jun 10 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安装攻略:常见问题解答(二)
2006/10/09 PHP
PHP异步调用socket实现代码
2012/01/12 PHP
用php简单实现加减乘除计算器
2014/01/06 PHP
WordPress导航菜单的滚动和淡入淡出效果的实现要点
2015/12/14 PHP
PHP自定义函数判断是否为Get、Post及Ajax提交的方法
2017/07/27 PHP
PHP实现支持CURL字符串证书传输的方法
2019/03/23 PHP
静态页面下用javascript操作ACCESS数据库(读增改删)的代码
2007/05/14 Javascript
js select常用操作控制代码
2010/03/16 Javascript
不要在cookie中使用特殊字符的原因分析
2010/07/13 Javascript
解析Jquery中如何把一段html代码动态写入到DIV中(实例说明)
2013/07/09 Javascript
javascript查找字符串中出现最多的字符和次数的小例子
2013/10/29 Javascript
JavaScript闭包_动力节点Java学院整理
2017/06/27 Javascript
微信小程序通过保存图片分享到朋友圈功能
2018/05/24 Javascript
JS获取子节点、父节点和兄弟节点的方法实例总结
2018/07/06 Javascript
JavaScript中import用法总结
2019/01/20 Javascript
JS实现关闭小广告特效
2021/01/29 Javascript
Python入门及进阶笔记 Python 内置函数小结
2014/08/09 Python
python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)
2017/03/12 Python
python下载文件记录黑名单的实现代码
2017/10/24 Python
Python获取基金网站网页内容、使用BeautifulSoup库分析html操作示例
2019/06/04 Python
使用python-Jenkins批量创建及修改jobs操作
2020/05/12 Python
Python字符串查找基本操作代码案例
2020/10/27 Python
利用python实现后端写网页(flask框架)
2021/02/28 Python
Emporio Armani腕表天猫官方旗舰店:乔治·阿玛尼为年轻人设计的副线品牌
2017/07/02 全球购物
英国领先的高级美容和在线皮肤诊所:Face the Future
2020/06/17 全球购物
我的求职计划书
2014/01/10 职场文书
《油菜花开了》教学反思
2014/02/22 职场文书
美术社团活动总结
2014/06/27 职场文书
大四毕业生自荐书
2014/07/05 职场文书
写字楼租赁意向书
2014/07/30 职场文书
企业党建工作汇报材料
2014/08/19 职场文书
银行会计主管岗位职责
2014/10/01 职场文书
同意迁入证明模板
2014/10/26 职场文书
2014年社区民政工作总结
2014/12/02 职场文书
2019年聘任书的写作格式及范文!
2019/07/03 职场文书
一文弄懂MySQL索引创建原则
2022/02/28 MySQL