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.
Using the subprocess solution is problematic as subprocess doesn't check the PATH where Azure CLI is found e.g. on Windows. To use "cmd -c" would be a Windows-specific solution and needs a fork if/else for additional Linux support.
@tom-sun's answer is almost correct, as you can reuse the Azure CLI python modules, as the CLI is also written in Python. Problem is, that the return of the .invoke() instruction is always returning the error code. To get the full body response, you must pass a file like object on the argument list of the underlying Knack Code to get the response. By default, this redirects to StdOut, that is why you can see it e.g. in your terminal but you always get a zero for success.
I wrote a little helper function that accepts the Azure CLI instructions in one string (I don't like many arguments as list, it doesn't read nicely - but that is just a personal preference, don't blame me). It uses a temporary file as output target and then it is read back in memory - this is required afaik from the underlying Knack CLI code; by default StdOut is the standard pipe.
It requires you to have azure-cli installed for Python:
pip install azure-cli
File
azhelper.py
:You can then invoke like this:
Of course you need to be logged in, see @4c74356b41 answer.
If somebody finds a better way to deal with the response instead with a temporary file, this would be much appreciated! I tried with an in memory StringIO object but this somehow doesn't comply with the underlying Knack CLI code.
since you still didnt delete this I assume you still looking for a way.
you will also need to silently auth first with something like:
I think you can use the subprocess and call the az cli to get the output instead using get_default_cli. Reference Git Repo
Use
subprocess.run
instead of usingsubprocess.Popen
It will by default cause python script to wait until the program run from subprocess (in this case azure cli command) is completed.
For example, let's create an Azure AD application.
For more information on using subprocess module see this link
According to this file. we could invoke the Azure CLI with following way:
Note : If you get
No module named 'azure.cli.command_modules'
error, please installazure-cli