1

I am writing a python runbook to be able to start or stop a Virtual machine. If the VM is running, I would like to stop it. If it is not running, I would like to turn it on. I need to write an if condition to do this but I don't know how to get the status of my Virtual machine in azure so I can make the comparison.

I tried using the following:

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

But when I print this, I don't see how to access the status of the Virtual machine.

This is my script code:

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()



2 Answers 2

2

The Azure SDK azure.mgmt.compute that you used is right. You just need to get the VM state inside that information. The code below:

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)

The output here:

enter image description here

For more details, see the instance_view in VM information.

Or you can also get the instance_view directly and the code below:

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

The output is also the same as above. For more details, see the function instance_view(resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This did exactly what I needed it to do!
why statuses [1]?
0

wrt to the accepted answer https://stackoverflow.com/a/57797443/8474309

For anyone wondering why the instance view index is 1 in the sample code - The first entry always shows the default provision status e.g.

    {'additional_properties': {}, 'code': 'ProvisioningState/succeeded', 'level': 'Info', 'display_status': 'Provisioning succeeded', 'message': None, 'time': datetime.datetime(2024, 3, 19, 18, 55, 51, 270654, tzinfo=<FixedOffset '+00:00'>)} Provisioning succeeded ProvisioningState/succeeded

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.