This topic describes how to create and manage an Elastic Compute Service (ECS) instance by calling Alibaba Cloud API operations. In this topic, ECS SDK for Python is used.
Background information
This topic provides the sample code to show how to create an ECS instance and also provides the explanation of the sample code. For more information, see the following topics:
Sample code
# 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
- 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 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 of memory, set this 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 in a virtual private cloud (VPC). For more information, see DescribeVSwitches.
Check and start an ECS instance after the instance is created
- Obtain the ID of the instance and check whether the instance is in the Stopped state.
- If the instance is in the Stopped state, call the StartInstance operation.
- 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 credit of your account is sufficient before you create a subscription ECS instance.
request.set_Period(1)
request.set_InstanceChargeType('PrePaid')
# 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