All Products
Search
Document Center

Elastic Compute Service:Create an ECS instance

Last Updated:Sep 12, 2023

This topic describes how to create and manage an Elastic Compute Service (ECS) instance by calling Alibaba Cloud API operations. In this topic, the ECS SDK for Python is used.

Background information

This topic provides the sample code to demonstrate how to create an ECS instance and also provides the explanation of the sample code. For more information, see the following sections of this topic:

Sample code

The following content is the sample code for creating an instance. You can configure parameters and modify the values of parameters in the code based on your business requirements.

#  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
import os
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.StartInstanceRequest import StartInstanceRequest
# configuration the log output formatter, if you want to save the output to file,
# append ",filename='ecs_invoke.log'" after datefmt.

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 provide higher security.
clt = client.AcsClient(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], '<region-Id>')
IMAGE_ID = 'ubuntu_18_04_64_20G_alibase_20190624.vhd'
INSTANCE_TYPE = 'ecs.g6.large'
SECURITY_GROUP_ID = 'sg-bp1i4c0xgqxadew2****'
INSTANCE_RUNNING = 'Running'
VSWITCH_ID = 'vsw-bp1ddbrxdlrcbim46****'

def create_instance_action():
    instance_id = create_after_pay_instance(IMAGE_ID, INSTANCE_TYPE, SECURITY_GROUP_ID, VSWITCH_ID)
    check_instance_running(instance_id)

# def create_prepay_instance_action():
#     instance_id = create_prepay_instance(IMAGE_ID, INSTANCE_TYPE, SECURITY_GROUP_ID, VSWITCH_ID)
#     check_instance_running(instance_id=instance_id)

# create one after pay ecs instance.
def create_after_pay_instance(image_id, instance_type, security_group_id, vsw_vswitch_id):
    request = CreateInstanceRequest()
    request.set_ImageId(image_id)
    request.set_SecurityGroupId(security_group_id)
    request.set_InstanceType(instance_type)
    request.set_IoOptimized('optimized')
    request.set_VSwitchId(vsw_vswitch_id)
    request.set_SystemDiskCategory('cloud_ssd')
    response = _send_request(request)
    instance_id = response.get('InstanceId')
    logging.info("instance %s created task submit successfully.", instance_id)
    return instance_id

# create one prepay ecs instance.
def create_prepay_instance(image_id, instance_type, security_group_id, vsw_vswitch_id):
    request = CreateInstanceRequest()
    request.set_ImageId(image_id)
    request.set_SecurityGroupId(security_group_id)
    request.set_InstanceType(instance_type)
    request.set_IoOptimized('optimized')
    request.set_VSwitchId(vsw_vswitch_id)
    request.set_SystemDiskCategory('cloud_ssd')
    request.set_Period(1)
    request.set_InstanceChargeType('PrePaid')
    response = _send_request(request)
    instance_id = response.get('InstanceId')
    logging.info("instance %s created task submit successfully.", instance_id)
    return instance_id

def check_instance_running(instance_id):
    detail = get_instance_detail_by_id(instance_id, INSTANCE_RUNNING)
    index = 0
    while detail is None and index < 60:
        detail = get_instance_detail_by_id(instance_id)
        time.sleep(10)
    if detail and detail.get('Status') == 'Stopped':
        logging.info("instance %s is stopped now.")
        start_instance(instance_id)
        logging.info("start instance %s job submit.")
    detail = get_instance_detail_by_id(instance_id, INSTANCE_RUNNING)
    while detail is None and index < 60:
        detail = get_instance_detail_by_id(instance_id, INSTANCE_RUNNING)
        time.sleep(10)
    logging.info("instance %s is running now.", instance_id)
    return instance_id

def start_instance(instance_id):
    request = StartInstanceRequest()
    request.set_InstanceId(instance_id)
    _send_request(request)

# output the instance owned in current region.
def get_instance_detail_by_id(instance_id, status='Stopped'):
    logging.info("Check instance %s status is %s", instance_id, status)
    request = DescribeInstancesRequest()
    request.set_InstanceIds(json.dumps([instance_id]))
    response = _send_request(request)
    instance_detail = None
    if response is not None:
        instance_list = response.get('Instances').get('Instance')
        for item in instance_list:
            if item.get('Status') == status:
                instance_detail = item
                break
        return instance_detail

# 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__':
    logging.info("Create ECS by OpenApi!")
    create_instance_action()
    # create_prepay_instance_action()

Create a pay-as-you-go ECS instance

Important

Before you create ECS instances, we recommend that you call the DescribeAvailableResource operation to query the resources that are available in the specified region or zone.

