简体   繁体   English

Azure python sdk - 获取机器状态

[英]Azure python sdk - getting the machine state

Using the python api for azure, I want to get the state of one of my machines.使用 python api for azure,我想获取我的一台机器的状态。

I can't find anywhere to access this information.我找不到任何地方可以访问这些信息。

Does someone know?有人知道吗?

After looking around, I found this:环顾四周后,我发现了这个:

get_with_instance_view(resource_group_name, vm_name)

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

if you are using the legacy api (this will work for classic virtual machines), use如果您使用的是旧版 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

if you are using the current api (will not work for classic vm's), use如果您使用的是当前的 api(不适用于经典虚拟机),请使用

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

If you are using Azure Cloud Services, you should use the Role Environment API, which provides state information regarding the current instance of your current service instance.如果使用 Azure 云服务,则应使用角色环境 API,它提供有关当前服务实例的当前实例的状态信息。 https://msdn.microsoft.com/en-us/library/azure/microsoft.windowsazure.serviceruntime.roleenvironment.aspx https://msdn.microsoft.com/en-us/library/azure/microsoft.windowsazure.serviceruntime.roleenvironment.aspx

In the new API resource manager There's a function:在新的 API 资源管理器中有一个函数:

get_with_instance_view(resource_group_name, vm_name)

It's the same function as get machine, but it also returns an instance view that contains the machine state.它与 get machine 的功能相同,但它还返回一个包含机器状态的实例视图。

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

Use this method get_deployment_by_name to get the instances status:使用此方法 get_deployment_by_name 获取实例状态:

subscription_id = '****-***-***-**'
certificate_path = 'CURRENT_USER\\my\\***'
sms = ServiceManagementService(subscription_id, certificate_path)
result=sms.get_deployment_by_name("your service name","your deployment name")

You can get instance status via " instance_status " property.您可以通过“ instance_status ”属性获取实例状态。 Please see this post https://stackoverflow.com/a/31404545/4836342请参阅此帖子https://stackoverflow.com/a/31404545/4836342

As mentioned in other answers the Azure Resource Manager API has an instance view query to show the state of running VMs.正如其他答案中提到的,Azure Resource Manager API 有一个实例视图查询来显示正在运行的 VM 的状态。

The documentation listing for this is here: VirtualMachineOperations.get_with_instance_view()文档列表在这里: VirtualMachineOperations.get_with_instance_view()

Typical code to get the status of a VM is something like this:获取 VM 状态的典型代码如下所示:

resource_group = "myResourceGroup"
vm_name = "myVMName"
creds = azure.mgmt.common.SubscriptionCloudCredentials(…)
compute_client = azure.mgmt.compute.ComputeManagementClient(creds)
vm = compute_client.virtual_machines.get_with_instance_view(resource_group, vm_name).virtual_machine

# Index 0 is the ProvisioningState, index 1 is the Instance PowerState, display_status will typically be "VM running, VM stopped, etc.
vm_status = vm.instance_view.statuses[1].display_status
  • There is no direct way to get the state of a virtual machine while listing them.在列出虚拟机时,没有直接的方法可以获取它们的状态。
  • But, we can list out the vms by looping into them to get the instance_view of a machine and grab its power state.但是,我们可以通过循环进入它们来列出虚拟机,以获取机器的instance_view并获取其电源状态。
  • In the code block below, I am doing the same and dumping the values into a .csv file to make a report.在下面的代码块中,我正在做同样的事情并将值转储到.csv文件中以制作报告。
import csv
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient


def get_credentials():
    subscription_id = "*******************************"
    credential = ServicePrincipalCredentials(
        client_id="*******************************",
        secret="*******************************",
        tenant="*******************************"
    )
    return credential, subscription_id


credentials, subscription_id = get_credentials()

# Initializing compute client with the credentials
compute_client = ComputeManagementClient(credentials, subscription_id)

resource_group_name = "**************"
json_list = []
json_object = {"Vm_name": "", "Vm_state": "", "Resource_group": resource_group_name}

# listing out the virtual machine names
vm_list = compute_client.virtual_machines.list(resource_group_name=resource_group_name)

# looping inside the list of virtual machines, to grab the state of each machine
for i in vm_list:
    vm_state = compute_client.virtual_machines.instance_view(resource_group_name=resource_group_name, vm_name=i.name)
    json_object["Vm_name"] = i.name
    json_object["Vm_state"] = vm_state.statuses[1].code
    json_list.append(json_object)

csv_columns = ["Vm_name", "Vm_state", "Resource_group"]
f = open("vm_state.csv", 'w+')
csv_file = csv.DictWriter(f, fieldnames=csv_columns)
csv_file.writeheader()
for i in json_list:
    csv_file.writerow(i)
  • To grab the state of a single virtual machine, where you know its resource_group_name and vm_name , just use the block below.要获取单个虚拟机的状态,您知道它的resource_group_namevm_name ,只需使用下面的块。
vm_state = compute_client.virtual_machines.instance_view(resource_group_name="foo_rg_name", vm_name="foo_vm_name")
power_state = vm_state.statuses[1].code
print(power_state)

As per the new API reference, this worked for me根据新的 API 参考,这对我有用

vm_status = compute_client.virtual_machines.instance_view(GROUP_NAME, VM_NAME).statuses[1].code

it will return any one of these states, based on the current state它将根据当前状态返回这些状态中的任何一个

"PowerState/stopped", "PowerState/running","PowerState/stopping", "PowerState/starting"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM