edit-icon download-icon

Create multiple instances at a time

Last Updated: Jul 04, 2018

RunInstances can create multiple ECS instances at a time. It helps you fast develop and deploy application. Compared with CreateInstance, RunInstances has the following benefits:

  • RunInstances contains Amount to create and automatically run up to 100 instances or preemptible instances for one request.
  • Instances have Internet IPs allocated if you set the value of InternetMaxBandwidthOut greater than 0.
  • Release plan can be scheduled by setting the AutoReleaseTime.
  • The error codes and available parameters of RunInstances are completely compatible with CreateInstance.
  • Status polling of the created instances is allowed since InstanceIdSets lists all the InstanceIds after the request.

Prerequisites

  • Here we use pip to download necessary SDK. Make sure you have installed pip for accessing to the ECS Python SDK.

  • Make sure you have created an AccessKey.

Note: Do not use the AccessKey of the primary account. If it is disclosed, your resources may be unsafe. Use the AccessKey of an RAM user account to reduce the risk of AccessKey disclosure.

Install ECS Python SDK

Make sure that you have runtime for Python. In this document, we take a version later than Python 2.7 as an example and the SDK version is 4.4.3.

  1. pip install aliyun-python-sdk-ecs

If you get any message indicating that you have no operation permission, switch to sudo.

  1. sudo pip install aliyun-python-sdk-ecs

Create instances

In this example, we create two instances and specify to automatically check the instance status every 10 seconds. The creation procedure ends when the instance status turns intoRunning.

Create RunInstancesRequest object and then enter the related parameters:

  1. # Your AccessKey Id
  2. ak_id = "YOU_ACCESS_KEY_ID"
  3. # Your AccessKey secret
  4. ak_secret = "YOU_ACCESS_SECRET"
  5. region_id = "cn-beijing"
  6. # Your expected instance type
  7. instance_type = "ecs.n4.small"
  8. # The selected vswitchId
  9. vswitch_id = "vws-xxxxx"
  10. # The selected image info
  11. image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
  12. # The selected security group of VPC network
  13. security_group_id = "sg-xxxxx"
  14. # Instance number to start, support 1-100, and default value is 100
  15. amount = 2;
  16. # The auto release time is in accordance with ISO8601 and must be UTC. The format is `yyyy-MM-ddTHH:mm:ssZ`. The release time must be at least 30 minutes later than the current time and less than 3 years from the current time.
  17. auto_release_time = "2017-12-05T22:40:00Z"
  18. clt = client.AcsClient(ak_id, ak_secret, 'cn-beijing')
  19. # create instance automatic running
  20. def batch_create_instance():
  21. request = build_request()
  22. request.set_Amount(amount)
  23. _execute_request(request)
  24. def _execute_request(request):
  25. response = _send_request(request)
  26. if response.get('Code') is None:
  27. instance_ids = response.get('InstanceIdSets').get('InstanceIdSet')
  28. running_amount = 0
  29. while running_amount < amount:
  30. time.sleep(10)
  31. running_amount = check_instance_running(instance_ids)
  32. print("ecs instance %s is running", instance_ids)
  33. def check_instance_running(instance_ids):
  34. request = DescribeInstancesRequest()
  35. request.set_InstanceIds(json.dumps(instance_ids))
  36. response = _send_request(request)
  37. if response.get('Code') is None:
  38. instances_list = response.get('Instances').get('Instance')
  39. running_count = 0
  40. for instance_detail in instances_list:
  41. if instance_detail.get('Status') == "Running":
  42. running_count += 1
  43. return running_count
  44. def build_request():
  45. request = RunInstancesRequest()
  46. request.set_ImageId(image_id)
  47. request.set_VSwitchId(vswitch_id)
  48. request.set_SecurityGroupId(security_group_id)
  49. request.set_InstanceName("Instance12-04")
  50. request.set_InstanceType(instance_type)
  51. return request
  52. # send open api request
  53. def _send_request(request):
  54. request.set_accept_format('json')
  55. try:
  56. response_str = clt.do_action(request)
  57. logging.info(response_str)
  58. response_detail = json.loads(response_str)
  59. return response_detail
  60. except Exception as e:
  61. logging.error(e)

Create instances with Internet IP

Create instances and add a line of attribute to specify Internet bandwidth. In this example, we assign 1 Mbit/s bandwidth for each instance.

  1. # create instance with public ip.
  2. def batch_create_instance_with_public_ip():
  3. request = build_request()
  4. request.set_Amount(amount)
  5. request.set_InternetMaxBandwidthOut(1)
  6. _execute_request(request)

