阿里云云中沙箱自助实验-使用OpenApi弹性释放和设置云服务器ECS释放

云服务器ECS的一个重要特性就是按需创建资源。您可以在业务高峰期按需弹性的自定义规则进行资源创建,在完成业务计算的时候释放资源。本篇将提供几个Tips帮助您更加容易和自动化的完成云服务器的释放和弹性设置。

本文将涉及到几个重要的功能和相关API:

释放后实例所使用的物理资源都被回收,包括磁盘及快照,相关数据全部丢失且永久不可恢复。如果您还想继续使用相关的手,建议您释放云服务器之前一定要对磁盘数据做快照,这样您可以下次创建ECS的时候直接通过快照来快速的创建资源。

释放云服务器

释放服务器,首先要求您的服务器处于停止状态,这样当服务器停止以后,如果影响到您的应用,你就可以将服务器重新启动。

停止云服务器

停止服务器的指令非常简单,这个对于按量付费和包年包月都是一样的。停止云服务器有一个参数是ForceStop,如果您将这个属性设置为true,它将类似于断电,直接停止服务器,不承诺数据能写到磁盘中,但是如果您是为了释放服务器,这个可以设置为true。

def stop_instance(instance_id, force_stop=False):
    ‘‘‘    stop one ecs instance.
    :param instance_id: instance id of the ecs instance, like ‘i-***‘.
    :param force_stop: if force stop is true, it will force stop the server and not ensure the data
    write to disk correctly.
    :return:    ‘‘‘
    request = StopInstanceRequest()
    request.set_InstanceId(instance_id)
    request.set_ForceStop(force_stop)
    logging.info("Stop %s command submit successfully.", instance_id)
    _send_request(request)
释放云服务器

如果您没有停止服务器直接执行释放,可能会报错下面的内容

{"RequestId":"3C6DEAB4-7207-411F-9A31-6ADE54C268BE","HostId":"ecs-cn-hangzhou.aliyuncs.com","Code":"IncorrectInstanceStatus","Message":"The current status of the resource does not support this operation."}

当服务器处于Stopped的状态的时候您可以执行释放服务器。释放服务器的方法也比较简单的。参数包括:

  • InstanceId: 实例的id
  • force: 如果将这个参数设置为true,将会执行强制释放,即使云服务器不是Stopped状态也可以释放,所以执行的时候务必小心,以防错误释放影响您的业务。
def release_instance(instance_id, force=False):
    ‘‘‘
    delete instance according instance id, only support after pay instance.    :param instance_id: instance id of the ecs instance, like ‘i-***‘.    :param force:    if force is false, you need to make the ecs instance stopped, you can    execute the delete action.
    If force is true, you can delete the instance even the instance is running.    :return:
    ‘‘‘
    request = DeleteInstanceRequest();
    request.set_InstanceId(instance_id)
    request.set_Force(force)
    _send_request(request)

释放云服务器成功的Response比较简单:

{"RequestId":"689E5813-D150-4664-AF6F-2A27BB4986A3"}

设置云服务器的自动释放时间

为了更加简化您对云服务器的管理,您可以自定义云服务器的释放时间,当定时任务时间到了以后,阿里云将自动为您完成服务器的释放, 您可以不用自己来执行释放。

请注意自动释放时间按照 ISO8601 标准表示,并需要使用 UTC 时间。 格式为:yyyy-MM-ddTHH:mm:ssZ。 如果秒不是 00,则自动取为当前分钟开始时。最少在当前时间之后半小时;最多不能超过当前时间起三年。

def set_instance_auto_release_time(instance_id, time_to_release = None):
    ‘‘‘
    setting instance auto delete time    :param instance_id: instance id of the ecs instance, like ‘i-***‘.    :param time_to_release: if the property is setting, such as ‘2017-01-30T00:00:00Z‘
    it means setting the instance to be release at that time.    if the property is None, it means cancel the auto delete time.    :return:
    ‘‘‘
    request = ModifyInstanceAutoReleaseTimeRequest()
    request.set_InstanceId(instance_id)    if time_to_release is not None:
        request.set_AutoReleaseTime(time_to_release)
    _send_request(request)

执行 set_instance_auto_release_time(‘i-1111‘, ‘2017-01-30T00:00:00Z‘) 就会执行设置。

执行设置成功之后您可以通过熟悉的DescribeInstances来查询自动释放的时间设置。

def describe_instance_detail(instance_id):
    ‘‘‘
    describe instance detail
    :param instance_id: instance id of the ecs instance, like ‘i-***‘.
    :return:
    ‘‘‘
    request = DescribeInstancesRequest()
    request.set_InstanceIds(json.dumps([instance_id]))
    response = _send_request(request)    if response is not None:
        instance_list = response.get(‘Instances‘).get(‘Instance‘)        if len(instance_list) > 0:            return instance_list[0]def check_auto_release_time_ready(instance_id):
    detail = describe_instance_detail(instance_id=instance_id)    if detail is not None:
        release_time = detail.get(‘AutoReleaseTime‘)        return release_time

取消自动释放设置

如果您的业务有变化,需要取消自动释放设置。只需要执行命令将自动释放时间设置为空即可。

set_instance_auto_release_time(‘i-1111‘)

完整代码如下

释放云服务器需谨慎^_^。

#  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 json
import logging

from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.ModifyInstanceAutoReleaseTimeRequest import     ModifyInstanceAutoReleaseTimeRequest
from aliyunsdkecs.request.v20140526.StopInstanceRequest import StopInstanceRequest# 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‘)

def stop_instance(instance_id, force_stop=False):
    ‘‘‘
    stop one ecs instance.    :param instance_id: instance id of the ecs instance, like ‘i-***‘.    :param force_stop: if force stop is true, it will force stop the server and not ensure the data
    write to disk correctly.    :return:
    ‘‘‘
    request = StopInstanceRequest()
    request.set_InstanceId(instance_id)
    request.set_ForceStop(force_stop)
    logging.info("Stop %s command submit successfully.", instance_id)
    _send_request(request)

def describe_instance_detail(instance_id):
    ‘‘‘
    describe instance detail    :param instance_id: instance id of the ecs instance, like ‘i-***‘.    :return:
    ‘‘‘
    request = DescribeInstancesRequest()
    request.set_InstanceIds(json.dumps([instance_id]))
    response = _send_request(request)    if response is not None:
        instance_list = response.get(‘Instances‘).get(‘Instance‘)        if len(instance_list) > 0:            return instance_list[0]

def check_auto_release_time_ready(instance_id):
    detail = describe_instance_detail(instance_id=instance_id)    if detail is not None:
        release_time = detail.get(‘AutoReleaseTime‘)        return release_time

def release_instance(instance_id, force=False):
    ‘‘‘
    delete instance according instance id, only support after pay instance.    :param instance_id: instance id of the ecs instance, like ‘i-***‘.    :param force:    if force is false, you need to make the ecs instance stopped, you can    execute the delete action.
    If force is true, you can delete the instance even the instance is running.    :return:
    ‘‘‘
    request = DeleteInstanceRequest();
    request.set_InstanceId(instance_id)
    request.set_Force(force)
    _send_request(request)

def set_instance_auto_release_time(instance_id, time_to_release = None):
    ‘‘‘
    setting instance auto delete time    :param instance_id: instance id of the ecs instance, like ‘i-***‘.    :param time_to_release: if the property is setting, such as ‘2017-01-30T00:00:00Z‘
    it means setting the instance to be release at that time.    if the property is None, it means cancel the auto delete time.    :return:
    ‘‘‘
    request = ModifyInstanceAutoReleaseTimeRequest()
    request.set_InstanceId(instance_id)    if time_to_release is not None:
        request.set_AutoReleaseTime(time_to_release)
    _send_request(request)
    release_time = check_auto_release_time_ready(instance_id)
    logging.info("Check instance %s auto release time setting is %s. ", instance_id, release_time)

def _send_request(request):
    ‘‘‘
    send open api request    :param request:    :return:
    ‘‘‘
    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("Release ecs instance by Aliyun OpenApi!")
    set_instance_auto_release_time(‘i-1111‘, ‘2017-01-28T06:00:00Z‘)    # set_instance_auto_release_time(‘i-1111‘)
    # stop_instance(‘i-1111‘)
    # release_instance(‘i-1111‘)
    # release_instance(‘i-1111‘, True)

云中沙箱为阿里云官方实验平台。

相关实验:ECS的磁盘挂载、快照及自定义镜像

时间: 2024-08-24 19:10:13

阿里云云中沙箱自助实验-使用OpenApi弹性释放和设置云服务器ECS释放的相关文章

阿里云云中沙箱自助实验-从Gitlab数据库被删看数据备份的重要性!

云中沙箱实验"RDS的数据备份和恢复",教您如何使用阿里云RDS来备份和恢复您的数据库! 一.基本概念 阿里云关系型数据库(Relational Database Service,简称 RDS)是一种稳定可靠.可弹性伸缩的在线数据库服务.基于阿里云分布式文件系统和高性能存储,RDS 支持 MySQL.SQL Server.PostgreSQL 和 PPAS(Postgre Plus Advanced Server,一种高度兼容 Oracle 的数据库)引擎,并且提供了容灾.备份.恢复.

阿里云的云服务器ECS是什么?

云服务器Elastic Compute Service(ECS)是阿里云提供的一种基础云计算服务.使用云服务器ECS就像使用水.电.煤气等资源一样便捷.高效.您无需提前采购硬件设备,而是根据业务需要,随时创建所需数量的云服务器ECS实例.在使用过程中,随着业务的扩展,您可以随时扩容磁盘.增加带宽.如果不再需要云服务器,也能随时释放资源,节省费用. 下图列出了ECS涉及的所有资源,包括实例规格.块存储.镜像.快照.带宽和安全组.您可以通过 云服务器管理控制台 配置您的ECS资源. 相关概念 在使用

阿里云服务器 ECS 部署lamp:centos+apache+mysql+php安装配置方法 (centos7)

1.效果图 1 2. 部署步骤 1 1. mysql安装附加(centos7) 7 3.错误注意****** 10 1.效果图 2.部署步骤 链接 http://jingyan.baidu.com/article/870c6fc31218e8b03fe4be16.html 首先安装apachecentos可以直接yum安装apache ?. 命令:yum install httpd ? //根据提示,输入Y安装即可成功安装? 然后启动apache,并且设置系统让?Apache 开机自动启动. 命

阿里云服务器ECS部署应用教程

购买阿里云服务器 在次页面购买ECS云服务器,其他的很简单,只是有几点需要注意 地域: 在选择地域时需要与镜像类型配合,因为阿里云规定地域必须在一个区域,不管做什么(这一点我只知道皮毛,不过就目前我的了解,增加服务器/带宽/存储等等都与 地域相互绑定了的).服务器地域必须与镜像的地域相同,否则无法匹配. 镜像类型 两个选择,公共镜像/镜像市场购买的镜像. 公共镜像:只有基础的操作系统,其他的软件都没有,但据我的了解在之后可以登陆服务器自行安装. 镜像市场:不但包含基础的操作系统,还包括一些软件之

阿里云服务器 ECS Ubuntu系统安装配置

1. 登陆服务器 系统开通成功后手机会收到阿里云发来的短信,包含公网IP及root登录密码. WEB管理后台方式 可通过阿里云管理后台选择“连接管理终端…”进行登录 提示输入VNC密码 登录成功后显示shell界面,这时需要输入root账号及其密码登录到系统 这时候就可以进行系统操作了 但是这种方式操作比较不方便,建议使用ssh进行管理操作,阿里云系统已经自带了ssh服务,我们用ssh client连接进来即可. SSH方式远程管理 windows用户可以安装putty,通过putty进行SSH

阿里云服务器ECS配置Apache2+php5.3+mysql5图文过程(window 2008 R2 32位)

楔子 现在很多国内IT巨头都开始搞云服务器,前两天,小弟在阿里云(http://www.aliyun.com)中购买了一个云服务器,OS是window 2008 R2 32位,并准备将自己的网站(ThinkPhp+Mysql)搬迁到新服务器. 新服务器的系统相当纯净,连最基本的server软件也没有集成(不想吐槽),本着方便快捷的目的,小弟使用了阿里云提供的IIS+PHP5.5+Mysql+phpWind一键安装包,安装完成后,phpWind运行正常,然后将我的网站导入IIS,发现访问不了.这下

阿里云产品介绍(一):云服务器ECS

最近天南海北的跑客户,在沟通过程中,发现很多客户对于阿里云众多的产品颇有种挑花了眼不知如何入手的感觉,就想写一个系列来简单的介绍下. 云计算的概念刚出来的时候,吹的牛皮是可以将成千上万台物理服务器连接成一台虚拟的服务器来提供服务.而从2006年亚马逊AWS开始运营,十年过去了,如今云计算最成熟的商业模式,却还是将一台物理机器切割成N台虚拟机出售给客户.有时候想想,也挺黑色幽默的. 没错,云服务器ECS(Elastic Compute Service:弹性计算服务,对应亚马逊AWS的产品叫EC2,

阿里云一 第一篇:云服务器ECS

阿里云(www.aliyun.com)创立于2009年,是全球领先的云计算及人工智能科技公司,为200多个国家和地区的企业.开发者和政府机构提供服务.截至2017年3月,阿里云付费云计算用户达87.4万.阿里云致力于以在线公共服务的方式,提供安全.可靠的计算和数据处理能力,让计算和人工智能成为普惠科技. 但是对于很多刚刚接触阿里云的用户来说,经常会被这庞大的产品系统.众多的服务弄得眼花缭乱,感觉无法下手,不知道该怎么选择适合自己的产品服务.针对这个问题,从今天起,我会带着大家一起,分门别类的对阿

阿里云服务器ECS选型、购买参照

作为国内领先的云服务基础设施提供商,使用阿里云提供的ECS是不错的选择.小到个人站长大到电子商务平台,阿里云都有合适的解决方案.本篇教程旨在帮助你如何选型.购买ecs. 首先,你需要注册阿里云账号,最好进行实名认证并登录到阿里云. 温馨提示: 领取阿里云优惠券 第一步,在阿里云官网上选择 产品-云服务器ECS 进入到ecs产品界面后,你可以了解一下关于ECS的介绍. 点击立即购买就可以进入ECS配置页面了. 第二步,选择购买方式和机房所在区域 一般都会默认包年包月的方式购买ECS服务.至于机房的