All Products
Search
Document Center

Elastic Compute Service:Create multiple ECS instances at a time

Last Updated:May 25, 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 this operation. For more information, see Obtain 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 within your account may be exposed to risks. We recommend that you use a RAM user to call API operations. This minimizes the possibility of disclosing the AccessKey pair of your Alibaba Cloud account.

Background information

Compared with CreateInstance, RunInstances has the following advantages:

  • A maximum of 100 ECS instances can be created at a time.

  • After an ECS 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 the InternetMaxBandwidthOut parameter when you call this operation to create an ECS instance, a public IP address is automatically assigned to the instance. You do not need to call an API operation to assign a public IP address to the instance.

  • You can create up to 100 preemptible instances at a time to meet your business requirements.

  • The parameters of RunInstances are compatible with those of CreateInstance. The Amount parameter is added to specify the number of ECS instances that you want to create. The AutoReleaseTime parameter is added to specify the automatic release time of the created instance.

  • After ECS instances are created, InstanceIdSets that contains InstanceIds is returned. You can query the states of the instances based on their IDs. For more information, see DescribeInstanceStatus.

This topic provides a complete sample code to show how to create multiple instances at a time. For more information, see Sample code. This topic also provides the explanation of the sample code. For more information, see the following topics:

Install ECS SDK for Python

Make sure that you have prepared the runtime environment for Python. Python 2.7 or later is applicable to running the code.

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 permissions, run the following sudo command to install ECS SDK for Python:

sudo pip install aliyun-python-sdk-ecs

In this topic, ECS SDK for Python 4.4.3 is used. ECS SDK for Python 4.4.3 or later is applicable to running the code. If you are using an earlier version, update it.

Sample code

#  coding=utf-8

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')

# Enter your AccessKey ID. 
ak_id = "your-access-key-id"

# Enter your AccessKey secret. 
ak_secret = "your-access-key-secret"

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

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

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

# Specify the vSwitch to which to connect the instances. 
vswitch_id = "vsw-bp1ddbrxdlrcbim46****"

# Specify the image to use to create instances. 
image_id = "<imageid>"

# Specify the security group to which to assign the instances in the current virtual private cloud (VPC). 
security_group_id = "sg-bp1i4c0xgqxadew2****"

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

# Specify the automatic release time. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time must be in UTC. The earliest release time is 30 minutes after the current time. The latest release time cannot be 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 set their automatic release time. 
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 and associate public IP addresses. 
    # create_multiple_instances_with_public_ip()
    # Create instances and set their automatic release time. 
    # create_multiple_instances_with_auto_release_time()

Create multiple ECS instances at a time

You can specify the required parameters in RunInstances to create multiple ECS instances at a time.

In this example, two ECS instances are created. The states of the instances are automatically checked every 10 seconds. The creation is complete after the ECS instances enter the Running state.

# Enter your AccessKey ID. 
ak_id = "your-access-key-id"

# Enter your AccessKey secret. 
ak_secret = "your-access-key-secret"

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

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

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

# Specify the vSwitch to which to connect the instances. 
vswitch_id = "vsw-bp1ddbrxdlrcbim46****"

# Specify the image to use to create instances. 
image_id = "<imageid>"

# Specify the security group to which to assign the instances in the current VPC. 
security_group_id = "sg-bp1i4c0xgqxadew2****"

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

# Specify the automatic release time. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time must be in UTC. The earliest release time is 30 minutes after the current time. The latest release time cannot be 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 ECS instances and assign public IP addresses

You can specify the public bandwidth when you create multiple ECS instances. In this example, the instances are assigned with 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 ECS instances and set their automatic release time

You can specify the automatic release time when you create multiple ECS instances. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time must be in UTC. The earliest release time is 30 minutes after the current time. The latest release time cannot be three years later than the current time. For more information, see ISO 8601 Time Format.

# Create instances and set their automatic release time. 
def create_multiple_instances_with_auto_release_time():
    request = build_request()
    request.set_Amount(amount)
    request.set_AutoReleaseTime(auto_release_time)
    _execute_request(request)