热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用OpenAPI代码来弹性地创建和管理ECS-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(&#39;Status&#39;) == &#39;Stopped&#39;:
        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(&#39;optimized&#39;)
    request.set_SystemDiskCategory(&#39;cloud_ssd&#39;)
    request.set_Period(1)
    request.set_InstanceChargeType(&#39;PrePaid&#39;)
    respOnse= _send_request(request)
    instance_id = response.get(&#39;InstanceId&#39;)
    logging.info("instance %s created task submit successfully.", instance_id)
    return instance_id;

完整的代码

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

#  coding=utf-8
# if the python sdk is not install using &#39;sudo pip install aliyun-python-sdk-ecs&#39;
# if the python sdk is install using &#39;sudo pip install --upgrade aliyun-python-sdk-ecs&#39;
# make sure the sdk version is 2.1.2, you can use command &#39;pip show aliyun-python-sdk-ecs&#39; 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=&#39;ecs_invoke.log&#39;" after datefmt.
logging.basicConfig(level=logging.INFO,
                    format=&#39;%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s&#39;,
                    datefmt=&#39;%a, %d %b %Y %H:%M:%S&#39;)
clt = client.AcsClient(&#39;Your Access Key Id&#39;, &#39;Your Access Key Secrect&#39;, &#39;cn-beijing&#39;)
IMAGE_ID = &#39;ubuntu1404_64_40G_cloudinit_20160727.raw&#39;
INSTANCE_TYPE = &#39;ecs.s2.large&#39;  # 2c4g generation 1
SECURITY_GROUP_ID = &#39;sg-****&#39;
INSTANCE_RUNNING = &#39;Running&#39;
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(&#39;optimized&#39;)
    request.set_SystemDiskCategory(&#39;cloud_ssd&#39;)
    respOnse= _send_request(request)
    instance_id = response.get(&#39;InstanceId&#39;)
    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(&#39;optimized&#39;)
    request.set_SystemDiskCategory(&#39;cloud_ssd&#39;)
    request.set_Period(1)
    request.set_InstanceChargeType(&#39;PrePaid&#39;)
    respOnse= _send_request(request)
    instance_id = response.get(&#39;InstanceId&#39;)
    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(&#39;Status&#39;) == &#39;Stopped&#39;:
        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=&#39;Stopped&#39;):
    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(&#39;Instances&#39;).get(&#39;Instance&#39;)
        for item in instance_list:
            if item.get(&#39;Status&#39;) == status:
                instance_detail = item
                break;
        return instance_detail;
# send open api request
def _send_request(request):
    request.set_accept_format(&#39;json&#39;)
    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__ == &#39;__main__&#39;:
    logging.info("Create ECS by OpenApi!")
    create_instance_action()
    # create_prepay_instance_action()

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


推荐阅读
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • 学习SLAM的女生,很酷
    本文介绍了学习SLAM的女生的故事,她们选择SLAM作为研究方向,面临各种学习挑战,但坚持不懈,最终获得成功。文章鼓励未来想走科研道路的女生勇敢追求自己的梦想,同时提到了一位正在英国攻读硕士学位的女生与SLAM结缘的经历。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • 本文介绍了RPC框架Thrift的安装环境变量配置与第一个实例,讲解了RPC的概念以及如何解决跨语言、c++客户端、web服务端、远程调用等需求。Thrift开发方便上手快,性能和稳定性也不错,适合初学者学习和使用。 ... [详细]
  • 31.项目部署
    目录1一些概念1.1项目部署1.2WSGI1.3uWSGI1.4Nginx2安装环境与迁移项目2.1项目内容2.2项目配置2.2.1DEBUG2.2.2STAT ... [详细]
  • MySQL语句大全:创建、授权、查询、修改等【MySQL】的使用方法详解
    本文详细介绍了MySQL语句的使用方法,包括创建用户、授权、查询、修改等操作。通过连接MySQL数据库,可以使用命令创建用户,并指定该用户在哪个主机上可以登录。同时,还可以设置用户的登录密码。通过本文,您可以全面了解MySQL语句的使用方法。 ... [详细]
  • PHPMailer邮件类邮件发送功能的使用教学及注意事项
    本文介绍了使用国外开源码PHPMailer邮件类实现邮件发送功能的简单教学,同时提供了一些注意事项。文章涵盖了字符集设置、发送HTML格式邮件、群发邮件以及避免类的重定义等方面的内容。此外,还提供了一些与PHP相关的资源和服务,如传奇手游游戏源码下载、vscode字体调整、数据恢复、Ubuntu实验环境搭建、北京爬虫市场、进阶PHP和SEO人员需注意的内容。 ... [详细]
  • Ubuntu安装常用软件详细步骤
    目录1.GoogleChrome浏览器2.搜狗拼音输入法3.Pycharm4.Clion5.其他软件1.GoogleChrome浏览器通过直接下载安装GoogleChro ... [详细]
  • 本文介绍了在Docker容器技术中限制容器对CPU的使用的方法,包括使用-c参数设置容器的内存限额,以及通过设置工作线程数量来充分利用CPU资源。同时,还介绍了容器权重分配的情况,以及如何通过top命令查看容器在CPU资源紧张情况下的使用情况。 ... [详细]
  • 在ubuntu服务器上安装vscode,但是目前使用的方法都无法成功。第一次安装经历:安装完anaconda后有自动安装vscode的选项,输入yes后,没有出现错误,但是在终端输 ... [详细]
author-avatar
o筱灵丹
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有