This topic describes how to create and manage an ECS instance by using Alibaba Cloud API operations.

Background information

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

Sample code

The following content is the sample code for creating an instance. You can modify the code and change the values of parameters based on your actual needs.
#  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.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')

clt = client.AcsClient('<accessKeyId>', '<accessSecret>', '<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

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 of ECS instances in the security group. We recommend that you configure security group rules based on your actual needs. For more information, see CreateSecurityGroup.
  • InstanceType: the instance type. For example, if you want to use the g6.large instance type with two vCPUs and 8 GiB memory, set this input parameter to ecs.g6.large. For more information, see Instance families.
  • 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 of the VPC type. For more information, see DescribeVSwitches.
  1. Create an ECS instance.
    The following code shows how to create a VPC-type ECS instance. The cloud_ssd value indicates that the instance uses a standard SSD as the system disk. The optimized value indicates that the instance is I/O optimized. Other request parameters are also supported in CreateInstance. For more information, 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 more information about the states of ECS instances, see ECS instance lifecycle. Note the following items:
    • The StartInstance operation can be performed only on instances in the Stopped state.
    • The StopInstance operation can be performed 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 instance status 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, the instance is in the Stopped state by default. If you want to put the instance into the Running state, 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 change a running instance to the Stopped state, 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 after creation

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 the required operation. The sample code has the following logic:
  1. Check whether the instance is in the Stopped state after the ID of the instance is obtained.
  2. If the instance is in the Stopped state, call StartInstance.
  3. Wait for the ECS 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 a specific 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. The balance or credit of your account is sufficient. Fees are automatically deducted during the instance creation.

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