Как проверить, работает ли виртуальная машина с помощью Python

Я пишу runbook python, чтобы иметь возможность запускать или останавливать виртуальную машину. Если виртуальная машина работает, я хотел бы ее остановить. Если он не работает, я хотел бы включить его. Мне нужно написать условие if, чтобы сделать это, но я не знаю, как получить статус моей виртуальной машины в Azure, чтобы я мог провести сравнение.

Я попытался использовать следующее:

compute_client.virtual_machines.get(resourceGroupName, vmName, expand = 'instanceview')

Но когда я печатаю это, я не вижу, как получить доступ к статусу виртуальной машины.

Это мой код скрипта:

import os
from azure.mgmt.compute import ComputeManagementClient
import azure.mgmt.resource
import automationassets

import sys

resourceGroupName = str(sys.argv[1])
vmName = str(sys.argv[2])

def get_automation_runas_credential(runas_connection):
    from OpenSSL import crypto
    import binascii
    from msrestazure import azure_active_directory
    import adal

    # Get the Azure Automation RunAs service principal certificate
    cert = automationassets.get_automation_certificate("AzureRunAsCertificate")
    pks12_cert = crypto.load_pkcs12(cert)
    pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())

    # Get run as connection information for the Azure Automation service principal
    application_id = runas_connection["ApplicationId"]
    thumbprint = runas_connection["CertificateThumbprint"]
    tenant_id = runas_connection["TenantId"]

    # Authenticate with service principal certificate
    resource ="https://management.core.windows.net/"
    authority_url = ("https://login.microsoftonline.com/"+tenant_id)
    context = adal.AuthenticationContext(authority_url)
    return azure_active_directory.AdalAuthentication(
    lambda: context.acquire_token_with_client_certificate(
            resource,
            application_id,
            pem_pkey,
            thumbprint)
    )

# Authenticate to Azure using the Azure Automation RunAs service principal
runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
azure_credential = get_automation_runas_credential(runas_connection)

# Initialize the compute management client with the RunAs credential and specify the subscription to work against.
compute_client = ComputeManagementClient(
    azure_credential,
    str(runas_connection["SubscriptionId"])
)

printMe = compute_client.virtual_machines.get(resourceGroupName, vmName, expand = 'instanceview')
print(printMe)

#Start the VM if not running:

print('\n' + 'Starting the ' + ' ' + vmName + ' ' + 'in ' + ' ' + resourceGroupName)
async_vm_start = compute_client.virtual_machines.start(
  resourceGroupName, vmName)
async_vm_start.wait()




person tt1997    schedule 04.09.2019    source источник


Ответы (1)


Пакет Azure SDK azure.mgmt.compute, который вы использовали, правильный. Вам просто нужно получить состояние виртуальной машины внутри этой информации. Код ниже:

vm = compute_client.virtual_machines.get('v-chaxu-ChinaCXPTeam', 'azureUbuntu18', expand='instanceView')

# These are the statuses of the VM about the event execution status and the vm state, the vm state is the second one.
statuses = vm.instance_view.statuses
print(statuses[1].display_status)

Вывод здесь:

введите здесь описание изображения

Дополнительные сведения см. в разделе instance_view в информации о ВМ.

Или вы также можете напрямую получить instance_view и код ниже:

instance_view = compute_client.virtual_machines.instance_view('v-chaxu-ChinaCXPTeam', 'azureUbuntu18')
print(instance_view.statuses[1].display_status)

Выход также такой же, как указано выше. Дополнительные сведения см. в описании функции instance_view(resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config).

person Charles Xu    schedule 05.09.2019
comment
Спасибо! Это сделало именно то, что мне было нужно! - person tt1997; 05.09.2019