Creating ECS instances using OpenAPI elasticity
In addition to creating ECS in the ECS console or on the sales page, you can use OpenAPI code to create and manage ECS flexibly. This page uses Python as an example to illustrate.
When creating ECS, you need to pay attention to the following API s:
- Create an ECS instance
- Query instance list
- Start an ECS instance
- Distribution of Public Network IP Address
Prerequisite
When you open a pay-for-quantity product, your account balance should not be less than 100 yuan. For more information, please refer to the ECS instructions. You need to make sure your balance is adequate at Aliyun's expense center.
Creating Cloud-by-volume Server
Required attributes when creating cloud servers:
- Security Group Id: Security Group ID. The security group configures a group of instances through firewall rules to protect the network access requests of the instances. When setting access rules for security groups, it is suggested that all access rules should be opened on demand rather than by default. You can also create security groups through the ECS console.
- InstanceType: Instance specification. Refer to the ECS sells page option, the interface 1 core 2GB n1.small is included in the ecs.n1.small.
- ImageId: Mirror ID. Referring to the mirror list of the ECS console, you can filter common or custom images of the system.
Create a Cloud Server
As shown in the following code, create a classic network ECS, using system disk ssd, disk parameter cloud_ssd, select io optimization example optimization.
# create one after pay ecs instance. def create_after_pay_instance(image_id, instance_type, security_group_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_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;
When the creation is successful, the corresponding instance ID will be returned, and if it fails, the corresponding ErrorCode will also exist. As there are many parameters, you can refer to the sales page of ECS for adjustment.
{"InstanceId":"i-***","RequestId":"006C1303-BAC5-48E5-BCDF-7FD5C2E6395D"}
Cloud Server Life Cycle
For status operations of cloud servers, refer to the life cycle of cloud server instances.
Only instances of Stopped state can perform Start operations. Only ECS in Running state can perform Stop operation. Queries about the status of cloud servers can be filtered by querying the list of instances into InstanceId. In Describe Instances Request, you can query the status of the resource by passing in a String in JSON array format. Querying the status of a single instance suggests using Describe Instances instead of Describe Instance Attribute, because the former returns more attributes and content than the latter.
The following code checks the status of the instance and returns the details of the instance only if the status of the instance meets the entry criteria.
# 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;
Start Cloud Server
The default state of the ECS after successful creation is Stopped. If you want to start an ECS instance in Running state, you only need to send a startup instruction.
def start_instance(instance_id): request = StartInstanceRequest() request.set_InstanceId(instance_id) _send_request(request)
Stop Cloud Server
Stop the cloud server by simply passing in instanceId.
def stop_instance(instance_id): request = StopInstanceRequest() request.set_InstanceId(instance_id) _send_request(request)
Start "Auto Start Cloud Server" at creation time
Starting and stopping servers is an asynchronous operation, which you can perform when scripts are created and the cloud servers are checked for compliance.
After creating the resource, get the instance ID. First, determine whether the instance is in Stopped state. If it is in Stopped state, issue the Start server's instructions, and then wait for the server's status to become Running.
def check_instance_running(instance_id): detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING) index = 0 while detail is None and index < 60: detail = get_instance_detail_by_id(instance_id=instance_id); time.sleep(10) if detail and detail.get('Status') == 'Stopped': logging.info("instance %s is stopped now.") start_instance(instance_id=instance_id) logging.info("start instance %s job submit.") detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING) while detail is None and index < 60: detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING); time.sleep(10) logging.info("instance %s is running now.", instance_id) return instance_id;
Distribution of Public Network IP
If the public network bandwidth is specified in the process of creating the cloud server, the API is also called to allocate the public network IP if the access rights of the public network are needed. For more information, please refer to: Distribution of public IP addresses.
Resource Creation of Year and Month
In addition to creating cloud servers for volume services, your API also supports creating servers for package years and months. The process of creating a package year and a package month is different from that of creating an official website. It uses the automatic deduction mode. That is to say, you need to make sure that the account has sufficient balance or credit line before creating a server, and the account will be deducted directly when it is created.
Compared with ECS which pays by volume, it only needs to specify the type and length of payment. The following time is one month.
request.set_Period(1) request.set_InstanceChargeType('PrePaid')
The overall code for creating a package year package month instance is as follows:
# create one prepay ecs instance. def create_prepay_instance(image_id, instance_type, security_group_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_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;
Complete code
The complete code is as follows, you can set it according to your own resource parameters.
# 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 2.1.2, 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('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing') IMAGE_ID = 'ubuntu1404_64_40G_cloudinit_20160727.raw' INSTANCE_TYPE = 'ecs.s2.large' # 2c4g generation 1 SECURITY_GROUP_ID = 'sg-****' INSTANCE_RUNNING = 'Running' def create_instance_action(): instance_id = create_after_pay_instance(image_id=IMAGE_ID, instance_type=INSTANCE_TYPE, security_group_id=SECURITY_GROUP_ID) check_instance_running(instance_id=instance_id) def create_prepay_instance_action(): instance_id = create_prepay_instance(image_id=IMAGE_ID, instance_type=INSTANCE_TYPE, security_group_id=SECURITY_GROUP_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): request = CreateInstanceRequest(); request.set_ImageId(image_id) request.set_SecurityGroupId(security_group_id) request.set_InstanceType(instance_type) request.set_IoOptimized('optimized') 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): request = CreateInstanceRequest(); request.set_ImageId(image_id) request.set_SecurityGroupId(security_group_id) request.set_InstanceType(instance_type) request.set_IoOptimized('optimized') 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_id, status=INSTANCE_RUNNING) index = 0 while detail is None and index < 60: detail = get_instance_detail_by_id(instance_id=instance_id); time.sleep(10) if detail and detail.get('Status') == 'Stopped': logging.info("instance %s is stopped now.") start_instance(instance_id=instance_id) logging.info("start instance %s job submit.") detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING) while detail is None and index < 60: detail = get_instance_detail_by_id(instance_id=instance_id, status=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()