edit-icon download-icon

Renew an instance

Last Updated: Mar 19, 2018

Lifecycle is important to ECS instances of the Subscription billing method. If you fail to renew your ECS instance on time, the instance may be locked or even released, thus affecting your service continuity. In addition to the ECS console or the ECS purchase page, Alibaba Cloud provides you with APIs to view the resource expiration time and renew your instance.

This article covers the following APIs:

Query ECS instances by expiration time

Use the DescribeInstances interface to query the instances that will expire within the specified time range by setting the filter parameters ExpiredStartTime and ExpiredEndTime. The time parameters follow the ISO8601 standard in UTC time, using the format yyyy-MM-ddTHH:mmZ. The system returns a list of instances that will expire within the specified time range.

Note: If you want to filter by security group, add the security group ID.

  1. INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING = '2017-01-22T00:00Z'
  2. INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING = '2017-01-28T00:00Z'
  3. def describe_need_renew_instance(page_size=100, page_number=1, instance_id=None,
  4. check_need_renew=True, security_group_id=None):
  5. request = DescribeInstancesRequest()
  6. if check_need_renew is True:
  7. request.set_Filter3Key("ExpiredStartTime")
  8. request.set_Filter3Value(INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING)
  9. request.set_Filter4Key("ExpiredEndTime")
  10. request.set_Filter4Value(INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING)
  11. if instance_id is not None:
  12. request.set_InstanceIds(json.dumps([instance_id]))
  13. if security_group_id:
  14. request.set_SecurityGroupId(security_group_id)
  15. request.set_PageNumber(page_number)
  16. request.set_PageSize(page_size)
  17. return _send_request(request)

Query and enable automatic ECS instance renewal

You can use the ModifyInstanceAutoRenewAttribute interface to query and set automatic renewal. The API supports only ECS instances of the Subscription billing method. If you use the API on a Pay-As-You-Go instance, an error will be returned.

Query automatic renewal setting

To query the automatic renewal setting, only the instance ID is required. You can query the automatic renewal status of up to 100 ECS instances of the Subscription billing method at a time. Use commas to separate multiple instance IDs.

  1. # check the instances is renew or not
  2. def describe_auto_renew(instance_ids, expected_auto_renew=True):
  3. describe_request = DescribeInstanceAutoRenewAttributeRequest()
  4. describe_request.set_InstanceId(instance_ids)
  5. response_detail = _send_request(request=describe_request)
  6. failed_instance_ids = ''
  7. if response_detail is not None:
  8. attributes = response_detail.get('InstanceRenewAttributes').get('InstanceRenewAttribute')
  9. if attributes:
  10. for item in attributes:
  11. auto_renew_status = item.get('AutoRenewEnabled')
  12. if auto_renew_status != expected_auto_renew:
  13. failed_instance_ids += item.get('InstanceId') + ','
  14. describe_auto_renew('i-1111,i-2222')

The following content is returned:

  1. {"InstanceRenewAttributes":{"InstanceRenewAttribute":[{"Duration":0,"InstanceId":"i-1111","AutoRenewEnabled":false},{"Duration":0,"InstanceId":"i-2222","AutoRenewEnabled":false}]},"RequestId":"71FBB7A5-C793-4A0D-B17E-D6B426EA746A"}

If automatic renewal is set, the returned attribute AutoRenewEnabled is true. If automatic renewal is not set, the attribute is false.

Enable automatic renewal for ECS instances

To enable automatic renwal for ECS instances, three input parameters are required:

  • InstanceId: You can set automatic renewal for up to 100 ECS instances of the Subscription billing method at a time. Use commas to separate multiple instance IDs.
  • Duration: Set to 1, 2, 3, 6, or 12, in unit of Month.
  • AutoRenew: Set to true to enable automatic renewal.

    Note: Set to false to disable automatic renewal.

  1. def setting_instance_auto_renew(instance_ids, auto_renew = True):
  2. logging.info('execute enable auto renew ' + instance_ids)
  3. request = ModifyInstanceAutoRenewAttributeRequest();
  4. request.set_Duration(1);
  5. request.set_AutoRenew(auto_renew);
  6. request.set_InstanceId(instance_ids)
  7. _send_request(request)

When the operation is successful, the following response is returned:

  1. {"RequestId":"7DAC9984-AAB4-43EF-8FC7-7D74C57BE46D"}

You can perform a query after successful renewal. The system will return the renewal duration and the status of automatic renewal (true/false).

  1. {"InstanceRenewAttributes":{"InstanceRenewAttribute":[{"Duration":1,"InstanceId":"i-1111","AutoRenewEnabled":true},{"Duration":1,"InstanceId":"i-2222","AutoRenewEnabled":true}]},"RequestId":"7F4D14B0-D0D2-48C7-B310-B1DF713D4331"}

