This is where the --query
parameter can come in handy. Let's take a look at how we can simplify the CLI experience using --query
starting with setting the current account context.
Before you can set the account context, you must discover the name of the Subscription in your account. We do this by running
az account list
Running this command returns something like this:
[
{
"cloudName": "AzureCloud",
"homeTenantId": "some-guid",
"id": "some-guid",
"isDefault": false,
"managedByTenants": [],
"name": "Subscription Name 1",
"state": "Enabled",
"tenantId": "some-guid",
"user": {
"name": "michael.paterson@cloudconstruct.com",
"type": "user"
}
},
{
"cloudName": "AzureCloud",
"homeTenantId": "some-guid",
"id": "some-guid",
"isDefault": false,
"managedByTenants": [],
"name": "Subscription Name 2",
"state": "Enabled",
"tenantId": "some-guid",
"user": {
"name": "michael.paterson@cloudconstruct.com",
"type": "user"
}
}
Now if you have 50 results that is a lot of scrolling to find the one you are looking for. Instead, let's just bring back the list of subscription names via the name property in the json. Note that because the list
command returns an array, we must use []
to select properties in that array like this:
az account list --query [].name
That returns a result similar to this:
[
"Subscription Name 1",
"Subscription Name 2",
"Subscription Name 3",
"Subscription Name 4"
]
That's much easier to read. Now what if we wanted to pull back multipe fields, say id
, name
, and state
? The syntax would look like this:
az account list --query '[].[id, name, state]'
Note that the query is now in single quotes and surrounded with brackets and returns something like the following:
[
[ "1", "Subscription Name 1", "Enabled" ],
[ "2", "Subscription Name 2", "Enabled" ],
[ "3", "Subscription Name 3", "Enabled" ],
[ "4", "Subscription Name 4", "Enabled" ]
]
What if want to give names to these properties?
az account list --query '[].{SubscriptionId:id, SubscriptionName:name, SubscriptionState:state}'
The results now look like this:
[
{
"SubscriptionId": "1",
"SubscriptionName": "Subscription Name 1",
"SubscriptionStatus": "Enabled"
},
{
"SubscriptionId": "2",
"SubscriptionName": "Subscription Name 2",
"SubscriptionStatus": "Enabled"
},
{
"SubscriptionId": "3",
"SubscriptionName": "Subscription Name 3",
"SubscriptionStatus": "Enabled"
},
{
"SubscriptionId": "4",
"SubscriptionName": "Subscription Name 4",
"SubscriptionStatus": "Enabled"
}
]
Note that we are now dealing with JSON objects instead of string arrays which is great if we are writing code for automation purposes but isn't quite as readable. To make something easier to read let's output the data to a table: