Use OpenApi to elastically release and set up cloud server ECS release

Introduction: An important feature of cloud server ECS is to create resources on demand. You can create resources with on-demand elastic custom rules during peak business hours, and release resources when business calculations are completed. This article will provide several Tips to help you more easily and automatically complete the release and elastic settings of cloud servers.
An important feature of cloud server ECS is the creation of resources on demand. You can create resources with on-demand elastic custom rules during peak business hours , and release resources when business calculations are completed. This article will provide several Tips to help you more easily and automatically complete the release and elastic settings of cloud servers.
This article will cover several important functions and related APIs:
•Free pay-as-you-go cloud servers
•Set the automatic release time of pay-as-you-go instances
•stop the server
•Query instance list
After the release, all physical resources used by the instance are reclaimed, including disks and snapshots. All related data is lost and cannot be recovered permanently. If you still want to continue to use the related hand, it is recommended that you take a snapshot of the disk data before releasing the cloud server, so that you can quickly create resources directly through the snapshot the next time you create an ECS.

【Use OpenApi to elastically release and set up cloud server ECS release】free cloud server


To release the server, first require your server to be in a stopped state, so that when the server is stopped, if it affects your application, you can restart the server.
stop cloud server
The instruction to stop the server is very simple, this is the same for pay-as-you-go and annual subscription. There is a parameter to stop the cloud server is ForceStop, if you set this property to true, it will be similar to a power outage, stop the server directly, and do not promise that the data can be written to the disk, but if you are to release the server, this can be set to 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)

【Use OpenApi to elastically release and set up cloud server ECS release】free cloud server


If you do not stop the server and execute the release directly, the following error may be reported
{ "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." }
When the server is in the Stopped state you can execute the release server. The method of releasing the server is also relatively simple. Parameters include:
•InstanceId: the id of the instance
•force: If this parameter is set to true, the forced release will be performed, even if the cloud server is not in the Stopped state, it can be released, so be careful when executing it to prevent the wrong release from affecting your business.
def release_instance(instance_id, force=False):
'''
delete instance according to 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)
The successful response of releasing the cloud server is relatively simple:
{ "RequestId" : "689E5813-D150-4664-AF6F-2A27BB4986A3" }
Set the automatic release time of the cloud server
In order to simplify your management of cloud servers, you can customize the release time of the cloud servers. When the scheduled task time is up, Alibaba Cloud will automatically release the servers for you, and you do not need to perform the release yourself.
Please note that the auto-release time is expressed in accordance with the ISO8601 standard and requires the use of UTC time. The format is: yyyy-MM-ddTHH:mm:ssZ. If the second is not 00, it is automatically taken as the start of the current minute. At least half an hour after the current time; at most three years from the current time.
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 released 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)
Execute set_instance_auto_release_time('i-1111', '2017-01-30T00:00:00Z') to execute the setting.
query the automatic release time setting through the familiar 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
Cancel the auto release setting
If your business changes, you need to cancel the auto-release setting. Just execute the command to set the autorelease time to null.
set_instance_auto_release_time ( 'i-1111' )
The complete code is as follows
Be careful when releasing cloud servers ^_^.
# 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

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 to 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 released 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)

Copyright statement: The content of this article is contributed by Alibaba Cloud real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00