搜索
首页运维linux运维如何使用 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"}

云服务器生命周期

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

只有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 check
import json
import logging
import time
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from 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 1
SECURITY_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 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("Create ECS by OpenApi!")
    create_instance_action()
    # create_prepay_instance_action()


以上是如何使用 OpenAPI 代码来弹性地创建和管理ECS的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:阿里云。如有侵权,请联系admin@php.cn删除
Linux操作系统的5个核心组件Linux操作系统的5个核心组件May 08, 2025 am 12:08 AM

Linux操作系统的5个核心组件是:1.内核,2.系统库,3.系统工具,4.系统服务,5.文件系统。这些组件协同工作,确保系统的稳定和高效运行,共同构成了一个强大而灵活的操作系统。

Linux的5个基本要素:解释Linux的5个基本要素:解释May 07, 2025 am 12:14 AM

Linux的五个核心元素是:1.内核,2.命令行界面,3.文件系统,4.包管理,5.社区与开源。这些元素共同定义了Linux的本质和功能。

Linux操作:安全和用户管理Linux操作:安全和用户管理May 06, 2025 am 12:04 AM

Linux用户管理和安全性可以通过以下步骤实现:1.创建用户和组,使用命令如sudouseradd-m-gdevelopers-s/bin/bashjohn。2.批量创建用户和设置密码策略,使用for循环和chpasswd命令。3.检查和修复常见错误,如家目录和shell设置。4.实施最佳实践,如强密码策略、定期审计和最小权限原则。5.优化性能,使用sudo和调整PAM模块配置。通过这些方法,可以有效管理用户和提升系统安全性。

Linux操作:文件系统,进程等Linux操作:文件系统,进程等May 05, 2025 am 12:16 AM

Linux文件系统和进程管理的核心操作包括文件系统的管理和进程的控制。1)文件系统操作包括创建、删除、复制和移动文件或目录,使用命令如mkdir、rmdir、cp和mv。2)进程管理涉及启动、监控和终止进程,使用命令如./my_script.sh&、top和kill。

Linux操作:外壳脚本和自动化Linux操作:外壳脚本和自动化May 04, 2025 am 12:15 AM

Shell脚本是Linux系统中用于自动化执行命令的强大工具。1)Shell脚本通过解释器逐行执行命令,处理变量替换和条件判断。2)基本用法包括备份操作,如使用tar命令备份目录。3)高级用法涉及使用函数和case语句管理服务。4)调试技巧包括使用set-x开启调试模式和set-e在命令失败时退出。5)性能优化建议避免子Shell,使用数组和优化循环。

Linux操作:了解核心功能Linux操作:了解核心功能May 03, 2025 am 12:09 AM

Linux是一个基于Unix的多用户、多任务操作系统,强调简单性、模块化和开放性。其核心功能包括:文件系统:以树状结构组织,支持多种文件系统如ext4、XFS、Btrfs,使用df-T查看文件系统类型。进程管理:通过ps命令查看进程,使用PID管理进程,涉及优先级设置和信号处理。网络配置:灵活设置IP地址和管理网络服务,使用sudoipaddradd配置IP。这些功能在实际操作中通过基本命令和高级脚本自动化得以应用,提升效率并减少错误。

Linux:进入和退出维护模式Linux:进入和退出维护模式May 02, 2025 am 12:01 AM

进入Linux维护模式的方法包括:1.编辑GRUB配置文件,添加"single"或"1"参数并更新GRUB配置;2.在GRUB菜单中编辑启动参数,添加"single"或"1"。退出维护模式只需重启系统。通过这些步骤,你可以在需要时快速进入维护模式,并安全地退出,确保系统的稳定性和安全性。

了解Linux:定义的核心组件了解Linux:定义的核心组件May 01, 2025 am 12:19 AM

Linux的核心组件包括内核、shell、文件系统、进程管理和内存管理。1)内核管理系统资源,2)shell提供用户交互界面,3)文件系统支持多种格式,4)进程管理通过fork等系统调用实现,5)内存管理使用虚拟内存技术。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境