雲服務器 ECS 使用OpenAPI管理ECS:使用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狀態也可以釋放。執行的時候請務必小心,以防錯誤釋放影響您的業務。
python 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,則自動取為當前分鍾開始時。自動釋放的時間範圍:當前時間後 30 分鍾 ~ 當前時間起 3 年。
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 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 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)
最後更新:2017-08-15 14:33:36