Create instances with auto release time

Create instances and add a line of attribute to specify auto release time for instances. The auto release time is in accordance with ISO8601 and must be UTC. The format is YYYY-MM-DDTHH:mm:ssZ. The release time cannot be 30 minutes earlier than the current time or more than 3 years from the current time.

  1. # create instance with auto release time.
  2. def batch_create_instance_with_auto_release_time():
  3. request = build_request()
  4. request.set_Amount(amount)
  5. request.set_AutoReleaseTime(auto_release_time)
  6. _execute_request(request)

Complete example code

The complete example code is as the following.

  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 4.4.3, you can use command 'pip show aliyun-python-sdk-ecs' to check
  5. import json
  6. import logging
  7. import time
  8. from aliyunsdkcore import client
  9. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  10. from aliyunsdkecs.request.v20140526.RunInstancesRequest import RunInstancesRequest
  11. logging.basicConfig(level=logging.INFO,
  12. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  13. datefmt='%a, %d %b %Y %H:%M:%S')
  14. # Your AccessKey Id
  15. ak_id = "YOU_ACCESS_KEY_ID"
  16. # Your AccessKey secret
  17. ak_secret = "YOU_ACCESS_SECRET"
  18. region_id = "cn-beijing"
  19. # Your expected instance type
  20. instance_type = "ecs.n4.small"
  21. # The selected vswitchId
  22. vswitch_id = "vws-xxxxx"
  23. # The selected image info
  24. image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
  25. # The selected security group of VPC network
  26. security_group_id = "sg-xxxxx"
  27. # Instance number to start, support 1-100, and default value is 100
  28. amount = 2;
  29. # The auto release time is in accordance with ISO8601 and must be UTC. The format is `YYYY-MM-DDTHH:mm:ssZ`. The release time must be at least 30 minutes later than the current time and less than 3 years from the current time.
  30. auto_release_time = "2017-12-05T22:40:00Z"
  31. clt = client.AcsClient(ak_id, ak_secret, 'cn-beijing')
  32. # create instance automatic running
  33. def batch_create_instance():
  34. request = build_request()
  35. request.set_Amount(amount)
  36. _execute_request(request)
  37. # create instance with Internet IP.
  38. def batch_create_instance_with_public_ip():
  39. request = build_request()
  40. request.set_Amount(amount)
  41. request.set_InternetMaxBandwidthOut(1)
  42. _execute_request(request)
  43. # create instance with auto release time.
  44. def batch_create_instance_with_auto_release_time():
  45. request = build_request()
  46. request.set_Amount(amount)
  47. request.set_AutoReleaseTime(auto_release_time)
  48. _execute_request(request)
  49. def _execute_request(request):
  50. response = _send_request(request)
  51. if response.get('Code') is None:
  52. instance_ids = response.get('InstanceIdSets').get('InstanceIdSet')
  53. running_amount = 0
  54. while running_amount < amount:
  55. time.sleep(10)
  56. running_amount = check_instance_running(instance_ids)
  57. print("ecs instance %s is running", instance_ids)
  58. def check_instance_running(instance_ids):
  59. request = DescribeInstancesRequest()
  60. request.set_InstanceIds(json.dumps(instance_ids))
  61. response = _send_request(request)
  62. if response.get('Code') is None:
  63. instances_list = response.get('Instances').get('Instance')
  64. running_count = 0
  65. for instance_detail in instances_list:
  66. if instance_detail.get('Status') == "Running":
  67. running_count += 1
  68. return running_count
  69. def build_request():
  70. request = RunInstancesRequest()
  71. request.set_ImageId(image_id)
  72. request.set_VSwitchId(vswitch_id)
  73. request.set_SecurityGroupId(security_group_id)
  74. request.set_InstanceName("Instance12-04")
  75. request.set_InstanceType(instance_type)
  76. return request
  77. # Send your request
  78. def _send_request(request):
  79. request.set_accept_format('json')
  80. try:
  81. response_str = clt.do_action(request)
  82. logging.info(response_str)
  83. response_detail = json.loads(response_str)
  84. return response_detail
  85. except Exception as e:
  86. logging.error(e)
  87. if __name__ == '__main__':
  88. print "hello ecs batch create instance"
  89. # batch_create_instance()
  90. # batch_create_instance_with_public_ip()
  91. # batch_create_instance_with_auto_release_time()
Thank you! We've received your feedback.