云服务器 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()
相关实践学习
通义万相文本绘图与人像美化
本解决方案展示了如何利用自研的通义万相AIGC技术在Web服务中实现先进的图像生成。
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
5月前
|
弹性计算 搜索推荐 异构计算
阿里云服务器多少钱一年?亲自整理ECS、轻量和GPU服务器租赁价格表
2025年阿里云服务器优惠汇总:轻量应用服务器2核2G 38元/年起,ECS 2核2G 99元/年,2核4G 199元/年,4核16G 89元/月,8核32G 160元/月,香港轻量25元/月起,新老用户同享,续费同价。
1528 158
|
5月前
|
弹性计算 运维 安全
阿里云轻量应用服务器与云服务器ECS啥区别?新手帮助教程
阿里云轻量应用服务器适合个人开发者搭建博客、测试环境等低流量场景,操作简单、成本低;ECS适用于企业级高负载业务,功能强大、灵活可扩展。二者在性能、网络、镜像及运维管理上差异显著,用户应根据实际需求选择。
437 10
|
5月前
|
弹性计算 运维 安全
区别及选择指南:阿里云轻量应用服务器与ECS云服务器有什么区别?
阿里云轻量应用服务器适合个人开发者、学生搭建博客、测试环境,易用且性价比高;ECS功能更强大,适合企业级应用如大数据、高流量网站。根据需求选择:轻量入门首选,ECS专业之选。
370 2
|
5月前
|
弹性计算 运维 安全
阿里云轻量应用服务器38元1年和云服务器99元1年怎么选?二者性能区别及选择参考
在阿里云当下的活动中,38元/年的轻量应用服务器与99元/年的云服务器ECS成为众多新用户的关注焦点。但是有部分用户并不是很清楚二者之间的区别,因此就不知道应该如何选择。接下来,笔者将为您详细剖析ECS云服务器与轻量应用服务器的差异,以供您参考和选择。
560 4
阿里云轻量应用服务器38元1年和云服务器99元1年怎么选?二者性能区别及选择参考
|
5月前
|
弹性计算 搜索推荐 异构计算
租用阿里云服务器一年要多少钱?ECS、轻量和GPU服务器租赁价格,手动整理
2025年10月阿里云服务器优惠持续,轻量应用服务器200M带宽38元起/年,ECS 2核2G 99元/年、2核4G 199元/年,4核16G 89元/月,8核32G 160元/月,香港轻量25元/月起,新老同享,续费不涨价。
1116 2
|
5月前
|
运维 安全 Ubuntu
阿里云渠道商:服务器操作系统怎么选?
阿里云提供丰富操作系统镜像,涵盖Windows与主流Linux发行版。选型需综合技术兼容性、运维成本、安全稳定等因素。推荐Alibaba Cloud Linux、Ubuntu等用于Web与容器场景,Windows Server支撑.NET应用。建议优先选用LTS版本并进行测试验证,通过标准化镜像管理提升部署效率与一致性。