All Products
Search
Document Center

Elastic Compute Service:Create multiple ECS instances at a time

Last Updated:Sep 05, 2023

You can call the RunInstances operation to create multiple pay-as-you-go or subscription Elastic Compute Service (ECS) instances at a time. This allows you to scale resources with ease to meet requirements for developing and deploying applications.

Prerequisites

An AccessKey pair is created before you call the RunInstances operation. For more information, see Create an AccessKey pair.

Important

Do not use the AccessKey pair of your Alibaba Cloud account. If you use the AccessKey pair of your Alibaba Cloud account, the AccessKey pair may be disclosed and then all resources in your account may be exposed to risks. We recommend that you use a RAM user to call API operations. This reduces the risk of the AccessKey pair of your Alibaba Cloud account being leaked.

Background information

Compared with CreateInstance, RunInstances has the following advantages:

  • Up to 100 instances can be created at a time.

  • After an instance is created, the instance automatically enters the Starting state and then the Running state. You do not need to call the StartInstance operation to start the instance.

  • If you specify InternetMaxBandwidthOut when you call the RunInstances operation to create instances, public IP addresses are automatically assigned to the instances. You do not need to call an API operation to assign public IP addresses to the instances.

  • Up to 100 preemptible instances can be created at a time to meet your business requirements.

  • In addition to the parameters that you can find in CreateInstance, RunInstances also provides the Amount parameter that specifies the number of instances that you want to create and the AutoReleaseTime parameter that specifies the automatic release time of instances.

  • The value of the InstanceIdSets response parameter consists of instance IDs. You can query the status of the instances based on their IDs. For more information, see DescribeInstanceStatus.

This topic provides complete sample code that can be used to create multiple ECS instances at a time. For more information, see the Complete sample code section of this topic. This topic also explains the sample code. For more information, see the following sections of this topic:

Install ECS SDK for Python

Make sure that you have prepared the Python runtime. The Python version must be 2.7 or later.

The version of ECS SDK for Python must be 4.4.3 or later. If you are using an earlier version, update the SDK. Run the following command to install ECS SDK for Python:

pip install aliyun-python-sdk-ecs

If you are prompted that you do not have the required permissions, run the following sudo command to continue the installation:

sudo pip install aliyun-python-sdk-ecs

Complete sample code

#  coding=utf-8

import json
import logging
import time
import os
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')

# Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
# If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code shows how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. The sample code is for reference only. We recommend that you use Security Token Service (STS) tokens, which provides higher security.
ak_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
ak_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']

# Specify the ID of the region in which to create instances. 
region_id = "cn-hangzhou"

clt = client.AcsClient(ak_id, ak_secret, region_id)

# Specify an instance type. 
instance_type = "ecs.g6.large"

# Specify a vSwitch. 
vswitch_id = "vsw-bp1ddbrxdlrcbim46****"

# Specify an image. 
image_id = "<imageid>"

# Specify a security group of the Virtual Private Cloud (VPC) type. 
security_group_id = "sg-bp1i4c0xgqxadew2****"

# Specify the number of instances that you want to create. Valid values: 1 to 100. Default value: 1. 
amount = 2

# Specify a time at which to automatically release the instances. Specify the time in the ISO 8601 standard in the YYYY-MM-DDThh:mm:ssZ format. The time must be in UTC. The specified time must be at least 30 minutes and at most three years later than the current time. 
auto_release_time = "2020-04-17T18:20:00Z"

# Create and start instances. 
def create_multiple_instances():
    request = build_request()
    request.set_Amount(amount)
    _execute_request(request)

# Create instances and assign public IP addresses. 
def create_multiple_instances_with_public_ip():
    request = build_request()
    request.set_Amount(amount)
    request.set_InternetMaxBandwidthOut(1)
    _execute_request(request)

# Create instances and specify a time at which to automatically release the instances. 
def create_multiple_instances_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("Instance-Name")
    request.set_InstanceType(instance_type)
    return request

# Send the 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")
    # Create and start instances. 
    create_multiple_instances()
    # Create instances that are assigned public IP addresses. 
    # create_multiple_instances_with_public_ip()
    # Create instances and specify a time at which to automatically release the instances. 
    # create_multiple_instances_with_auto_release_time()

Create multiple instances at a time

Call the RunInstances operation with the required parameters to create multiple instances.

In this example, two instances are created. The status of the instances is automatically checked every 10 seconds. The instance creation process is complete when the instances enter the Running state.

# Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime. 
# If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code shows how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. The sample code is for reference only. We recommend that you use STS tokens, which provides higher security.
ak_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
ak_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']

# Specify the ID of the region in which to create instances. 
region_id = "cn-hangzhou"

clt = client.AcsClient(ak_id, ak_secret, region_id)

# Specify an instance type. 
instance_type = "ecs.g6.large"

# Specify a vSwitch. 
vswitch_id = "vsw-bp1ddbrxdlrcbim46****"

# Specify an image. 
image_id = "<imageid>"

# Specify a security group of the VPC type. 
security_group_id = "sg-bp1i4c0xgqxadew2****"

# Specify the number of instances that you want to create. Valid values: 1 to 100. Default value: 1. 
amount = 2

# Specify a time at which to automatically release the instances. Specify the time in the ISO 8601 standard in the YYYY-MM-DDThh:mm:ssZ format. The time must be in UTC. The specified time must be at least 30 minutes and at most three years later than the current time. 
auto_release_time = "2020-04-17T18:20:00Z"

# Create and start instances. 
def create_multiple_instances():
    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("Instance-Name")
    request.set_InstanceType(instance_type)
    return request

# Send the 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)

Create multiple instances at a time and assign public IP addresses

When you call RunInstances, you can specify InternetMaxBandwidthOut in the request to allocate a specified amount of public bandwidth to each instance. This way, a public IP address is automatically assigned to each created instance. In this example, the instances are assigned a bandwidth of 1 Mbit/s.

# Create instances and assign public IP addresses. 
def create_multiple_instances_with_public_ip():
    request = build_request()
    request.set_Amount(amount)
    request.set_InternetMaxBandwidthOut(1)
    _execute_request(request)

Create multiple instances at a time and specify an automatic release time for the instances

When you call RunInstances, you can specify AutoReleaseTime in the request to set the automatic release time for instances. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time must be in UTC. The specified time must be at least 30 minutes and at most three years later than the current time. For more information, see ISO 8601 Time Format.

# Create instances and specify a time at which to automatically release the instances. 
def create_multiple_instances_with_auto_release_time():
    request = build_request()
    request.set_Amount(amount)
    request.set_AutoReleaseTime(auto_release_time)
    _execute_request(request)