全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网
云服务器 ECS

使用OpenAPI弹性释放ECS实例

更新时间:2017-06-07 13:26:11

云服务器 ECS 的一个重要特性就是按需创建资源。您可以在业务高峰期按需弹性地进行自定义资源创建,完成业务计算时释放资源。本篇将提供若干 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操作

本文导读目录