Create output variables with Azure CLI 2.0

I’m using more and more the Azure CLI 2.0, which makes my scripting life with Azure Resources a lot easier.

The default output of the Azure CLI is json, but you can also use other kind of output formats, as described in this blog.

I want to have some variables that I can reuse in other commands, so let’s say I want to get the name of all the Resource Groups which have a tag called Kind with a value VM, I can use the following JMESPath query:

az group list --query "[?tags.Kind=='VM'].name"

The output will be:

[
  "Development",
  "Mystique"
]

Now, I want to pick the first one:

az group list --query "[?tags.Kind=='VM'].name|[0]"

Let’s set the output into a variable called rgName so that I can reuse it later:

Note: I am working from a Bash shell, so variables are defined like name=value and referred later with a $ sing in front of it

rgName="$(az group list --query "[?tags.Kind=='VM'].name|[0]" --output tsv)"

the switch –output tsv makes possible to remove the double quotes from the output.

Now we can reuse the variable in other commands:

az group show -n $rgName

And the output:

{
  "id": "/subscriptions/ff1a0889-5f9e-44bc-908c-59e3e99361c3/resourceGroups/Development",
  "location": "westeurope",
  "managedBy": null,
  "name": "Development",
  "properties": {
    "provisioningState": "Succeeded"
  },
  "tags": {
    "Kind": "VM"
  }
}

 

2 thoughts on “Create output variables with Azure CLI 2.0

Add yours

  1. Hey,
    Thanks for the post. It really helped me. Just wondering. You declare rgName without the $ sign and then use it with the $ sign ($rgName). Is this a typo?

    Like

    1. Hi Russel,

      it’s not a typo, it’s up to the environment you are working on. In this case it’s Bash, and there you declare a variable like name=value and then reference it later with the $ sign in front of it.
      I will change my post and make it more clear. Thanks!

      Like

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: