How to run Azure CLI commands using python?

I am L picture I am L · Jul 26, 2018 · Viewed 13.8k times · Source

I want to use Azure CLI to get the list of all the VMs in my resource group. But I want to implement the same using a python script.

For example, I will use the following command in Azure CLI to list the VMs in my resource group:

" az vm list -g MyResourceGroup "

But, I want the python script to do the same, where I just have to incorporate the CLI command in the python program.

Answer

joek575 picture joek575 · May 2, 2019

I have been implementing this over the last couple days. The method that @cbehrenberg provides is mostly what I used, but I found that you can do it without using a temporary file. Instead catch the output directly from the azure client. Thought it might be useful.

from azure.cli.core import get_default_cli

def az_cli (args_str):
    args = args_str.split()
    cli = get_default_cli()
    cli.invoke(args)
    if cli.result.result:
        return cli.result.result
    elif cli.result.error:
        raise cli.result.error
    return True

Then invoked the same way:

from azhelper import az_cli

response = az_cli("vm list")
print("vm's: %s" % (response))