Azure的管理平臺採用Restful API的方式實現管理。比如獲取VM的管理API的各種操作的文件請參考:
https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/get
微軟釋出的各種SDK,PowerShell或CLI都是基於這些API進行的封裝,方便操作。
本文將採用Python來獲取Azure VM的狀態資訊。
1 安裝Python的Azure模組
Python的Azure模組的Github連結:
https://github.com/gbowerman/azurerm
如果需要管理China的Azure,安裝Stan Peng修改過的模組:
pip install mcazurerm
2 建立Azure的Service Principle
Azure的Service Principle就類似一個使用者,可以對Azure的資源進行管理。
採用Azure CLI 2.0的具體命令如下:
az ad sp create-for-rbac --name hwsp –password xxxx
獲得輸出:
{ "appId": "xxxx", "displayName": "hwsp", "name": "http://hwsp", "password": "xxxx", "tenant": "xxxx" }
檢視:
az role assignment list --assignee xxxx [ { "id": "/subscriptions/xxxx/providers/Microsoft.Authorization/roleAssignments/xxxx", "name": "xxxx", "properties": { "principalId": "xxxx", "principalName": "http://hwsp", "roleDefinitionId": "/subscriptions/xxxx/providers/Microsoft.Authorization/roleDefinitions/xxxx", "roleDefinitionName": "Contributor", "scope": "/subscriptions/xxxx" }, "type": "Microsoft.Authorization/roleAssignments" } ]
3 新增建立get_vm_instanceview模組
在原有的mcazurerm中沒有檢視instanceview的模組,根據前文提到的文件,新增如下:
from mcazurerm import * def get_vm_instanceview(access_token, subscription_id, resource_group, vm_name): endpoint = ''.join([azure_rm_endpoint, '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '?$expand=instanceView' '&api-version=', COMP_API]) return do_get(endpoint, access_token)
4 獲取Azure VM狀態
通過如下程式碼獲取Azure VM狀態:
import json import sys import mcazurerm import instanceview try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except SystemError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = mcazurerm.get_access_token(tenant_id, app_id, app_secret) vminstanceview = instanceview.get_vm_instanceview(access_token,sub['subscriptionId'],"test01","hwcent01") print 'VM Name: ',vminstanceview['name'] print 'VM Resource Group: ',vminstanceview['id'].split('/')[4] print 'VM Location: ',vminstanceview['location'] print "VM Status: ",vminstanceview['properties']['instanceView']['statuses'][1]['displayStatus']
Azurermconfig.json的檔案格式請參考:
https://github.com/gbowerman/azurerm/blob/master/examples/azurermconfig.json.tmpl
過具體輸出結果如下:
VM Name: hwcent01
VM Resource Group: test01
VM Location: chinanorth
VM Status: VM deallocated
總結:
Python通過新增模組,實現獲取Azure VM執行狀態。