您好,登錄后才能下訂單哦!
OpenAPI 代碼如何彈性地創建和管理ECS?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
彈性創建 ECS 實例
創建 ECS 時需關注以下 API:
創建ECS實例
查詢實例列表
啟動ECS實例
分配公網IP地址
前提條件
開通按量付費產品,您的賬戶余額不得少于 100 元,更多的需求參見 ECS使用須知。您需要在阿里云的費用中心確保自己的余額充足。
創建按量云服務器
創建云服務器時的必選屬性:
SecurityGroupId:安全組 ID。安全組通過防火墻規則實現對一組實例的配置,保護實例的網絡出入請求。在設置安全組出入規則時,建議按需開放而不要默認開放所有的出入規則。您也可以通過 ECS 控制臺創建安全組。
InstanceType:實例規格。參考 ECS 售賣頁的選項,界面上 1 核 2GB n1.small則入參為 ecs.n1.small。
ImageId:鏡像 ID。參考ECS控制臺的鏡像列表,您可以過濾系統公共鏡像或者自定義鏡像。
更多參數設置請參考創建 ECS 實例。
創建云服務器
如下面的代碼所示,創建一臺經典網絡的ECS,使用系統盤ssd,盤參數為cloud_ssd,選擇io優化實例optimized。
# 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;
創建成功后將返回相應的實例 ID,失敗的話也會有對應的 ErrorCode。由于參數較多,您可以參考 ECS 的售賣頁進行調整。
{"InstanceId":"i-***","RequestId":"006C1303-BAC5-48E5-BCDF-7FD5C2E6395D"}
云服務器生命周期
對于云服務器的狀態操作, 請參考云服務器實例生命周期。
只有Stopped狀態的實例可以執行 Start 操作。也只有Running狀態的 ECS 可以執行Stop操作。查詢云服務器的狀態可以通過查詢實例列表傳入 InstanceId 進行過濾。在DescribeInstancesRequest時可以通過傳入一個 JSON 數組格式的 String 就可以查詢這個資源的狀態。查詢單個實例的狀態建議使用DescribeInstances而不要使用DescribeInstanceAttribute, 因為前者比后者返回更多的屬性和內容。
下面的代碼會檢查實例的狀態,只有實例的狀態符合入參才會返回實例的詳情。
# 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;
啟動云服務器
創建成功后的 ECS 默認狀態是Stopped。如果要啟動 ECS 實例為Running狀態,只需要發送啟動指令即可。
def start_instance(instance_id): request = StartInstanceRequest() request.set_InstanceId(instance_id) _send_request(request)
停止云服務器
停止云服務器只需傳入instanceId即可。
def stop_instance(instance_id): request = StopInstanceRequest() request.set_InstanceId(instance_id) _send_request(request)
創建時啟動“自動啟動云服務器”
服務器的啟動和停止都是一個異步操作,您可以在腳本創建并同時檢測云服務器符合狀態時執行相應操作。
創建資源后得到實例ID,首先判斷實例是否處于Stopped的狀態,如果處于Stopped狀態,下發Start服務器的指令,然后等待服務器的狀態變成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;
分配公網IP
如果在創建云服務器的過程中,指定了公網帶寬,若需要公網的訪問權限還要調用API來分配公網IP。詳情請參考:分配公網 IP 地址。
包年包月的資源創建
除了創建按量服務的云服務器,您的API還支持創建包年包月的服務器。包年包月的創建和官網的創建流程不同,使用的是自動扣費的模式,也就是說您需要在創建服務器之前確保賬號有足夠的余額或者信用額度,在創建的時候將直接扣費。
和按量付費的 ECS 相比,只需要指定付費類型和時長即可,下面的時長為1個月。
request.set_Period(1) request.set_InstanceChargeType(‘PrePaid’)
創建包年包月實例的整體的代碼如下:
# 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;
完整的代碼
完整的代碼如下,您可以按照自己的資源參數進行設置。
# 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()
看完上述內容,你們掌握 OpenAPI 代碼如何彈性地創建和管理ECS的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。