为了更方便的实现弹性的资源创建,方便您一次运行多台ECS按量实例来完成应用的开发和部署,我们开放了ECS的批量创建实例接口RunInstances。和目前的CreateInstance相比,RunInstances有下面的优点:
- 单次可以最多创建100台实例,避免重复调用。
- 批量提交一定的ECS实例数目,如果库存不足,则直接失败,避免您创建的实例数目不能满足需求而额外产生费用。
- 实例创建之后,会自动的开始Start,实例会变成
Starting
状态,直至Running
,不需要您调用Start的操作。 - 创建实例的时候指定了
InternetMaxBandwidthOut
,则自动为您分配公网IP,不需要您再调用分配IP的操作。 - 您可以在创建的时候指定自动释放时间,自动释放,不需要您再额外设置自动释放时间。
- 您也可以一次创建100台的SpotInstance,充分满足您的弹性需求。
- 创建的参数保持和CreateInstance保持兼容,提供了
Amount
来设定创建的个数,提供了AutoReleaseTime
来设定自动释放时间。 - 创建返回一个
InstanceIdSets
会记录相关的InstanceIds,您只需要根据实例ID轮询实例状态即可。
下文以Python为示例,其他的版本SDK都需要大于4.4.3
即可。
安装ECS Python SDK
首先确保您已经具备Python的Runtime,本文中使用的Python版本为2.7+。
pip install aliyun-python-sdk-ecs
如果提示您没有权限,请切换sudo
继续执行。
sudo pip install aliyun-python-sdk-ecs
本文使用的sdk版本为4.4.3
, 如果您使用是旧版本的sdk,需要你更新下。
批量创建实例
首先创建RunInstancesRequest
的实例,然后填入相关需要的参数即可。
下面的例子创建了2台实例,并且添加了自动每隔10秒钟检查一次实例的运行状态。直到实例状态变成Running结束创建流程。
# your access key Id
ak_id = "YOU_ACCESS_KEY_ID"
# your access key secret
ak_secret = "YOU_ACCESS_SECRET"
region_id = "cn-beijing"
# your expected instance type
instance_type = "ecs.n4.small"
# 选择的vswitchId
vswitch_id = "vws-xxxxx"
# 使用的镜像信息
image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
# 当前vpc类型的安全组
security_group_id = "sg-xxxxx"
# instance number to lunch, support 1-100, default value is 100
amount = 2;
# instance auto delete time 按照 ISO8601 标准表示,并需要使用 UTC 时间。格式为 yyyy-MM-ddTHH:mm:ssZ 。 最短在当前时间之后半小时。最长不能超过当前时间起三年
auto_release_time = "2017-12-05T22:40:00Z"
clt = client.AcsClient(ak_id, ak_secret, 'cn-beijing')
# create instance automatic running
def batch_create_instance():
request = build_request()
request.set_Amount(amount)
_execute_request(request)
def _execute_request(request):
response = _send_request(request)
if response.get('Code') is None:
instance_ids = response.get('InstanceIdSets').get('InstanceIdSet')
running_amount = 0
while running_amount < amount:
time.sleep(10)
running_amount = check_instance_running(instance_ids)
print("ecs instance %s is running", instance_ids)
def check_instance_running(instance_ids):
request = DescribeInstancesRequest()
request.set_InstanceIds(json.dumps(instance_ids))
response = _send_request(request)
if response.get('Code') is None:
instances_list = response.get('Instances').get('Instance')
running_count = 0
for instance_detail in instances_list:
if instance_detail.get('Status') == "Running":
running_count += 1
return running_count
def build_request():
request = RunInstancesRequest()
request.set_ImageId(image_id)
request.set_VSwitchId(vswitch_id)
request.set_SecurityGroupId(security_group_id)
request.set_InstanceName("Instance12-04")
request.set_InstanceType(instance_type)
return request
# send open api request
def _send_request(request):
request.set_accept_format('json')
try:
response_str = clt.do_action(request)
logging.info(response_str)
response_detail = json.loads(response_str)
return response_detail
except Exception as e:
logging.error(e)
批量创建实例并自动分配公网IP
相比上面的代码,我们只需要添加一行属性,指定公网的带宽即可。下面的例子中我们默认给实例都分配了1M的按流量带宽。
# create instance with public ip.
def batch_create_instance_with_public_ip():
request = build_request()
request.set_Amount(amount)
request.set_InternetMaxBandwidthOut(1)
_execute_request(request)
批量创建实例并自动设置自动释放时间
相比上面的代码,我们只需要添加一行属性,实例的自动释放时间即可。 自动释放时间按照 ISO8601 标准表示,并需要使用 UTC 时间。格式为 yyyy-MM-ddTHH:mm:ssZ 。 最短在当前时间之后半小时。最长不能超过当前时间起三年。
# create instance with auto release time.
def batch_create_instance_with_auto_release_time():
request = build_request()
request.set_Amount(amount)
request.set_AutoReleaseTime(auto_release_time)
_execute_request(request)
完整代码如下
# coding=utf-8
# if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
# if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
# make sure the sdk version is 4.4.3, you can use command 'pip show aliyun-python-sdk-ecs' to check
import json
import logging
import time
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.RunInstancesRequest import RunInstancesRequest
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S')
# your access key Id
ak_id = "YOU_ACCESS_KEY_ID"
# your access key secret
ak_secret = "YOU_ACCESS_SECRET"
region_id = "cn-beijing"
# your expected instance type
instance_type = "ecs.n4.small"
# 选择的vswitchId
vswitch_id = "vws-xxxxx"
# 使用的镜像信息
image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
# 当前vpc类型的安全组
security_group_id = "sg-xxxxx"
# instance number to lunch, support 1-100, default value is 100
amount = 2;
# instance auto delete time 按照 ISO8601 标准表示,并需要使用 UTC 时间。格式为 yyyy-MM-ddTHH:mm:ssZ 。 最短在当前时间之后半小时。最长不能超过当前时间起三年
auto_release_time = "2017-12-05T22:40:00Z"
clt = client.AcsClient(ak_id, ak_secret, 'cn-beijing')
# create instance automatic running
def batch_create_instance():
request = build_request()
request.set_Amount(amount)
_execute_request(request)
# create instance with public ip.
def batch_create_instance_with_public_ip():
request = build_request()
request.set_Amount(amount)
request.set_InternetMaxBandwidthOut(1)
_execute_request(request)
# create instance with auto release time.
def batch_create_instance_with_auto_release_time():
request = build_request()
request.set_Amount(amount)
request.set_AutoReleaseTime(auto_release_time)
_execute_request(request)
def _execute_request(request):
response = _send_request(request)
if response.get('Code') is None:
instance_ids = response.get('InstanceIdSets').get('InstanceIdSet')
running_amount = 0
while running_amount < amount:
time.sleep(10)
running_amount = check_instance_running(instance_ids)
print("ecs instance %s is running", instance_ids)
def check_instance_running(instance_ids):
request = DescribeInstancesRequest()
request.set_InstanceIds(json.dumps(instance_ids))
response = _send_request(request)
if response.get('Code') is None:
instances_list = response.get('Instances').get('Instance')
running_count = 0
for instance_detail in instances_list:
if instance_detail.get('Status') == "Running":
running_count += 1
return running_count
def build_request():
request = RunInstancesRequest()
request.set_ImageId(image_id)
request.set_VSwitchId(vswitch_id)
request.set_SecurityGroupId(security_group_id)
request.set_InstanceName("Instance12-04")
request.set_InstanceType(instance_type)
return request
# send open api request
def _send_request(request):
request.set_accept_format('json')
try:
response_str = clt.do_action(request)
logging.info(response_str)
response_detail = json.loads(response_str)
return response_detail
except Exception as e:
logging.error(e)
if __name__ == '__main__':
print "hello ecs batch create instance"
# batch_create_instance()
# batch_create_instance_with_public_ip()
# batch_create_instance_with_auto_release_time()
通过RunInstances将简化您的资源创建和运行管理。更多的需求您可以留言或者工单提交对我们的反馈。谢谢!