edit-icon download-icon

Release an instance

Last Updated: Sep 19, 2017

One important feature of ECS is on-demand resource creation. You can create custom resources elastically on demand during peak service hours, and then release those resources after service computing is completed. This document describes how to easily release ECS instances and achieve elasticity.

This document covers the following APIs:

After an ECS instance is released, the physical resources used by the instance are recycled, including disks and snapshots. The data of the instance is completely lost and can never be recovered. If you want to retain the data, we recommend that you create snapshots of disks before releasing the ECS instance. The snapshots can be directly used to create a new ECS instance.

To release an ECS instance, you must stop it first. If any application is affected after the ECS instance is stopped, restart the instance.

Stop an ECS instance

Use the StopInstance interface to stop an ECS instance, regardless of the billing method of the instance. The stop command is as follows. When the ForceStop parameter is set to true, the ECS instance is stopped directly but data is not necessarily written to a disk, similar to power failure. Therefore, if you want to release an instance, set ForceStop to 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)

Release an ECS instance

Use the DeleteInstance interface to release an ECS instance.

When the ECS instance is in the Stopped status, you can release it. The API has only two request parameters:

  • InstanceId: Instance ID
  • Force: If this parameter is set to “true”, the ECS instance is released forcibly even when it is not in the Stopped status. Use caution when setting this parameter. Release by mistake may affect your services.
  1. def release_instance(instance_id, force=False):
  2. '''
  3. delete instance according instance id, only support after pay instance.
  4. :param instance_id: instance id of the ecs instance, like 'i-***'.
  5. :param force:
  6. if force is false, you need to make the ecs instance stopped, you can
  7. execute the delete action.
  8. If force is true, you can delete the instance even the instance is running.
  9. :return:
  10. '''
  11. request = DeleteInstanceRequest();
  12. request.set_InstanceId(instance_id)
  13. request.set_Force(force)
  14. _send_request(request)

The following response is returned when an ECS instance is released successfully:

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

If you release an ECS instance when it is not in the Stopped status, an error occurs:

  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."}

Set the automatic release time for an ECS instance

You can set the automatic release time for an ECS instance to simplify instance management. When the set time is reached, Alibaba Cloud releases your ECS instance automatically. Use the ModifyInstanceAutoReleaseTime to set the automatic release time for an ECS instance.

Note:
The automatic release time follows the ISO8601 standard in UTC time. The format is yyyy-MM-ddTHH:mm:ssZ. If the seconds place is not 00, it is automatically set to start from the current minute.
The automatic release time must be at least half an hour later than the current time, and must not be more than 3 years since the current time.

  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)

Run the command set_instance_auto_release_time('i-1111', '2017-01-30T00:00:00Z') to set the time. Then you can use the DescribeInstances to query the automatic release time.

  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

If you want to cancel the automatic release due to service changes, run the set_instance_auto_release_time('i-1111') command to set the automatic release time to null.

Complete example code

Note: Proceed with caution when releasing ECS instances.

  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)

If you want to learn other API operations in ECS, see ECS API operation.

Thank you! We've received your feedback.