OpenAPI 代碼如何彈性地創(chuàng)建和管理ECS?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
10多年的下城網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時及時工作處理。全網(wǎng)整合營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整下城建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。創(chuàng)新互聯(lián)從事“下城網(wǎng)站設(shè)計”,“下城網(wǎng)站推廣”以來,每個客戶項目都認真落實執(zhí)行。
彈性創(chuàng)建 ECS 實例
創(chuàng)建 ECS 時需關(guān)注以下 API:
創(chuàng)建ECS實例
查詢實例列表
啟動ECS實例
分配公網(wǎng)IP地址
前提條件
開通按量付費產(chǎn)品,您的賬戶余額不得少于 100 元,更多的需求參見 ECS使用須知。您需要在阿里云的費用中心確保自己的余額充足。
創(chuàng)建按量云服務(wù)器
創(chuàng)建云服務(wù)器時的必選屬性:
SecurityGroupId:安全組 ID。安全組通過防火墻規(guī)則實現(xiàn)對一組實例的配置,保護實例的網(wǎng)絡(luò)出入請求。在設(shè)置安全組出入規(guī)則時,建議按需開放而不要默認開放所有的出入規(guī)則。您也可以通過 ECS 控制臺創(chuàng)建安全組。
InstanceType:實例規(guī)格。參考 ECS 售賣頁的選項,界面上 1 核 2GB n1.small則入?yún)?ecs.n1.small。
ImageId:鏡像 ID。參考ECS控制臺的鏡像列表,您可以過濾系統(tǒng)公共鏡像或者自定義鏡像。
更多參數(shù)設(shè)置請參考創(chuàng)建 ECS 實例。
創(chuàng)建云服務(wù)器
如下面的代碼所示,創(chuàng)建一臺經(jīng)典網(wǎng)絡(luò)的ECS,使用系統(tǒng)盤ssd,盤參數(shù)為cloud_ssd,選擇io優(yōu)化實例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;
創(chuàng)建成功后將返回相應(yīng)的實例 ID,失敗的話也會有對應(yīng)的 ErrorCode。由于參數(shù)較多,您可以參考 ECS 的售賣頁進行調(diào)整。
{"InstanceId":"i-***","RequestId":"006C1303-BAC5-48E5-BCDF-7FD5C2E6395D"}
云服務(wù)器生命周期
對于云服務(wù)器的狀態(tài)操作, 請參考云服務(wù)器實例生命周期。
只有Stopped狀態(tài)的實例可以執(zhí)行 Start 操作。也只有Running狀態(tài)的 ECS 可以執(zhí)行Stop操作。查詢云服務(wù)器的狀態(tài)可以通過查詢實例列表傳入 InstanceId 進行過濾。在DescribeInstancesRequest時可以通過傳入一個 JSON 數(shù)組格式的 String 就可以查詢這個資源的狀態(tài)。查詢單個實例的狀態(tài)建議使用DescribeInstances而不要使用DescribeInstanceAttribute, 因為前者比后者返回更多的屬性和內(nèi)容。
下面的代碼會檢查實例的狀態(tài),只有實例的狀態(tài)符合入?yún)⒉艜祷貙嵗脑斍椤?/p>
# 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;
啟動云服務(wù)器
創(chuàng)建成功后的 ECS 默認狀態(tài)是Stopped。如果要啟動 ECS 實例為Running狀態(tài),只需要發(fā)送啟動指令即可。
def start_instance(instance_id): request = StartInstanceRequest() request.set_InstanceId(instance_id) _send_request(request)
停止云服務(wù)器
停止云服務(wù)器只需傳入instanceId即可。
def stop_instance(instance_id): request = StopInstanceRequest() request.set_InstanceId(instance_id) _send_request(request)
創(chuàng)建時啟動“自動啟動云服務(wù)器”
服務(wù)器的啟動和停止都是一個異步操作,您可以在腳本創(chuàng)建并同時檢測云服務(wù)器符合狀態(tài)時執(zhí)行相應(yīng)操作。
創(chuàng)建資源后得到實例ID,首先判斷實例是否處于Stopped的狀態(tài),如果處于Stopped狀態(tài),下發(fā)Start服務(wù)器的指令,然后等待服務(wù)器的狀態(tài)變成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;
分配公網(wǎng)IP
如果在創(chuàng)建云服務(wù)器的過程中,指定了公網(wǎng)帶寬,若需要公網(wǎng)的訪問權(quán)限還要調(diào)用API來分配公網(wǎng)IP。詳情請參考:分配公網(wǎng) IP 地址。
包年包月的資源創(chuàng)建
除了創(chuàng)建按量服務(wù)的云服務(wù)器,您的API還支持創(chuàng)建包年包月的服務(wù)器。包年包月的創(chuàng)建和官網(wǎng)的創(chuàng)建流程不同,使用的是自動扣費的模式,也就是說您需要在創(chuàng)建服務(wù)器之前確保賬號有足夠的余額或者信用額度,在創(chuàng)建的時候?qū)⒅苯涌圪M。
和按量付費的 ECS 相比,只需要指定付費類型和時長即可,下面的時長為1個月。
request.set_Period(1) request.set_InstanceChargeType(‘PrePaid’)
創(chuàng)建包年包月實例的整體的代碼如下:
# 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;
完整的代碼
完整的代碼如下,您可以按照自己的資源參數(shù)進行設(shè)置。
# 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()
看完上述內(nèi)容,你們掌握 OpenAPI 代碼如何彈性地創(chuàng)建和管理ECS的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
當前題目:OpenAPI代碼如何彈性地創(chuàng)建和管理ECS
分享路徑:http://www.rwnh.cn/article42/jgpjhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、響應(yīng)式網(wǎng)站、網(wǎng)站建設(shè)、商城網(wǎng)站、虛擬主機、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)