使用OpenApi弹性创建云服务器ECS

本文涉及的产品
轻量应用服务器 2vCPU 4GiB,适用于搭建Web应用/小程序
轻量应用服务器 2vCPU 1GiB,适用于搭建电商独立站
轻量应用服务器 2vCPU 4GiB,适用于网站搭建
简介: 除了可以在ECS控制台或者售卖页创建ECS之外,您可以使用OpenApi代码来弹性的创建和管理ECS。这里使用Python来作例子。 开通按量付费产品,您的账户余额不得少于100元,更多的需求参见ECS 使用须知,您需要在阿里云的费用中心确保自己的余额充足。

除了可以在ECS控制台或者售卖页创建ECS之外,您可以使用OpenApi代码来弹性的创建和管理ECS。这里使用Python来作例子。

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

创建ECS的有下面几个API需要关注:

按量的云服务器创建

创建一台云服务器有很多关键参数,下面几个是必选属性:

  • 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;
AI 代码解读

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

{"InstanceId":"i-***","RequestId":"006C1303-BAC5-48E5-BCDF-7FD5C2E6395D"}
AI 代码解读
云服务器生命周期

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

只有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;
AI 代码解读
启动云服务器

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

def start_instance(instance_id):
    request = StartInstanceRequest()
    request.set_InstanceId(instance_id)
    _send_request(request)
AI 代码解读
停止云服务器

停止云服务器也是非常的简单,只需要传入instanceId即可。

def stop_instance(instance_id):
    request = StopInstanceRequest()
    request.set_InstanceId(instance_id)
    _send_request(request)
AI 代码解读
创建时启动自动启动云服务器

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

在创建资源之后得到实例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;
AI 代码解读

这样就完成了资源的创建。

分配公网IP

如果在创建云服务器的过程中,您指定了公网带宽,如果想要公网的访问权限还需要调用API来分配公网IP。分配公网 IP 地址可以参考这个文档来完成。

包年包月的资源创建

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

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

    request.set_Period(1)
    request.set_InstanceChargeType('PrePaid')
AI 代码解读

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

# 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;
AI 代码解读

完整的代码

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

#  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()
AI 代码解读
相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情:&nbsp;https://www.aliyun.com/product/ecs
祝犁
+关注
目录
打赏
0
0
0
3
354
分享
相关文章
阿里云服务器ECS是什么?ECS应用场景、租用流程及使用教程整理
阿里云ECS(弹性计算服务)是性能稳定、弹性扩展的云计算服务,支持多种处理器架构和实例类型,适用于网站托管、开发测试、数据存储、企业服务、游戏多媒体及微服务架构等场景。提供从注册、配置到部署、运维的完整使用流程,助力用户高效上云。
阿里云服务器4核8G配置:ECS实例规格、CPU型号及使用场景说明
阿里云4核8G服务器ECS提供多种实例规格,包括高主频计算型hfc8i、计算型c8i、通用算力型u1、经济型e等。各规格配备不同CPU型号与主频性能,适用于机器学习、数据分析、游戏服务器、Web前端等多种场景。用户可根据需求选择Intel或AMD处理器,如第四代Xeon或AMD EPYC系列,满足高性能计算及企业级应用要求。更多详情参见阿里云官方文档。
182 1
阿里云服务器租用价格:云服务器ECS/轻量/GPU收费标准与活动价格参考
阿里云服务器产品主要包括云服务器ECS、轻量应用服务器以及GPU云服务器等。为了方便大家了解阿里云各类服务器的价格信息,本文整理汇总了阿里云服务器、轻量应用服务器、GPU云服务器的最新收费标准以及活动价格情况,供大家参考选择。
阿里云服务器4核8G配置:ECS实例规格、CPU型号及使用场景说明
阿里云4核8G服务器ECS提供多种实例规格,如高主频计算型hfc8i、计算型c8i、通用算力型u1、经济型e等。各规格基于不同CPU型号与主频性能设计,适用于机器学习、数据分析、游戏服务器、网站应用等多种场景。用户可根据实际需求选择适合的配置,满足高性能计算或经济性要求。更多详情及参数说明可参考官方文档。
374 4
阿里云服务器4核16G配置整理:ECS实例规格、CPU型号及适用场景说明
阿里云ECS服务器4核16G配置提供了多种实例规格选择,如高主频通用型hfg8i(Intel第四代Xeon处理器,全核睿频3.9GHz)、经济型e、通用型g8i/g7等,满足不同业务需求。其中,hfg8i为官方推荐,适合高性能计算;经济型e在活动中更具性价比。各规格覆盖游戏服务器、数据库系统、数据分析、AI训练等多种场景,用户可根据实际需求选择合适的CPU型号与使用场景。更多详情可参考阿里云官方文档。
285 2
阿里云服务器国际站dns服务器不可用怎么办?dns可以随便改吗?
阿里云服务器国际站dns服务器不可用怎么办?dns可以随便改吗?
阿里云服务器国际站高防bgp服务器参数怎么看?服务器被攻击了怎么解决?
阿里云服务器国际站高防bgp服务器参数怎么看?服务器被攻击了怎么解决?
阿里云轻量应用服务器38元与云服务器99元和199元区别及选择参考
2025年,阿里云推出了多款价格比较实惠的轻量应用服务器和云服务器,这些产品以其卓越的性能和亲民的价格,吸引了众多个人开发者、小型网站以及中小企业的关注。本文将对这几款轻量应用服务器和云服务器进行详细对比和测评,分析其性能和适用场景,以供大家在选择时参考。

热门文章

最新文章

相关产品

  • 云服务器 ECS
  • AI助理

    你好,我是AI助理

    可以解答问题、推荐解决方案等