阿里雲團隊努力不懈,讓最新技術內容能以更快方式以您最熟悉的語言呈現給您。本文內容由機器自動翻譯簡體中文,過程無人工干預。轉碼所造成任何內容錯誤及相關損失,阿里雲概不負責。敬請見諒。若任何內容問題涉及信息準確性,請以英文版為準。
全部產品
Search
文件中心

彈性建立 ECS 執行個體

更新時間: Aug 23, 2018

除了可以在ECS控制台售賣頁建立 ECS 外,您還可以使用 OpenAPI 代碼來彈性地建立和管理ECS。本頁面使用 Python 為例進行說明。

建立 ECS 時需關注以下 API:

建立按量雲端服務器

建立雲端服務器時的必選屬性:

  • 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()