使用OpenApi彈性管理雲伺服器ECS

祝犁發表於2017-01-24

阿里雲的雲伺服器ECS除了提供控制檯來進行日常的管理和資源建立,還提供了OpenApi來進行資源的管理和定製開發。通過OpenApi您可以更加靈活的管理和配置雲伺服器。

阿里雲提供了SDK來包裝OpenApi,可以讓您將雲伺服器的管理整合到您的已有系統中。本文以Python的開發來說明OpenApi如何來管理雲伺服器,即便您沒有Python的開發經驗,通過本文也可以輕鬆的0基礎入門進行雲服務的開發。其它語言的開發和管理您可以通過留言溝通。

安裝ECS Python SDK

首先確保您已經具備Python的Runtime,本文中使用的Python版本為2.7+。

pip install aliyun-python-sdk-ecs

如果提示您沒有許可權,請切換sudo 繼續執行。

sudo pip install aliyun-python-sdk-ecs

本文使用的sdk版本為2.1.2, 如果您使用是舊版本的sdk,建議你更新下。

Hello Aliyun ECS

我們首先建立一個檔案hello_ecs_api.py. 為了使用SDK,首先例項化 AcsClient物件,這裡需要輸入的是您的阿里雲在Accesskey和Accesskey Secrect,你可以通過https://ak-console.aliyun.com/ 獲取自己的AK。

Access Key ID和Access Key Secret是您訪問阿里雲API的金鑰,具有該賬戶完全的許可權,請您妥善保管。

from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.DescribeRegionsRequest import DescribeRegionsRequest


clt = client.AcsClient(`Your Access Key Id`, `Your Access Key Secrect`, `cn-beijing`)

完成了例項化之後就可以進行您的第一個應用的開發。做一個簡單的查詢查詢下當前您的賬號支援的地域列表。具體的文件參見查詢可用地域列表.


def hello_aliyun_regions():
    request = DescribeRegionsRequest()
    response = _send_request(request)
    region_list = response.get(`Regions`).get(`Region`)
    assert response is not None
    assert region_list is not None
    result = map(_print_region_id, region_list)
    logging.info("region list: %s", result)
    
def _print_region_id(item):
    region_id = item.get("RegionId")
    return region_id

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

在命令列執行python hello_ecs_api.py會得到當前的支援的Region列表。類似的輸出如下

[u`cn-shenzhen`, u`ap-southeast-1`, u`cn-qingdao`, u`cn-beijing`, u`cn-shanghai`, u`us-east-1`, u`cn-hongkong`, u`me-east-1`, u`ap-southeast-2`, u`cn-hangzhou`, u`eu-central-1`, u`ap-northeast-1`, u`us-west-1`]

查詢當前的Region下的ECS例項列表

查詢例項列表和查詢Region列表非常類似,替換入參物件為DescribeInstancesRequest即可,更多的查詢引數參考查詢例項列表

def list_instances():
    request = DescribeInstancesRequest()
    response = _send_request(request)
    if response is not None:
        instance_list = response.get(`Instances`).get(`Instance`)
        result = map(_print_instance_id, instance_list)
        logging.info("current region include instance %s", result)


def _print_instance_id(item):
    instance_id = item.get(`InstanceId`);
    return instance_id

輸出結果為如下

current region include instance [u`i-****`, u`i-****``]

更多的API參考ECS API 概覽,嘗試做一個查詢磁碟列表。將例項的引數替換為DescribeDisksRequest

下一步

完成了上面的任務之後我們下一步將包含新的任務。下面的內容將持續更新,敬請關注:

全部的程式碼如下

#  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

from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.DescribeRegionsRequest import DescribeRegionsRequest

# 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`)

# sample api to list aliyun open api.
def hello_aliyun_regions():
    request = DescribeRegionsRequest()
    response = _send_request(request)
    if response is not None:
        region_list = response.get(`Regions`).get(`Region`)
        assert response is not None
        assert region_list is not None
        result = map(_print_region_id, region_list)
        logging.info("region list: %s", result)


# output the instance owned in current region.
def list_instances():
    request = DescribeInstancesRequest()
    response = _send_request(request)
    if response is not None:
        instance_list = response.get(`Instances`).get(`Instance`)
        result = map(_print_instance_id, instance_list)
        logging.info("current region include instance %s", result)


def _print_instance_id(item):
    instance_id = item.get(`InstanceId`);
    return instance_id


def _print_region_id(item):
    region_id = item.get("RegionId")
    return region_id


# 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("Hello Aliyun OpenApi!")
    hello_aliyun_regions()
    list_instances()


相關文章