如何使用 OpenAPI 代码来弹性地创建和管理ECS

本篇文章给大家带来的内容是关于如何使用 openapi 代码来弹性地创建和管理ecs,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

弹性创建 ECS 实例

创建 ECS 时需关注以下 API:

创建ECS实例

查询实例列表

启动ECS实例

分配公网IP地址

前提条件

开通按量付费产品,您的账户余额不得少于 100 元,更多的需求参见 ECS使用须知。您需要在阿里云的费用中心确保自己的余额充足。

创建按量云服务器

创建云服务器时的必选属性:

SecurityGroupId:安全组 ID。安全组通过防火墙规则实现对一组实例的配置,保护实例的网络出入请求。在设置安全组出入规则时,建议按需开放而不要默认开放所有的出入规则。您也可以通过 ECS 控制台创建安全组。

InstanceType:实例规格。参考 ECS 售卖页的选项,界面上 1 核 2GB n1.small则入参为 ecs.n1.small。

ImageId:镜像 ID。参考ECS控制台的镜像列表,您可以过滤系统公共镜像或者自定义镜像。

更多参数设置请参考创建 ECS 实例。

创建云服务器

如下面的代码所示,创建一台经典网络的ECS,使用系统盘ssd,盘参数为cloud_ssd,选择io优化实例optimized。

# create one after pay ecs instance.def create_after_pay_instance(image_id, instance_type, security_group_id):    request = CreateInstanceRequest();    request.set_ImageId(image_id)    request.set_SecurityGroupId(security_group_id)    request.set_InstanceType(instance_type)    request.set_IoOptimized('optimized')    request.set_SystemDiskCategory('cloud_ssd')    response = _send_request(request)    instance_id = response.get('InstanceId')    logging.info("instance %s created task submit successfully.", instance_id)    return instance_id;

创建成功后将返回相应的实例 ID,失败的话也会有对应的 ErrorCode。由于参数较多,您可以参考 ECS 的售卖页进行调整。

{"InstanceId":"i-***","RequestId":"006C1303-BAC5-48E5-BCDF-7FD5C2E6395D"}

云服务器生命周期

对于云服务器的状态操作, 请参考云服务器实例生命周期。

maven使用方法 中文WORD版 maven使用方法 中文WORD版

本文档主要讲述的是maven使用方法;Maven是基于项目对象模型的(pom),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具。Maven将你的注意力从昨夜基层转移到项目管理层。Maven项目已经能够知道 如何构建和捆绑代码,运行测试,生成文档并宿主项目网页。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看

maven使用方法 中文WORD版 0 查看详情 maven使用方法 中文WORD版

只有Stopped状态的实例可以执行 Start 操作。也只有Running状态的 ECS 可以执行Stop操作。查询云服务器的状态可以通过查询实例列表传入 InstanceId 进行过滤。在DescribeInstancesRequest时可以通过传入一个 JSON 数组格式的 String 就可以查询这个资源的状态。查询单个实例的状态建议使用DescribeInstances而不要使用DescribeInstanceAttribute, 因为前者比后者返回更多的属性和内容。

下面的代码会检查实例的状态,只有实例的状态符合入参才会返回实例的详情。

# output the instance owned in current region.def get_instance_detail_by_id(instance_id, status='Stopped'):    logging.info("Check instance %s status is %s", instance_id, status)    request = DescribeInstancesRequest()    request.set_InstanceIds(json.dumps([instance_id]))    response = _send_request(request)    instance_detail = None    if response is not None:        instance_list = response.get('Instances').get('Instance')        for item in instance_list:            if item.get('Status') == status:                instance_detail = item                break;        return instance_detail;

启动云服务器

创建成功后的 ECS 默认状态是Stopped。如果要启动 ECS 实例为Running状态,只需要发送启动指令即可。

def start_instance(instance_id):    request = StartInstanceRequest()    request.set_InstanceId(instance_id)    _send_request(request)

停止云服务器

停止云服务器只需传入instanceId即可。

def stop_instance(instance_id):    request = StopInstanceRequest()    request.set_InstanceId(instance_id)    _send_request(request)

创建时启动“自动启动云服务器”

服务器的启动和停止都是一个异步操作,您可以在脚本创建并同时检测云服务器符合状态时执行相应操作。