Required parameters:

  • SecurityGroupId: the ID of the security group. A security group is similar to a firewall and uses security group rules to control inbound and outbound traffic for ECS instances in the security group. We recommend that you configure security group rules based on your needs instead of allowing all traffic by default. For more information, see CreateSecurityGroup.

  • InstanceType: the instance type of the instance. For example, to use the g6.large instance type with two vCPUs and 8 GiB of memory, set this parameter to ecs.g6.large. For more information, see DescribeInstanceTypes.

  • ImageId: the ID of the image. You can use a public or custom image. For more information, see DescribeImages.

  • VSwitchId: the ID of the vSwitch. You must specify a vSwitch ID if you want to create an ECS instance in a virtual private cloud (VPC). For more information, see DescribeVSwitches.

  1. Create an ECS instance.

    The following sample code provides an example on how to call the CreateInstance operation with SystemDiskCategory set to cloud_ssd and IoOptimized to optimized to create an I/O optimized instance that uses a standard SSD as the system disk in a VPC. CreateInstance provides other request parameters. For information about how to re-configure these parameters, see CreateInstance.

    # create one after pay ecs instance.
    def create_after_pay_instance(image_id, instance_type, security_group_id, vsw_vswitch_id):
        request = CreateInstanceRequest()
        request.set_ImageId(image_id)
        request.set_SecurityGroupId(security_group_id)
        request.set_InstanceType(instance_type)
        request.set_IoOptimized('optimized')
        request.set_VSwitchId(vsw_vswitch_id)
        request.set_SystemDiskCategory('cloud_ssd')
        response = _send_request(request)
        instance_id = response.get('InstanceId')
        logging.info("instance %s created task submit successfully.", instance_id)
        return instance_id
  2. Query the status of the ECS instance.

    For information about the status of ECS instances, see Instance lifecycle. Take note of the following items:

    • The StartInstance operation can be called only on instances in the Stopped state.

    • The StopInstance operation can be called only on instances in the Running state.

    You can query the status of a specific ECS instance by specifying InstanceId. When you call the DescribeInstances operation, you can pass in a JSON array of strings to query the instance status. For more information, see DescribeInstances. The following code queries the status of an instance and returns information about the instance:

    # output the instance owned in current region.
    def get_instance_detail_by_id(instance_id, status='Stopped'):
        logging.info("Check instance %s status is %s", instance_id, status)
        request = DescribeInstancesRequest()
        request.set_InstanceIds(json.dumps([instance_id]))
        response = _send_request(request)
        instance_detail = None
        if response is not None:
            instance_list = response.get('Instances').get('Instance')
            for item in instance_list:
                if item.get('Status') == status:
                    instance_detail = item
                    break
            return instance_detail
  3. Start the ECS instance.

    After the ECS instance is created, it enters the Stopped state by default. If you want to put the instance into the Running state, you can call StartInstance. For more information, see StartInstance.

    def start_instance(instance_id):
        request = StartInstanceRequest()
        request.set_InstanceId(instance_id)
        _send_request(request)
  4. (Optional) Stop the ECS instance.

    If you want to put a running instance into the Stopped state, you can call StopInstance. For more information, see StopInstance.

    def stop_instance(instance_id):
        request = StopInstanceRequest()
        request.set_InstanceId(instance_id)
        _send_request(request)

Check and start an ECS instance immediately after the instance is created

The operations of starting and stopping an ECS instance are asynchronous. You can use scripts to create an ECS instance, check its status, and perform required operations. After the sample code is run, the following operations are performed:

  1. Obtain the ID of the instance and check whether the instance is in the Stopped state.

  2. If the instance is in the Stopped state, call StartInstance.

  3. Wait for the instance to enter the Running state.

def check_instance_running(instance_id):
    detail = get_instance_detail_by_id(instance_id, INSTANCE_RUNNING)
    index = 0
    while detail is None and index < 60:
        detail = get_instance_detail_by_id(instance_id)
        time.sleep(10)
    if detail and detail.get('Status') == 'Stopped':
        logging.info("instance %s is stopped now.")
        start_instance(instance_id)
        logging.info("start instance %s job submit.")
    detail = get_instance_detail_by_id(instance_id, INSTANCE_RUNNING)
    while detail is None and index < 60:
        detail = get_instance_detail_by_id(instance_id, INSTANCE_RUNNING)
        time.sleep(10)
    logging.info("instance %s is running now.", instance_id)
    return instance_id

Assign a public IP address to an ECS instance

If you specify the public bandwidth when you create an ECS instance, you must call an API operation to assign a public IP address to the instance for Internet access. For more information, see AllocatePublicIpAddress.

Create a subscription ECS instance

Prerequisites: The process of creating a subscription ECS instance by calling API operations is different from that in the ECS console. Fees are automatically deducted when you call API operations. Make sure that the balance or credits in your account are sufficient before you create a subscription ECS instance.

You must specify the billing method and duration. The duration is set to one month in the following sample code:

request.set_Period(1)
request.set_InstanceChargeType('PrePaid') 

The following sample code shows how to create a subscription instance:

# create one prepay ecs instance.
def create_prepay_instance(image_id, instance_type, security_group_id, vsw_vswitch_id):
    request = CreateInstanceRequest()
    request.set_ImageId(image_id)
    request.set_SecurityGroupId(security_group_id)
    request.set_InstanceType(instance_type)
    request.set_IoOptimized('optimized')
    request.set_VSwitchId(vsw_vswitch_id)
    request.set_SystemDiskCategory('cloud_ssd')
    request.set_Period(1)
    request.set_InstanceChargeType('PrePaid')
    response = _send_request(request)
    instance_id = response.get('InstanceId')
    logging.info("instance %s created task submit successfully.", instance_id)
    return instance_id