阿里雲團隊努力不懈,讓最新技術內容能以更快方式以您最熟悉的語言呈現給您。本文內容由機器自動翻譯簡體中文,過程無人工干預。轉碼所造成任何內容錯誤及相關損失,阿里雲概不負責。敬請見諒。若任何內容問題涉及信息準確性,請以英文版為準。
全部產品
Search
文件中心

彈性釋放 ECS 執行個體

更新時間: Aug 23, 2018

Elastic Compute Service 的一個重要特性就是按需建立資源。您可以在業務高峰期按需彈性地進行自訂資源建立,完成業務計算時釋放資源。本篇將提供若干 Tips 幫助您更加便捷地完成雲端服務器的釋放以及彈性設定。

本文將涉及到幾個重要功能和相關API:

釋放後,執行個體所使用的實體資源將被回收,包括磁碟及快照,相關資料將全部丟失且永久不可恢複。如果您還想繼續使用相關的資料,建議您釋放雲端服務器之前一定要對磁碟資料做快照,下次建立 ECS 時可以直接通過快照建立資源。

釋放雲端服務器

釋放伺服器,首先要求您的伺服器處於停止狀態。當伺服器停止後,若影響到應用,您可以將伺服器重新啟動。

停止雲端服務器

停止伺服器的指令非常簡單,且對於隨用隨付和訂用帳戶都是一樣的。停止雲端服務器的一個參數是 ForceStop,若屬性設定為 true,它將類似於斷電,直接停止伺服器,但不承諾資料能寫到磁碟中。如果僅僅為了釋放伺服器,這個可以設定為 true。

  1. def stop_instance(instance_id, force_stop=False):
  2. '''
  3. stop one ecs instance.
  4. :param instance_id: instance id of the ecs instance, like 'i-***'.
  5. :param force_stop: if force stop is true, it will force stop the server and not ensure the data
  6. write to disk correctly.
  7. :return:
  8. '''
  9. request = StopInstanceRequest()
  10. request.set_InstanceId(instance_id)
  11. request.set_ForceStop(force_stop)
  12. logging.info("Stop %s command submit successfully.", instance_id)
  13. _send_request(request)

釋放雲端服務器

