Azure python sdk - 获取机器状态

Oli*_*ver 3 python azure

使用python api for azure,我想得到我的一台机器的状态.

我无法在任何地方找到这些信息.

有人知道吗?

环顾四周后,我发现了这个:

get_with_instance_view(resource_group_name, vm_name)
Run Code Online (Sandbox Code Playgroud)

https://azure-sdk-for-python.readthedocs.org/en/latest/ref/azure.mgmt.compute.computemanagement.html#azure.mgmt.compute.computemanagement.VirtualMachineOperations.get_with_instance_view

小智 8

如果您使用的是旧版api(这适用于经典虚拟机),请使用

from azure.servicemanagement import ServiceManagementService
sms = ServiceManagementService('your subscription id', 'your-azure-certificate.pem')

your_deployment = sms.get_deployment_by_name('service name', 'deployment name')
for role_instance in your_deployment.role_instance_list:
    print role_instance.instance_name, role_instance.instance_status
Run Code Online (Sandbox Code Playgroud)

如果你正在使用当前的api(不适用于经典的vm),请使用

from azure.common.credentials import UserPassCredentials
from azure.mgmt.compute import ComputeManagementClient

import retry

credentials = UserPassCredentials('username', 'password')
compute_client = ComputeManagementClient(credentials, 'your subscription id')

@retry.retry(RuntimeError, tries=3)
def get_vm(resource_group_name, vm_name):
    '''
    you need to retry this just in case the credentials token expires,
    that's where the decorator comes in
    this will return all the data about the virtual machine
    '''
    return compute_client.virtual_machines.get(
        resource_group_name, vm_name, expand='instanceView')

@retry.retry((RuntimeError, IndexError,), tries=-1)
def get_vm_status(resource_group_name, vm_name):
    '''
    this will just return the status of the virtual machine
    sometime the status may be unknown as shown by the azure portal;
    in that case statuses[1] doesn't exist, hence retrying on IndexError
    also, it may take on the order of minutes for the status to become
    available so the decorator will bang on it forever
    '''
    return compute_client.virtual_machines.get(resource_group_name, vm_name, expand='instanceView').instance_view.statuses[1].display_status
Run Code Online (Sandbox Code Playgroud)

  • @AnatoliiChmykhalo为了使“ instance_view”不为“无”,您需要向“ compute_client.virtual_machines.get”调用中添加“ expand ='instanceView”`。 (2认同)