edit-icon download-icon

Create an instance

Last Updated: Dec 29, 2017

In addition to the ECS Console or Buy Page, you can also use OpenAPI code to elastically create and manage ECS instances. This article describes how to create an ECS instance using Python.

When creating an ECS instance, pay attention to the following APIs:

Create a Pay-As-You-Go ECS instance

Mandatory attributes:

  • SecurityGroupId: Security group ID. A security group is used to implement the configurations of a group of instances based on firewall rules to protect the network access requests of the instances. We recommend that only necessary access rules, rather than all access rules, be enabled when you configure security group access rules. You can create a security group in the ECS console.
  • InstanceType: Instance type. See the ECS Buy Page. The option “one-core 2GB n1.small” indicates that the input parameter is “ecs.n1.small”.
  • ImageId: Image ID. See the image list in the ECS console. You can filter public images or custom images.

For more parameter settings, see Create an ECS instance.

Create an ECS instance

The following code shows creating an I/O optimized classic-network ECS instance with SSD as system disk and “cloud_ssd” as disk parameter.

  1. # create one after pay ecs instance.
  2. def create_after_pay_instance(image_id, instance_type, security_group_id):
  3. request = CreateInstanceRequest();
  4. request.set_ImageId(image_id)
  5. request.set_SecurityGroupId(security_group_id)
  6. request.set_InstanceType(instance_type)
  7. request.set_IoOptimized('optimized')
  8. request.set_SystemDiskCategory('cloud_ssd')
  9. response = _send_request(request)
  10. instance_id = response.get('InstanceId')
  11. logging.info("instance %s created task submit successfully.", instance_id)
  12. return instance_id;

An instance ID is returned after the ECS instance is created successfully. If creation fails, an error code is returned. Since there are many parameters, you can make adjustments by visiting the ECS Buy Page.

  1. {"InstanceId":"i-***","RequestId":"006C1303-BAC5-48E5-BCDF-7FD5C2E6395D"}

ECS lifecycle

For more information about the operations in different ECS status, see ECS Instance Lifecycle.

Only when an instance is in the Stopped status, can the Start operation be performed, and only when it is in the Running status, can the Stop operation be performed. To query the ECS status, you can filter the instance list by inputting the parameter Instance ID. When you call DescribeInstancesRequest, input a JSON array of strings to query the resource status. When you query the status of a single instance, we suggest using DescribeInstances rather than DescribeInstanceAttribute, because the former API returns more attributes and content than the latter.

The following code is used to check the instance status. The system returns instance details only when the instance status conforms to the input parameters.

  1. # output the instance owned in current region.
  2. def get_instance_detail_by_id(instance_id, status='Stopped'):
  3. logging.info("Check instance %s status is %s", instance_id, status)
  4. request = DescribeInstancesRequest()
  5. request.set_InstanceIds(json.dumps([instance_id]))
  6. response = _send_request(request)
  7. instance_detail = None
  8. if response is not None:
  9. instance_list = response.get('Instances').get('Instance')
  10. for item in instance_list:
  11. if item.get('Status') == status:
  12. instance_detail = item
  13. break;
  14. return instance_detail;

Start an ECS instance

After an ECS instance is created successfully, the default instance status is Stopped. To change to the Running status, send the Start command.

  1. def start_instance(instance_id):
  2. request = StartInstanceRequest()
  3. request.set_InstanceId(instance_id)
  4. _send_request(request)

Stop an ECS instance

To stop an ECS instance, use the input instance ID.

  1. def stop_instance(instance_id):
  2. request = StopInstanceRequest()
  3. request.set_InstanceId(instance_id)
  4. _send_request(request)

Enable “ECS automatic startup” when creating an ECS instance

The ECS Start and Stop operations are asynchronous. You can perform the operation when the script is creating an ECS instance and detecting if it is in an appropriate status.

After you obtain the ID of a successfully created ECS instance, check whether the instance is in the Stopped status. If it is in the Stopped status, send the Start ECS command and wait until the ECS status changes to Running.

  1. def check_instance_running(instance_id):
  2. detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)
  3. index = 0
  4. while detail is None and index < 60:
  5. detail = get_instance_detail_by_id(instance_id=instance_id);
  6. time.sleep(10)
  7. if detail and detail.get('Status') == 'Stopped':
  8. logging.info("instance %s is stopped now.")
  9. start_instance(instance_id=instance_id)
  10. logging.info("start instance %s job submit.")
  11. detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)
  12. while detail is None and index < 60:
  13. detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING);
  14. time.sleep(10)
  15. logging.info("instance %s is running now.", instance_id)
  16. return instance_id;

Allocate a public IP address

If you specify the public network bandwidth when creating an ECS instance, you need to call an API to allocate a public IP address to the instance for public network access. For more information, see Allocate a public IP address.

Create an ECS instance in the Subscription mode

OpenAPI also supports creating ECS instances in the Subscription mode, in addition to Pay-As-You-Go ECS instances. The process for creating an ECS instance in the Subscription mode is different from that on Alibaba Cloud’s website. Fees are automatically deducted for an ECS instance created in the Subscription mode. Before you create an ECS instance, make sure that you have sufficient account balance or credit amount, so that the fees can be deducted directly during creation.

When creating an ECS instance in Subscription mode, you only need to specify the payment option and duration. In the following code, the duration is set to one month.

  1. request.set_Period(1) request.set_InstanceChargeType(‘PrePaid’)