如果您沒有停止伺服器直接執行釋放,可能會有如下報錯:

  1. {"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 如下:

  1. {“RequestId”:”689E5813-D150-4664-AF6F-2A27BB4986A3”}

設定雲端服務器的自動釋放時間

為了更加簡化對雲端服務器的管理,您可以自訂雲端服務器的釋放時間。當定時時間到後,阿里雲將自動為您完成伺服器的釋放, 無需手動執行釋放。

注意:自動釋放時間按照 ISO8601 標準表示,並需要使用 UTC 時間。 格式為:yyyy-MM-ddTHH:mm:ssZ。 如果秒不是 00,則自動取為當前分鐘開始時。自動釋放的時間範圍:目前時間後 30 分鐘 ~ 目前時間起 3 年。

  1. def set_instance_auto_release_time(instance_id, time_to_release = None):
  2. '''
  3. setting instance auto delete time
  4. :param instance_id: instance id of the ecs instance, like 'i-***'.
  5. :param time_to_release: if the property is setting, such as '2017-01-30T00:00:00Z'
  6. it means setting the instance to be release at that time.
  7. if the property is None, it means cancel the auto delete time.
  8. :return:
  9. '''
  10. request = ModifyInstanceAutoReleaseTimeRequest()
  11. request.set_InstanceId(instance_id)
  12. if time_to_release is not None:
  13. request.set_AutoReleaseTime(time_to_release)
  14. _send_request(request)

執行 set_instance_auto_release_time(‘i-1111’, ‘2017-01-30T00:00:00Z’) 後完成設定。

執行設定成功後,您可以通過DescribeInstances來查詢自動釋放的時間設定。

  1. def describe_instance_detail(instance_id):
  2. '''
  3. describe instance detail
  4. :param instance_id: instance id of the ecs instance, like 'i-***'.
  5. :return:
  6. '''
  7. request = DescribeInstancesRequest()
  8. request.set_InstanceIds(json.dumps([instance_id]))
  9. response = _send_request(request)
  10. if response is not None:
  11. instance_list = response.get('Instances').get('Instance')
  12. if len(instance_list) > 0:
  13. return instance_list[0]
  14. def check_auto_release_time_ready(instance_id):
  15. detail = describe_instance_detail(instance_id=instance_id)
  16. if detail is not None:
  17. release_time = detail.get('AutoReleaseTime')
  18. return release_time

取消自動釋放設定

如果您的業務有變化,需要取消自動釋放設定。只需執行命令將自動釋放時間設定為空即可。

  1. set_instance_auto_release_time('i-1111')

完整代碼如下:

注意:釋放雲端服務器需謹慎。

  1. # coding=utf-8
  2. # if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
  3. # if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
  4. # make sure the sdk version is 2.1.2, you can use command 'pip show aliyun-python-sdk-ecs' to check
  5. import json
  6. import logging
  7. from aliyunsdkcore import client
  8. from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest
  9. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  10. from aliyunsdkecs.request.v20140526.ModifyInstanceAutoReleaseTimeRequest import \
  11. ModifyInstanceAutoReleaseTimeRequest
  12. from aliyunsdkecs.request.v20140526.StopInstanceRequest import StopInstanceRequest
  13. # configuration the log output formatter, if you want to save the output to file,
  14. # append ",filename='ecs_invoke.log'" after datefmt.
  15. logging.basicConfig(level=logging.INFO,
  16. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  17. datefmt='%a, %d %b %Y %H:%M:%S')
  18. clt = client.AcsClient('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing')
  19. def stop_instance(instance_id, force_stop=False):
  20. '''
  21. stop one ecs instance.
  22. :param instance_id: instance id of the ecs instance, like 'i-***'.
  23. :param force_stop: if force stop is true, it will force stop the server and not ensure the data
  24. write to disk correctly.
  25. :return:
  26. '''
  27. request = StopInstanceRequest()
  28. request.set_InstanceId(instance_id)
  29. request.set_ForceStop(force_stop)
  30. logging.info("Stop %s command submit successfully.", instance_id)
  31. _send_request(request)
  32. def describe_instance_detail(instance_id):
  33. '''
  34. describe instance detail
  35. :param instance_id: instance id of the ecs instance, like 'i-***'.
  36. :return:
  37. '''
  38. request = DescribeInstancesRequest()
  39. request.set_InstanceIds(json.dumps([instance_id]))
  40. response = _send_request(request)
  41. if response is not None:
  42. instance_list = response.get('Instances').get('Instance')
  43. if len(instance_list) > 0:
  44. return instance_list[0]
  45. def check_auto_release_time_ready(instance_id):
  46. detail = describe_instance_detail(instance_id=instance_id)
  47. if detail is not None:
  48. release_time = detail.get('AutoReleaseTime')
  49. return release_time
  50. def release_instance(instance_id, force=False):
  51. '''
  52. delete instance according instance id, only support after pay instance.
  53. :param instance_id: instance id of the ecs instance, like 'i-***'.
  54. :param force:
  55. if force is false, you need to make the ecs instance stopped, you can
  56. execute the delete action.
  57. If force is true, you can delete the instance even the instance is running.
  58. :return:
  59. '''
  60. request = DeleteInstanceRequest();
  61. request.set_InstanceId(instance_id)
  62. request.set_Force(force)
  63. _send_request(request)
  64. def set_instance_auto_release_time(instance_id, time_to_release = None):
  65. '''
  66. setting instance auto delete time
  67. :param instance_id: instance id of the ecs instance, like 'i-***'.
  68. :param time_to_release: if the property is setting, such as '2017-01-30T00:00:00Z'
  69. it means setting the instance to be release at that time.
  70. if the property is None, it means cancel the auto delete time.
  71. :return:
  72. '''
  73. request = ModifyInstanceAutoReleaseTimeRequest()
  74. request.set_InstanceId(instance_id)
  75. if time_to_release is not None:
  76. request.set_AutoReleaseTime(time_to_release)
  77. _send_request(request)
  78. release_time = check_auto_release_time_ready(instance_id)
  79. logging.info("Check instance %s auto release time setting is %s. ", instance_id, release_time)
  80. def _send_request(request):
  81. '''
  82. send open api request
  83. :param request:
  84. :return:
  85. '''
  86. request.set_accept_format('json')
  87. try:
  88. response_str = clt.do_action(request)
  89. logging.info(response_str)
  90. response_detail = json.loads(response_str)
  91. return response_detail
  92. except Exception as e:
  93. logging.error(e)
  94. if __name__ == '__main__':
  95. logging.info("Release ecs instance by Aliyun OpenApi!")
  96. set_instance_auto_release_time('i-1111', '2017-01-28T06:00:00Z')
  97. # set_instance_auto_release_time('i-1111')
  98. # stop_instance('i-1111')
  99. # release_instance('i-1111')
  100. # release_instance('i-1111', True)

如您想瞭解 ECS 中 API 的其它操作,請參考 ECS中的API操作