全部产品
云服务器 ECS

使用OpenAPI弹性创建ECS实例

更新时间:2017-06-07 13:26:11   分享:   

除了可以在ECS控制台售卖页创建 ECS 外,您还可以使用 OpenAPI 代码来弹性地创建和管理ECS。本页面使用 Python 为例进行说明。

创建 ECS 时需关注以下 API:

前提条件

开通按量付费产品,您的账户余额不得少于 100 元,更多的需求参见 ECS使用须知。您需要在阿里云的费用中心确保自己的余额充足。

创建按量云服务器

创建云服务器时的必选属性:

  • SecurityGroupId:安全组 ID。安全组通过防火墙规则实现对一组实例的配置,保护实例的网络出入请求。在设置安全组出入规则时,建议按需开放而不要默认开放所有的出入规则。您也可以通过 ECS 控制台创建安全组。
  • InstanceType:实例规格。参考 ECS 售卖页的选项,界面上 1 核 2GB n1.small则入参为 ecs.n1.small。
  • ImageId:镜像 ID。参考ECS控制台的镜像列表,您可以过滤系统公共镜像或者自定义镜像。

更多参数设置请参考创建 ECS 实例

创建云服务器

如下面的代码所示,创建一台经典网络的ECS,使用系统盘ssd,盘参数为cloud_ssd,选择io优化实例optimized。

  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;

创建成功后将返回相应的实例 ID,失败的话也会有对应的 ErrorCode。由于参数较多,您可以参考 ECS 的售卖页进行调整。

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

云服务器生命周期

对于云服务器的状态操作, 请参考云服务器实例生命周期

只有Stopped状态的实例可以执行 Start 操作。也只有Running状态的 ECS 可以执行Stop操作。查询云服务器的状态可以通过查询实例列表传入 InstanceId 进行过滤。在DescribeInstancesRequest时可以通过传入一个 JSON 数组格式的 String 就可以查询这个资源的状态。查询单个实例的状态建议使用DescribeInstances而不要使用DescribeInstanceAttribute, 因为前者比后者返回更多的属性和内容。

下面的代码会检查实例的状态,只有实例的状态符合入参才会返回实例的详情。

  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;

启动云服务器

创建成功后的 ECS 默认状态是Stopped。如果要启动 ECS 实例为Running状态,只需要发送启动指令即可。

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

停止云服务器

停止云服务器只需传入instanceId即可。

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

创建时启动“自动启动云服务器”

服务器的启动和停止都是一个异步操作,您可以在脚本创建并同时检测云服务器符合状态时执行相应操作。

创建资源后得到实例ID,首先判断实例是否处于Stopped的状态,如果处于Stopped状态,下发Start服务器的指令,然后等待服务器的状态变成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;

分配公网IP

如果在创建云服务器的过程中,指定了公网带宽,若需要公网的访问权限还要调用API来分配公网IP。详情请参考:分配公网 IP 地址

包年包月的资源创建

除了创建按量服务的云服务器,您的API还支持创建包年包月的服务器。包年包月的创建和官网的创建流程不同,使用的是自动扣费的模式,也就是说您需要在创建服务器之前确保账号有足够的余额或者信用额度,在创建的时候将直接扣费。

和按量付费的 ECS 相比,只需要指定付费类型和时长即可,下面的时长为1个月。

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

创建包年包月实例的整体的代码如下:

  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;

完整的代码

完整的代码如下,您可以按照自己的资源参数进行设置。

  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()
本文导读目录
本文导读目录
以上内容是否对您有帮助?