Azure CLI and VM’s

Here we go with a quick query to get all your VM’s and IP addresses in a subscription

az login

$accounts = az account list | convertfrom-json | sort name

$accounts | foreach {az vm list-ip-addresses –query “[*].virtualMachine.[resourceGroup, name, network.privateIpAddresses[0], network.publicIpAddresses[0].ipAddress]” –subscription $_.id}

Line 1:  We are logging into Azure (skip this step if you have already done so).

Line 2:  We get all of your subscriptions, convert them into objects and sort them by name.  The sorting is optional.  You can sort by id if you like.

Line 3:  We iterate over the list of subscriptions you have access to, and for each one, we query the list of all VM’s in that subscription, getting the resource group, the name of the vm, the private IP (if any), and the public IP (if any).  When you look at the JSON returned from “az vm list-ip-addresses”, you will see that the private and public IP’s returned for each object is the complete list of addresses in that subnet.  We only need to grab the first one as that is the one assigned to the VM.

I really recommend reading the JMESPath documentation (at http://jmespath.org/examples.html).  It is simple query notation, with a couple small quirks, but easily digestible in 20 minutes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s