Skip to main content

Automating Azure Tasks with CLI and Cloud Shell

Automate Azure with the CLI in Cloud Shell: write a loop script, filter output with --query, and rerun it safely. Includes key az commands.

Overview and What You Will Learn

The Azure CLI (az) lets you create, list, query, and delete Azure resources from a terminal, and Cloud Shell gives you that terminal in your browser with nothing to install. In this lab, you will open Cloud Shell, write a reusable script that creates several resources in a loop and is safe to rerun, and use --query and --output to extract exactly the data you need.

Why This Matters in Production

Scripted infrastructure removes the naming slips and forgotten tags that come from repeating a Portal wizard by hand. Imagine a platform team at a company like Hotstar preparing for a major live event that needs twenty identical resources. Twenty trips through the wizard invite mistakes and waste hours, while a CLI loop takes seconds, gives identical results every time, and is reviewed and reused for the next event.

Core Principles

Every action in the Portal, CLI, PowerShell, or REST API goes through the same engine, Azure Resource Manager (ARM). That is why results stay consistent no matter which tool you use.

flowchart TD A([You]) --> B[Portal] A --> C[Azure CLI
in Cloud Shell] A --> D[PowerShell or REST] B --> E[Azure Resource Manager] C --> E D --> E E --> F[(Azure services)] classDef person fill:#8B5CF6,color:#FFFFFF classDef tool fill:#326CE5,color:#FFFFFF classDef cloud fill:#10B981,color:#FFFFFF class A person class B,C,D tool class E,F cloud

Cloud Shell is a browser-based terminal with the CLI and PowerShell preinstalled and already signed in as you. Your $HOME is a 5 GB image kept in an Azure Files share, so scripts saved there survive between sessions, and a session times out after 20 minutes of inactivity.

CLI output can be shaped in three ways, and picking the right one is the core skill of this lab:

  1. --output table prints readable columns for a human exploring interactively.
  2. --output tsv prints plain values with no quotes, ready for a script to consume.
  3. --query runs a JMESPath expression to filter and reshape the JSON before it is printed.

Detailed Step-by-Step Practical Lab

How to Open Cloud Shell and Check Your Subscription

Open Cloud Shell from the Portal's top navigation bar and choose Bash if prompted. The first launch asks you to create a small storage account for persistence, which lives outside this lab's resource group. Confirm your active account and subscription:

Bash
az account show --output table
az account list --output table
az account set --subscription "Pay-As-You-Go"
How to Write a Loop Script That Is Safe to Rerun

Save the script in your persistent home directory. The count is an argument, and each account is skipped if it already exists, so rerunning after a failure does not break on resources that were already created. Storage account names are globally unique, so replace rahul with your own suffix.

Bash
mkdir -p ~/scripts
cat > ~/scripts/create-storage.sh << 'EOF'
#!/usr/bin/env bash
# Stop on the first error, on unset variables, and on failed pipes
set -euo pipefail
RG="rg-cli-lab-mumbai"
LOCATION="centralindia"
COUNT="${1:-3}"
# Creating a group that already exists is harmless
az group create --name "$RG" --location "$LOCATION" --output none
for i in $(seq 1 "$COUNT"); do
NAME="stclilabrahul$i"
# Skip accounts that already exist
if az storage account show --name "$NAME" --resource-group "$RG" --output none 2>/dev/null; then
echo "$NAME already exists, skipping"
continue
fi
az storage account create \
--name "$NAME" \
--resource-group "$RG" \
--location "$LOCATION" \
--sku Standard_LRS \
--tags env=loadtest owner=rahul \
--output none
echo "Created $NAME"
done
EOF
chmod +x ~/scripts/create-storage.sh
~/scripts/create-storage.sh 3
Tip

Set defaults once with az configure --defaults group=rg-cli-lab-mumbai location=centralindia and you can drop --resource-group and --location from later commands. Clear them with az configure --defaults group="" location="".

How to List Resources in Table Format

Table output is the quickest way to confirm the loop produced exactly what you expect.

Bash
az storage account list \
--resource-group rg-cli-lab-mumbai \
--output table
How to Filter and Extract Fields with az --query

Use --query to select only what you need, and --output tsv when a script will read the result.

Bash
# Just the names, one per line
az storage account list \
--resource-group rg-cli-lab-mumbai \
--query "[].name" --output tsv
# Only accounts whose name starts with a prefix
az storage account list \
--resource-group rg-cli-lab-mumbai \
--query "[?starts_with(name, 'stclilab')].name" --output tsv
# Only accounts carrying a specific tag
az storage account list \
--resource-group rg-cli-lab-mumbai \
--query "[?tags.env=='loadtest'].name" --output tsv
# Name, location, and SKU as columns
az storage account list \
--resource-group rg-cli-lab-mumbai \
--query "[].[name, location, sku.name]" --output table
Remember

--query uses JMESPath and runs on the client after the JSON comes back. It is the Azure CLI's counterpart to --format in gcloud, and it becomes essential once you script against dozens of resources.

How to Clean Up Safely

Preview exactly what is about to be deleted, then delete the whole group.

Bash
# Preview: this must list only the lab's resources
az resource list --resource-group rg-cli-lab-mumbai --output table
az group delete --name rg-cli-lab-mumbai --yes --no-wait

Production Best Practices & Common Pitfalls

Common Mistake

Creating many similar resources in the Portal wizard "since it's just a few." Manual repetition is where inconsistent names, forgotten tags, and copy-paste errors creep in, while a script gives the same correct result every time.

Tip

Keep frequently used commands as small scripts in ~/scripts. Cloud Shell's persistent home directory keeps them after you close the browser tab.

Security

A loop that deletes resources is exactly as fast as a loop that creates them. Always preview with a list or az resource list first, and test destructive commands in a throwaway Resource Group before running them against anything real.

  • Use --output table while exploring and --output tsv or --query when scripting. Tables are easy for humans to scan, while tsv and JSON are stable for programs to parse.
  • Always put set -euo pipefail at the top of scripts. Without it, a failed creation in the middle of a loop is silently ignored and later steps run against missing resources.
  • Tag everything a script creates. Tags such as env=loadtest let you filter, audit, and clean up by purpose instead of guessing from names.
  • Make scripts idempotent. Check whether a resource exists before creating it, so a second run completes the job instead of failing halfway.
  • Never hard-code secrets in scripts. Read them from Azure Key Vault or prompt for them at run time.

Quick Reference & Troubleshooting Commands

Command Description
az account show Show the active subscription and account
az account set --subscription NAME Switch the active subscription
az configure --defaults group=RG location=LOC Set default group and location
az storage account list --query "[].name" -o tsv Extract only names from a resource list
az group exists --name RG Check whether a group exists before creating it
az group delete --yes --no-wait Delete a group without prompting or waiting

Explore More in Azure Fundamentals and Governance

All 6 Topics

Frequently Asked Questions

Is Automating Azure Tasks with CLI and Cloud Shell free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Automating Azure Tasks with CLI and Cloud Shell topic cover?

Automate Azure with the CLI in Cloud Shell: write a loop script, filter output with --query, and rerun it safely. Includes key az commands.

Found a mistake, an outdated step or a broken link?