Complete example code

  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.DescribeInstanceAutoRenewAttributeRequest import \
  9. DescribeInstanceAutoRenewAttributeRequest
  10. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  11. from aliyunsdkecs.request.v20140526.ModifyInstanceAutoRenewAttributeRequest import \
  12. ModifyInstanceAutoRenewAttributeRequest
  13. from aliyunsdkecs.request.v20140526.RenewInstanceRequest import RenewInstanceRequest
  14. logging.basicConfig(level=logging.INFO,
  15. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  16. datefmt='%a, %d %b %Y %H:%M:%S')
  17. clt = client.AcsClient('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing')
  18. # data format in UTC, only support passed the value for minute, seconds is not support.
  19. INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING = '2017-01-22T00:00Z'
  20. INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING = '2017-01-28T00:00Z'
  21. def renew_job(page_size=100, page_number=1, check_need_renew=True, security_group_id=None):
  22. response = describe_need_renew_instance(page_size=page_size, page_number=page_number,
  23. check_need_renew=check_need_renew,
  24. security_group_id=security_group_id)
  25. response_list = response.get('Instances').get('Instance')
  26. logging.info("%s instances need to renew", str(response.get('TotalCount')))
  27. if response_list > 0:
  28. instance_ids = ''
  29. for item in response_list:
  30. instance_id = item.get('InstanceId')
  31. instance_ids += instance_id + ','
  32. renew_instance(instance_id=instance_id)
  33. logging.info("%s execute renew action ready", instance_ids)
  34. def describe_need_renew_instance(page_size=100, page_number=1, instance_id=None,
  35. check_need_renew=True, security_group_id=None):
  36. request = DescribeInstancesRequest()
  37. if check_need_renew is True:
  38. request.set_Filter3Key("ExpiredStartTime")
  39. request.set_Filter3Value(INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING)
  40. request.set_Filter4Key("ExpiredEndTime")
  41. request.set_Filter4Value(INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING)
  42. if instance_id is not None:
  43. request.set_InstanceIds(json.dumps([instance_id]))
  44. if security_group_id:
  45. request.set_SecurityGroupId(security_group_id)
  46. request.set_PageNumber(page_number)
  47. request.set_PageSize(page_size)
  48. return _send_request(request)
  49. # check the instances is renew or not
  50. def describe_instance_auto_renew_setting(instance_ids, expected_auto_renew=True):
  51. describe_request = DescribeInstanceAutoRenewAttributeRequest()
  52. describe_request.set_InstanceId(instance_ids)
  53. response_detail = _send_request(request=describe_request)
  54. failed_instance_ids = ''
  55. if response_detail is not None:
  56. attributes = response_detail.get('InstanceRenewAttributes').get('InstanceRenewAttribute')
  57. if attributes:
  58. for item in attributes:
  59. auto_renew_status = item.get('AutoRenewEnabled')
  60. if auto_renew_status != expected_auto_renew:
  61. failed_instance_ids += item.get('InstanceId') + ','
  62. if len(failed_instance_ids) > 0:
  63. logging.error("instance %s auto renew not match expect %s.", failed_instance_ids,
  64. expected_auto_renew)
  65. def setting_instance_auto_renew(instance_ids, auto_renew=True):
  66. logging.info('execute enable auto renew ' + instance_ids)
  67. request = ModifyInstanceAutoRenewAttributeRequest();
  68. request.set_Duration(1);
  69. request.set_AutoRenew(auto_renew);
  70. request.set_InstanceId(instance_ids)
  71. _send_request(request)
  72. describe_instance_auto_renew_setting(instance_ids, auto_renew)
  73. # if using the instance id can be found means the instance is not renew successfully.
  74. def check_instance_need_renew(instance_id):
  75. response = describe_need_renew_instance(instance_id=instance_id)
  76. if response is not None:
  77. return response.get('TotalCount') == 1
  78. return False
  79. # Renew an instance for a month
  80. def renew_instance(instance_id, period='1'):
  81. need_renew = check_instance_need_renew(instance_id)
  82. if need_renew:
  83. _renew_instance_action(instance_id=instance_id, period=period)
  84. # describe_need_renew_instance(instance_id=instance_id, check_need_renew=False)
  85. def _renew_instance_action(instance_id, period='1'):
  86. request = RenewInstanceRequest()
  87. request.set_Period(period)
  88. request.set_InstanceId(instance_id)
  89. response = _send_request(request)
  90. logging.info('renew %s ready, output is %s ', instance_id, response)
  91. def _send_request(request):
  92. request.set_accept_format('json')
  93. try:
  94. response_str = clt.do_action(request)
  95. logging.info(response_str)
  96. response_detail = json.loads(response_str)
  97. return response_detail
  98. except Exception as e:
  99. logging.error(e)
  100. if __name__ == '__main__':
  101. logging.info("Renew ECS Instance by OpenApi!")
  102. # Query whether there is any instance that needs to be renewed within the specified time range.
  103. describe_need_renew_instance()
  104. # Renew an instance by direct fee deduction
  105. renew_instance('i-1111')
  106. # Query the status of automatic renewal
  107. # describe_instance_auto_renew_setting('i-1111,i-2222')
  108. # Set automatic instance renewal
  109. # setting_instance_auto_renew('i-1111,i-2222')

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

Thank you! We've received your feedback.