The complete code for creating an ECS instance in the Subscription mode is as follows:

  1. # create one prepay ecs instance.
  2. def create_prepay_instance(image_id, instance_type, security_group_id):
  3. request = CreateInstanceRequest();
  4. request.set_ImageId(image_id)
  5. request.set_SecurityGroupId(security_group_id)
  6. request.set_InstanceType(instance_type)
  7. request.set_IoOptimized('optimized')
  8. request.set_SystemDiskCategory('cloud_ssd')
  9. request.set_Period(1)
  10. request.set_InstanceChargeType('PrePaid')
  11. response = _send_request(request)
  12. instance_id = response.get('InstanceId')
  13. logging.info("instance %s created task submit successfully.", instance_id)
  14. return instance_id;

Complete code

See the complete code as follows. You can use your resource parameters for configuration.

  1. # coding=utf-8
  2. # if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
  3. # if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
  4. # make sure the sdk version is 2.1.2, you can use command 'pip show aliyun-python-sdk-ecs' to check
  5. import json
  6. import logging
  7. import time
  8. from aliyunsdkcore import client
  9. from aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequest
  10. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  11. from aliyunsdkecs.request.v20140526.StartInstanceRequest import StartInstanceRequest
  12. # configuration the log output formatter, if you want to save the output to file,
  13. # append ",filename='ecs_invoke.log'" after datefmt.
  14. logging.basicConfig(level=logging.INFO,
  15. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  16. datefmt='%a, %d %b %Y %H:%M:%S')
  17. clt = client.AcsClient('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing')
  18. IMAGE_ID = 'ubuntu1404_64_40G_cloudinit_20160727.raw'
  19. INSTANCE_TYPE = 'ecs.s2.large' # 2c4g generation 1
  20. SECURITY_GROUP_ID = 'sg-****'
  21. INSTANCE_RUNNING = 'Running'
  22. def create_instance_action():
  23. instance_id = create_after_pay_instance(image_id=IMAGE_ID, instance_type=INSTANCE_TYPE,
  24. security_group_id=SECURITY_GROUP_ID)
  25. check_instance_running(instance_id=instance_id)
  26. def create_prepay_instance_action():
  27. instance_id = create_prepay_instance(image_id=IMAGE_ID, instance_type=INSTANCE_TYPE,
  28. security_group_id=SECURITY_GROUP_ID)
  29. check_instance_running(instance_id=instance_id)
  30. # create one after pay ecs instance.
  31. def create_after_pay_instance(image_id, instance_type, security_group_id):
  32. request = CreateInstanceRequest();
  33. request.set_ImageId(image_id)
  34. request.set_SecurityGroupId(security_group_id)
  35. request.set_InstanceType(instance_type)
  36. request.set_IoOptimized('optimized')
  37. request.set_SystemDiskCategory('cloud_ssd')
  38. response = _send_request(request)
  39. instance_id = response.get('InstanceId')
  40. logging.info("instance %s created task submit successfully.", instance_id)
  41. return instance_id;
  42. # create one prepay ecs instance.
  43. def create_prepay_instance(image_id, instance_type, security_group_id):
  44. request = CreateInstanceRequest();
  45. request.set_ImageId(image_id)
  46. request.set_SecurityGroupId(security_group_id)
  47. request.set_InstanceType(instance_type)
  48. request.set_IoOptimized('optimized')
  49. request.set_SystemDiskCategory('cloud_ssd')
  50. request.set_Period(1)
  51. request.set_InstanceChargeType('PrePaid')
  52. response = _send_request(request)
  53. instance_id = response.get('InstanceId')
  54. logging.info("instance %s created task submit successfully.", instance_id)
  55. return instance_id;
  56. def check_instance_running(instance_id):
  57. detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)
  58. index = 0
  59. while detail is None and index < 60:
  60. detail = get_instance_detail_by_id(instance_id=instance_id);
  61. time.sleep(10)
  62. if detail and detail.get('Status') == 'Stopped':
  63. logging.info("instance %s is stopped now.")
  64. start_instance(instance_id=instance_id)
  65. logging.info("start instance %s job submit.")
  66. detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING)
  67. while detail is None and index < 60:
  68. detail = get_instance_detail_by_id(instance_id=instance_id, status=INSTANCE_RUNNING);
  69. time.sleep(10)
  70. logging.info("instance %s is running now.", instance_id)
  71. return instance_id;
  72. def start_instance(instance_id):
  73. request = StartInstanceRequest()
  74. request.set_InstanceId(instance_id)
  75. _send_request(request)
  76. # output the instance owned in current region.
  77. def get_instance_detail_by_id(instance_id, status='Stopped'):
  78. logging.info("Check instance %s status is %s", instance_id, status)
  79. request = DescribeInstancesRequest()
  80. request.set_InstanceIds(json.dumps([instance_id]))
  81. response = _send_request(request)
  82. instance_detail = None
  83. if response is not None:
  84. instance_list = response.get('Instances').get('Instance')
  85. for item in instance_list:
  86. if item.get('Status') == status:
  87. instance_detail = item
  88. break;
  89. return instance_detail;
  90. # send open api request
  91. def _send_request(request):
  92. request.set_accept_format('json')
  93. try:
  94. response_str = clt.do_action(request)
  95. logging.info(response_str)
  96. response_detail = json.loads(response_str)
  97. return response_detail
  98. except Exception as e:
  99. logging.error(e)
  100. if __name__ == '__main__':
  101. logging.info("Create ECS by OpenApi!")
  102. create_instance_action()
  103. # create_prepay_instance_action()
Thank you! We've received your feedback.