全部产品
阿里云办公

批量创建 ECS 实例

更新时间:2018-06-14 17:44:40

RunInstances 批量创建实例接口可以帮助您一次创建多台 ECS 按量付费实例来完成应用的开发和部署,方便实现弹性的资源创建。

CreateInstance 接口相比,RunInstances 接口有下面的优点:

  • 单次可以最多创建 100 台实例,避免重复调用。
  • 实例创建之后,实例会自动变成 Starting 状态,然后变成 Running 状态,不需要您调用 StartInstance 的操作。
  • 创建实例的时候指定了 InternetMaxBandwidthOut,则自动为您分配公网 IP,不需要您再调用分配 IP 的操作。
  • 您也可以一次创建 100 台抢占式实例,充分满足您的弹性需求。
  • 创建的参数保持和 CreateInstance 保持兼容,增加了 Amount 参数来设定创建的个数,以及 AutoReleaseTime 参数来设定自动释放时间,不需要您再额外设置自动释放时间。
  • 创建返回一个 InstanceIdSets 会记录相关的 InstanceIds,您只需要根据实例 ID 轮询实例状态即可。

前提条件

调用 API 前,您需要 创建 AccessKey

注意:禁止使用主账号 AK,因为主账号 AK 泄露会威胁您所有资源的安全。请使用子账号 AK 进行操作,可有效降低 AK 泄露的风险。

安装 ECS Python SDK

首先确保您已经具备 Python 的 Runtime,本文中使用的 Python 版本为 2.7+。

这里以 Python 为示例,其他的版本 SDK 大于 4.4.3 即可。

  1. pip install aliyun-python-sdk-ecs

如果提示您没有权限,请切换sudo继续执行。

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

本文使用的 SDK 版本为 4.4.3, 如果您使用是旧版本的 SDK,需要更新。

批量创建实例

首先创建 RunInstancesRequest 的实例,然后填入相关需要的参数即可。

下面的例子创建了 2 台实例,并且添加了自动每隔 10 秒钟检查一次实例的运行状态。直到实例状态变成Running结束创建流程。

  1. # your access key Id
  2. ak_id = "YOU_ACCESS_KEY_ID"
  3. # your access key secret
  4. ak_secret = "YOU_ACCESS_SECRET"
  5. region_id = "cn-beijing"
  6. # your expected instance type
  7. instance_type = "ecs.n4.small"
  8. # 选择的vswitchId
  9. vswitch_id = "vws-xxxxx"
  10. # 使用的镜像信息
  11. image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
  12. # 当前vpc类型的安全组
  13. security_group_id = "sg-xxxxx"
  14. # instance number to launch, support 1-100, default value is 100
  15. amount = 2;
  16. # instance auto delete time 按照 ISO8601 标准表示,并需要使用 UTC 时间。格式为 yyyy-MM-ddTHH:mm:ssZ 。 最短在当前时间之后半小时。最长不能超过当前时间起三年
  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)

批量创建实例并自动分配公网 IP

相比批量创建实例的代码,只需要添加一行属性,指定公网的带宽即可。下面的例子中默认给实例都分配了 1 M 的按流量带宽。

  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)

批量创建实例并自动设置自动释放时间

相比批量创建实例的代码,只需要添加一行属性,指定实例的自动释放时间即可。自动释放时间按照 ISO8601 标准表示,并需要使用 UTC 时间,格式为 yyyy-MM-ddTHH:mm:ssZ。最短在当前时间之后半小时,最长不能超过当前时间起三年。

  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)

完整代码示例

以上操作完整的代码示例如下所示。

  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 access key Id
  15. ak_id = "YOU_ACCESS_KEY_ID"
  16. # your access key secret
  17. ak_secret = "YOU_ACCESS_SECRET"
  18. region_id = "cn-beijing"
  19. # your expected instance type
  20. instance_type = "ecs.n4.small"
  21. # 选择的vswitchId
  22. vswitch_id = "vws-xxxxx"
  23. # 使用的镜像信息
  24. image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
  25. # 当前vpc类型的安全组
  26. security_group_id = "sg-xxxxx"
  27. # instance number to launch, support 1-100, default value is 100
  28. amount = 2;
  29. # instance auto delete time 按照 ISO8601 标准表示,并需要使用 UTC 时间。格式为 yyyy-MM-ddTHH:mm:ssZ 。 最短在当前时间之后半小时。最长不能超过当前时间起三年
  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 public 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 open api 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()