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运行状态。