0

From the az cli I have a cmd to find all the VMs that are running and it returns all the info as a JSON file with keys that I define.

My question is how can I do this using the Python SDK? I would like the same key/value in a JSON format. I am doing some post processing in Python so I prefer to use Python from start to finish to generate the info.

working code below:

az vm list -d -o json --query `
    "[?powerState=='VM running'].{Name:name, admin:osProfile.adminUsername, STATUS:powerState RG:resourceGroup TAGS:tags}" 

which returns

[
 {
    "Name": "boston",
    "RG": "r_group",
    "STATUS": "VM running",
    "TAGS": {
      "tag_1": "tag_value_1",
      "tag_2": "tag_value_2"
    },
    "admin": "waldo"
  }
]

2 Answers 2

1

You can use the following Code to list the VMS,

import azure.mgmt.compute as Compute
from azure.common.client_factory import get_client_from_cli_profile

import retry
import sys
import logging

@retry.retry(RuntimeError, tries=2)
def listVMs(resourceGroup):

    VM = get_client_from_cli_profile(Compute.ComputeManagementClient)

    try:
        VMs = VM.virtual_machines.list(resourceGroup)
        for vm in VMs:
            print(vm)

    except Exception as e:
        logging.error(e)

resourceGroup = sys.argv[1]

if __name__ == '__main__':
    listVMs(resourceGroup)

else:
    print('Running as imported module')
    listVMs(resourceGroup)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the start but the custom json is just as important for me.
you need to organize with the logic. SO is not providing coding service
1

In the end I was able to figure it with the help of a colleague and lots of searches. Posting this here in the hope that others will benefit from the answer.

Greets to @Charles Xu for getting me started with this answer how-could-i-list-azure-virtual-machines-using-python

It was difficult for me to find specific and relevant documentation from MS to address my issue.

NOTE: THis is a work in progress and I am sure that there is lots of room for improvement. I don't think the resulting json is perfect but json2html isn't complaining.

And now for the code....

#!/usr/bin/env python

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
import json
from json2html import *

# Tenant ID for your Azure subscription
TENANT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'

# Your service principal App ID
CLIENT = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'

# Your service principal password
KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'

# Your Azure Subscription ID
subscription_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'

credentials = ServicePrincipalCredentials(
    client_id=CLIENT,
    secret=KEY,
    tenant=TENANT_ID
)

result = []

# Create a Resource Management client
compute_client = ComputeManagementClient(credentials, subscription_id)
vm_list = compute_client.virtual_machines.list_all()
for vm in vm_list:
    resource_group = vm.id.split("/")[4]
    vm_name = vm.name
    details = compute_client.virtual_machines.instance_view(resource_group, vm_name, expand='instanceView')

    status = len(details.statuses) >= 2 and details.statuses[1]
    if status and status.code == 'PowerState/running':
        tagz = compute_client.virtual_machines.get(resource_group, vm_name).tags
        if not tagz:
            tagz = ""
        admin = ''
        if hasattr(details, 'os_profile'):
            admin = details.os_profile.admin_username
        row = {"ComputerName": vm_name, "ResourceGroup": resource_group, "Admin": admin,
               "Status": status.code, "Tags": tagz}
        result.append(row)

data = json.dumps(result)
html = json2html.convert(json=data)
print(html)

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.