创建资源后得到实例ID,首先判断实例是否处于Stopped的状态,如果处于Stopped状态,下发Start服务器的指令,然后等待服务器的状态变成Running。

def check_instance_running(instance_id):    detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)    index = 0    while detail is None and index < 60:        detail = get_instance_detail_by_id(instance_id=instance_id);        time.sleep(10)    if detail and detail.get('Status') == 'Stopped':        logging.info("instance %s is stopped now.")        start_instance(instance_id=instance_id)        logging.info("start instance %s job submit.")    detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)    while detail is None and index < 60:        detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING);        time.sleep(10)    logging.info("instance %s is running now.", instance_id)    return instance_id;

分配公网IP

如果在创建云服务器的过程中,指定了公网带宽,若需要公网的访问权限还要调用API来分配公网IP。详情请参考:分配公网 IP 地址。

包年包月的资源创建

除了创建按量服务的云服务器,您的API还支持创建包年包月的服务器。包年包月的创建和官网的创建流程不同,使用的是自动扣费的模式,也就是说您需要在创建服务器之前确保账号有足够的余额或者信用额度,在创建的时候将直接扣费。

和按量付费的 ECS 相比,只需要指定付费类型和时长即可,下面的时长为1个月。

 request.set_Period(1)    request.set_InstanceChargeType(‘PrePaid’)

创建包年包月实例的整体的代码如下:

# create one prepay ecs instance.def create_prepay_instance(image_id, instance_type, security_group_id):    request = CreateInstanceRequest();    request.set_ImageId(image_id)    request.set_SecurityGroupId(security_group_id)    request.set_InstanceType(instance_type)    request.set_IoOptimized('optimized')    request.set_SystemDiskCategory('cloud_ssd')    request.set_Period(1)    request.set_InstanceChargeType('PrePaid')    response = _send_request(request)    instance_id = response.get('InstanceId')    logging.info("instance %s created task submit successfully.", instance_id)    return instance_id;

完整的代码

完整的代码如下,您可以按照自己的资源参数进行设置。

#  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 checkimport jsonimport loggingimport timefrom aliyunsdkcore import clientfrom aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequestfrom aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequestfrom aliyunsdkecs.request.v20140526.StartInstanceRequest import StartInstanceRequest# 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')IMAGE_ID = 'ubuntu1404_64_40G_cloudinit_20160727.raw'INSTANCE_TYPE = 'ecs.s2.large'  # 2c4g generation 1SECURITY_GROUP_ID = 'sg-****'INSTANCE_RUNNING = 'Running'def create_instance_action():    instance_id = create_after_pay_instance(image_id=IMAGE_ID, instance_type=INSTANCE_TYPE,                                            security_group_id=SECURITY_GROUP_ID)    check_instance_running(instance_id=instance_id)def create_prepay_instance_action():    instance_id = create_prepay_instance(image_id=IMAGE_ID, instance_type=INSTANCE_TYPE,                                         security_group_id=SECURITY_GROUP_ID)    check_instance_running(instance_id=instance_id)# create one after pay ecs instance.def create_after_pay_instance(image_id, instance_type, security_group_id):    request = CreateInstanceRequest();    request.set_ImageId(image_id)    request.set_SecurityGroupId(security_group_id)    request.set_InstanceType(instance_type)    request.set_IoOptimized('optimized')    request.set_SystemDiskCategory('cloud_ssd')    response = _send_request(request)    instance_id = response.get('InstanceId')    logging.info("instance %s created task submit successfully.", instance_id)    return instance_id;# create one prepay ecs instance.def create_prepay_instance(image_id, instance_type, security_group_id):    request = CreateInstanceRequest();    request.set_ImageId(image_id)    request.set_SecurityGroupId(security_group_id)    request.set_InstanceType(instance_type)    request.set_IoOptimized('optimized')    request.set_SystemDiskCategory('cloud_ssd')    request.set_Period(1)    request.set_InstanceChargeType('PrePaid')    response = _send_request(request)    instance_id = response.get('InstanceId')    logging.info("instance %s created task submit successfully.", instance_id)    return instance_id;def check_instance_running(instance_id):    detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)    index = 0    while detail is None and index < 60:        detail = get_instance_detail_by_id(instance_id=instance_id);        time.sleep(10)    if detail and detail.get('Status') == 'Stopped':        logging.info("instance %s is stopped now.")        start_instance(instance_id=instance_id)        logging.info("start instance %s job submit.")    detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)    while detail is None and index < 60:        detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING);        time.sleep(10)    logging.info("instance %s is running now.", instance_id)    return instance_id;def start_instance(instance_id):    request = StartInstanceRequest()    request.set_InstanceId(instance_id)    _send_request(request)# output the instance owned in current region.def get_instance_detail_by_id(instance_id, status='Stopped'):    logging.info("Check instance %s status is %s", instance_id, status)    request = DescribeInstancesRequest()    request.set_InstanceIds(json.dumps([instance_id]))    response = _send_request(request)    instance_detail = None    if response is not None:        instance_list = response.get('Instances').get('Instance')        for item in instance_list:            if item.get('Status') == status:                instance_detail = item                break;        return instance_detail;# send open api requestdef _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("Create ECS by OpenApi!")    create_instance_action()    # create_prepay_instance_action()

以上就是如何使用 OpenAPI 代码来弹性地创建和管理ECS的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/764047.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
VSCode Zen模式使用指南
上一篇 2025年11月26日 02:17:46
在Java中如何使用volatile关键字实现可见性控制_volatile应用技巧解析
下一篇 2025年11月26日 02:17:48

相关推荐

  • sublime的session文件是做什么用的_sublime会话文件作用与恢复机制

    sublime的session文件是做什么用的_sublime会话文件作用与恢复机制sublime的session文件是做什么用的_sublime会话文件作用与恢复机制sublime的session文件是做什么用的_sublime会话文件作用与恢复机制sublime的session文件是做什么用的_sublime会话文件作用与恢复机制

    Sublime Text的session文件记录了打开的文件、光标位置、代码折叠状态、窗口布局及未保存内容等信息,位于系统特定目录下的Local文件夹中,以JSON格式存储,通过自动保存机制在重启后恢复编辑状态。 Sublime Text 的 session 文件主要用于保存用户当前编辑环境的状态信…

    2026年9月24日 用户投稿
    000
  • windows10的gpedit.msc组策略打不开_windows10组策略编辑器打不开修复方法

    windows10的gpedit.msc组策略打不开_windows10组策略编辑器打不开修复方法windows10的gpedit.msc组策略打不开_windows10组策略编辑器打不开修复方法windows10的gpedit.msc组策略打不开_windows10组策略编辑器打不开修复方法windows10的gpedit.msc组策略打不开_windows10组策略编辑器打不开修复方法

    首先检查系统文件完整性,运行sfc /scannow修复损坏文件;若为家庭版系统,使用DISM命令安装组策略组件;接着通过注册表编辑器修改MMC相关限制策略;最后尝试直接从System32目录运行gpedit.msc文件。 如果您尝试通过运行命令打开Windows 10的组策略编辑器(gpedit.…

    2026年9月24日 用户投稿
    000
  • DeepSeek能不能帮我写代码 简单编程任务如何交给DeepSeek完成

    DeepSeek能不能帮我写代码 简单编程任务如何交给DeepSeek完成DeepSeek能不能帮我写代码 简单编程任务如何交给DeepSeek完成DeepSeek能不能帮我写代码 简单编程任务如何交给DeepSeek完成DeepSeek能不能帮我写代码 简单编程任务如何交给DeepSeek完成

    很多用户好奇,像DeepSeek这样的AI模型能否帮助完成编程任务,特别是那些相对简单的编程需求。答案是肯定的。DeepSeek具备理解自然语言描述并尝试生成相应代码的能力,这使得它成为完成一些简单编程任务的有力工具。 ☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepS…

    2026年9月24日 用户投稿
    100
  • ubuntu如何mount网络驱动器

    在ubuntu中挂载网络驱动器有多种方法,以下是一些常见的方法: 方法一:使用mount命令 确定网络驱动器的地址:例如,如果是Samba共享,地址可能是smb://server/share。如果是NFS共享,地址可能是nfs://server/share。安装必要的软件包:对于Samba共享,安装…

    2026年9月24日
    000
  • Java中双精度浮点数的小数位控制技巧

    Java中双精度浮点数的小数位控制技巧Java中双精度浮点数的小数位控制技巧Java中双精度浮点数的小数位控制技巧Java中双精度浮点数的小数位控制技巧

    本文深入探讨了在Java中有效控制double类型数值小数位数的方法。通过Math.round()函数结合乘除操作,可以实现数值本身的四舍五入并改变其精度;而String.format()则提供了灵活的字符串格式化功能,用于在不修改原始数值的情况下精确控制显示的小数位数。这两种方法分别适用于不同的业…

    2026年9月24日 用户投稿
    000
  • Steam新游周报:经典恐怖游戏新作登场!

    Steam新游周报:经典恐怖游戏新作登场!Steam新游周报:经典恐怖游戏新作登场!Steam新游周报:经典恐怖游戏新作登场!Steam新游周报:经典恐怖游戏新作登场!

    十一国庆前的最后一周,Steam上又有许多令人兴奋的新作发布!本周策略玩家与模拟建设玩家有福了,将有数款新作等着你们,体育爱好者们则能玩到EA一款足球年货游戏,而本周黑马则是一款来自科乐美的经典日式恐怖游戏。让我们进入这周的新游周报吧! 周一(9月22日) 名望(抢先体验) Steam商店页面:名望…

    2026年9月24日 用户投稿
    000
  • 高质量免费logo设计网站 国产免费logo生成工具推荐

    国产免费Logo设计网站推荐即时设计、DesignEvo、牛人设计等,这些平台提供海量模板、支持中文输入与AI智能生成,具备全中文界面、本土化元素和矢量导出功能,适合零基础用户快速制作高质量Logo。 高质量免费logo设计网站国产免费logo生成工具推荐这是不少网友都关注的接下来由PHP小编为大家…

    2026年9月24日
    200
  • LINUX怎么统计一个文件夹下文件的数量_LINUX文件数量统计命令

    使用find命令统计文件数量最准确,如find /path/to/directory -type f | wc -l可递归统计所有普通文件,包含隐藏文件,推荐用于复杂场景。 要统计 Linux 系统中一个文件夹下文件的数量,可以使用多种命令组合来实现。最常用的方法是结合 find、ls 和 wc 命…

    2026年9月24日
    600
  • 如何通过BIOS调整CPU电压实现节能?

    答案:CPU降压通过BIOS调整Vcore电压,采用Offset模式在保证稳定前提下降低功耗与温度,提升能效;需结合HWiNFO64等工具监控温度、功耗,并用Prime95等压力测试验证稳定性,避免蓝屏或崩溃,合理设置可使CPU在更低温度下维持更高睿频,实现节能且不牺牲性能。 通过BIOS调整CPU…

    2026年9月24日
    700
  • 为什么GPU显存带宽比容量更重要?

    显存带宽比容量更重要,因其直接决定数据传输速度,影响GPU计算单元的利用率。在AI训练和高分辨率渲染中,高带宽可避免“数据饥饿”,确保海量数据高效流转,而HBM技术凭借3D堆叠和宽接口提供远超GDDR的带宽,成为高性能计算的关键。 GPU显存带宽比容量更重要,核心在于现代GPU的工作模式和其处理的数…

    2026年9月24日
    100
  • VSCode如何实现代码热重载 VSCode实时预览开发的高效配置方案

    使用live server扩展实现静态文件的实时预览,保存后浏览器自动刷新;2. 利用现代前端框架(如react、vue)内置的开发服务器(如vite、webpack dev server)实现hmr热模块替换,修改代码后仅更新变动模块而不刷新页面;3. 结合browsersync等工具实现多设备同…

    2026年9月24日
    000
  • mysql临时表如何使用_PHP中操作mysql临时表的具体步骤

    MySQL临时表仅在当前会话可见,连接关闭后自动删除,适合中间数据处理。使用PHP操作时,先通过mysqli或PDO建立数据库连接,再执行CREATE TEMPORARY TABLE语句创建临时表,随后可像普通表一样进行INSERT、SELECT及JOIN等操作。临时表可与永久表同名且优先被使用,支…

    2026年9月24日
    000
  • Java语法基础中static关键字可以修饰哪些内容

    static关键字用于定义类成员,包括静态变量(如计数器)、静态方法(如工具方法)、静态代码块(类加载时执行)和静态内部类(不依赖外部类实例),均属于类而非对象,通过类名访问,提升成员至类级别实现共享与提前使用。 static 关键字在 Java 中主要用于定义与类相关而非与对象实例相关的成员。它不…

    2026年9月24日
    100
  • 为什么要4k对齐

    早期硬盘的每个扇区以512字节为标准,而新一代硬盘的扇区容量则为4096个字节,即所谓的4k扇区。虽然硬盘标准已经更新,但操作系统仍然使用512字节扇区的标准。为了确保兼容性,硬盘制造商将4k扇区模拟成了512字节扇区。文件系统的块(簇)通常是512字节的倍数,而新系统大多设定为4k的倍数,例如li…

    2026年9月24日
    000
  • windows怎么关闭cortana进程_彻底关闭小娜(cortana)后台进程的方法

    1、可通过任务管理器结束Cortana进程并禁用其启动项;2、修改注册表或组策略可永久关闭;3、重命名系统目录文件夹可阻止其运行。 如果您发现Windows系统中Cortana(小娜)后台进程占用资源或影响系统性能,可能是该服务在后台持续运行。以下是彻底关闭Cortana进程的操作步骤: 本文运行环…

    2026年9月24日
    800
  • 苹果过时产品名单更新,M5 iPad Pro 开箱视频流出

    苹果过时产品名单更新,M5 iPad Pro 开箱视频流出苹果过时产品名单更新,M5 iPad Pro 开箱视频流出苹果过时产品名单更新,M5 iPad Pro 开箱视频流出苹果过时产品名单更新,M5 iPad Pro 开箱视频流出

    日前,苹果已将 iphone 11 pro max 和 apple watch series 3 的所有型号列入“过时产品”(vintage product)行列。 根据苹果的规定,一款产品在停止销售满 5 年后,可能会被归为“过时产品”。不过,这一分类并不会显著影响售后服务——苹果仍会继续为这些设…

    2026年9月24日 用户投稿
    600
  • VSCode如何实现AI版本迁移辅助 VSCode跨版本升级的智能建议

    vscode的“ai版本迁移辅助”并非独立功能,而是通过扩展兼容性检查、设置同步、lsp/dap协议支持及社区资源等生态能力协同实现;2. 升级后扩展无法工作时,应检查更新日志、尝试降级或重新安装扩展、禁用冲突扩展、查看控制台错误信息并向作者报告问题;3. 备份设置和扩展列表可通过启用设置同步、手动…

    2026年9月24日
    1000
  • Ubunt16.04 搭建 GPU 显卡驱动 + CUDA9.0 + cuDNN7 详细教程

    Ubunt16.04 搭建 GPU 显卡驱动 + CUDA9.0 + cuDNN7 详细教程Ubunt16.04 搭建 GPU 显卡驱动 + CUDA9.0 + cuDNN7 详细教程Ubunt16.04 搭建 GPU 显卡驱动 + CUDA9.0 + cuDNN7 详细教程Ubunt16.04 搭建 GPU 显卡驱动 + CUDA9.0 + cuDNN7 详细教程

    如果你的电脑运行着 ubuntu16.04,并且配备了一块 nvidia geforce gpu 显卡,那么不利用它来运行深度学习模型就太浪费了!虽然网上关于这方面的教程有很多,但质量参差不齐。本文将详细指导你如何安装 gpu 显卡驱动、cuda9.0 和 cudnn7,助你一步步搭建好环境,值得一…

    2026年9月24日 用户投稿
    600
  • MAC系统怎么开启防火墙_MAC开启防火墙教程

    1、建议在Mac系统中开启防火墙以提升网络安全,可通过“系统设置”中的“网络-防火墙”选项启用;2、高级用户可使用终端命令sudo /usr/libexec/ApplicationFirewall/socketfilterfw –setglobalstate on开启服务;3、启用后可在…

    2026年9月24日
    100
  • APM开发阅读

    APM开发阅读APM开发阅读APM开发阅读APM开发阅读

    我阅读apm的源码有两个主要目的:一是学习,了解飞控系统和大型项目的组织结构;二是为了移植的需要,满足项目需求。近年来,少儿编程市场非常火热,许多厂商推出了相关的产品,但这些产品大多使用空心杯电机,导致动力不足,且扩展性有限。许多任务需要io或图像识别的支持。 因此,我在考虑使用APM裁剪版的飞控系…

    2026年9月24日 用户投稿
    1600

发表回复

登录后才能评论
关注微信