云服务器 ECS 使用OpenAPI管理ECS:使用OpenAPI弹性管理ECS实例

简介:


使用OpenAPI弹性管理ECS实例

您除了可以通过 ECS 管理控制台 创建或管理 ECS 实例外,您也能通过 OpenAPI 管理或定制开发 ECS 实例。

阿里云提供了 SDK 来包装 OpenAPI,将云服务器 ECS 的管理集成到已有系统中。本文基于 Python 的开发来说明如何通过 OpenAPI 管理 ECS 实例。如果您没有 Python 开发经验,也能通过本文完成云服务的开发。

获取 RAM 子账号 AK 密钥

使用 OpenAPI 管理 ECS 实例,您需要能访问 ECS 资源的 API 密钥(Access Key ID 和 Access Key Secret)。为了保证云服务的安全,您需要创建一个能访问 ECS 资源的 RAM 子账号,获取该子账号的 AK 密钥,并使用这个 RAM 子账号和 OpenAPI 管理 ECS 实例。

以下是获取 RAM 子账号 AK 密钥的操作步骤:

  1. 创建 RAM 用户并获取 AK 密钥。
  2. 直接给 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 和 Accesskey Secret。

Access Key ID 和 Access Key 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 Secret', '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 Secret', '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()
相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
4月前
|
弹性计算 搜索推荐 异构计算
阿里云服务器多少钱一年?亲自整理ECS、轻量和GPU服务器租赁价格表
2025年阿里云服务器优惠汇总:轻量应用服务器2核2G 38元/年起,ECS 2核2G 99元/年,2核4G 199元/年,4核16G 89元/月,8核32G 160元/月,香港轻量25元/月起,新老用户同享,续费同价。
1410 158
|
4月前
|
弹性计算 运维 安全
区别及选择指南:阿里云轻量应用服务器与ECS云服务器有什么区别?
阿里云轻量应用服务器适合个人开发者、学生搭建博客、测试环境,易用且性价比高;ECS功能更强大,适合企业级应用如大数据、高流量网站。根据需求选择:轻量入门首选,ECS专业之选。
338 2
|
4月前
|
弹性计算 运维 安全
阿里云轻量应用服务器38元1年和云服务器99元1年怎么选?二者性能区别及选择参考
在阿里云当下的活动中,38元/年的轻量应用服务器与99元/年的云服务器ECS成为众多新用户的关注焦点。但是有部分用户并不是很清楚二者之间的区别,因此就不知道应该如何选择。接下来,笔者将为您详细剖析ECS云服务器与轻量应用服务器的差异,以供您参考和选择。
527 4
阿里云轻量应用服务器38元1年和云服务器99元1年怎么选?二者性能区别及选择参考
|
4月前
|
弹性计算 搜索推荐 异构计算
租用阿里云服务器一年要多少钱?ECS、轻量和GPU服务器租赁价格,手动整理
2025年10月阿里云服务器优惠持续,轻量应用服务器200M带宽38元起/年,ECS 2核2G 99元/年、2核4G 199元/年,4核16G 89元/月,8核32G 160元/月,香港轻量25元/月起,新老同享,续费不涨价。
969 2
《阿里云产品手册2022-2023 版》——OpenAPI Explorer
《阿里云产品手册2022-2023 版》——OpenAPI Explorer
199 0
|
域名解析 JSON 网络协议
利用阿里云 OpenAPI 以及 DNS 云解析自建 DDNS 动态域名解析服务
家里闲置着一台老款的Mac mini Server,跑OS X越来越慢,索性装上了Cent OS 7,变成了一台家庭服务器,装上了Plex媒体服务器和Transmission下载服务,同时,也装上了Nginx、Mysql、MongoDB、Redis等,可以调试代码,甚至担当一些小型项目的服务器。 不过,只在家庭内网使用,功能太有限,于是接下来面临的一个问题就是内网穿透。使用过花生壳和花生棒,服务相当不稳定,而且种种受限,每要多加一个端口就要多花钱,安全性也有问题。
6476 0
利用阿里云 OpenAPI 以及 DNS 云解析自建 DDNS 动态域名解析服务
|
JSON 数据格式 Python
阿里云openapi签名实现代码(基于Python)
部分开发者在接触阿里云openAPi调用的时候,Signature的构造和生成一直都是一只拦路虎,本文中将基于Python,和点播的APi:getPlayAuth 实现签名的构造,仅供大家参考。
1997 0
阿里云openapi签名实现代码(基于Python)
|
Java Linux Apache
阿里云Java SDK通过代理访问阿里云OpenAPI
经常有人会问,我们的服务器在内网,不想让服务器拥有外网IP前提下访问阿里云的OpenAPI可以吗?今天我们对此进行一个解答。在文章中,我们使用最新的阿里云Java SDK:`com.aliyun:aliyun-java-sdk-core:4.5.20`。 文章的示例代码中,代理假设为192.168.1.1:8888,具体代理,包括下面示例里用到的用户名、密码请在开发、测试时改为对应的正确配置。
1859 1

热门文章

最新文章