Azure CLI Complete Reference Cheatsheet

Introduction: Command-Line Management for Azure Resources

The Azure Command-Line Interface (CLI) is Microsoft’s cross-platform command-line tool for managing Azure resources. It allows administrators, developers, and DevOps professionals to execute commands through a terminal using interactive command-line prompts or scripts. Azure CLI provides the flexibility to manage resources from any environment that supports command-line interfaces, making it ideal for automation, CI/CD pipelines, and infrastructure as code.

Installation & Setup

Installation Methods

PlatformInstallation CommandNotes
WindowsMSI InstallerSimplest method for Windows
macOSbrew install azure-cliUsing Homebrew
Ubuntu/Debiancurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bashScript installation
RHEL/CentOS/Fedorasudo rpm --import https://packages.microsoft.com/keys/microsoft.asc<br>sudo dnf install -y azure-cliUsing package manager
Dockerdocker run -it mcr.microsoft.com/azure-cliContainerized version

Verification & Updates

# Verify installation
az --version

# Update CLI (non-MSI installations)
az upgrade

# Enable/disable automatic update checks
az config set auto-upgrade.enable=yes
az config set auto-upgrade.enable=no

Initial Configuration

# Configure CLI defaults
az configure

# Set default output format
az config set core.output=table  # Options: json (default), jsonc, table, tsv, yaml

# Set default location
az config set defaults.location=eastus

# View current configuration
az config get

Authentication & Account Management

Sign In Methods

# Interactive sign-in (browser-based)
az login

# Username and password (not recommended for production)
az login -u <username> -p <password>

# Using a service principal with secret
az login --service-principal -u <app-id> -p <password> --tenant <tenant-id>

# Using a service principal with certificate
az login --service-principal -u <app-id> --tenant <tenant-id> --password-certificate <cert-file>

# Using a managed identity
az login --identity

# Sign in with device code (useful for remote sessions)
az login --use-device-code

Account Management

# List available subscriptions
az account list

# Show current subscription details
az account show

# Switch to different subscription
az account set --subscription <subscription-id-or-name>

# Clear cached credentials
az logout

# Show current user
az ad signed-in-user show

Working with Multiple Environments

# Create a new named profile
az login --use-device-code --profile <profile-name>

# Use a named profile for a command
az vm list --profile <profile-name>

# Azure Cloud environments
az cloud list
az cloud set --name AzureUSGovernment  # Switch to US Gov cloud
az cloud set --name AzureCloud  # Switch back to public cloud

Basic CLI Structure & Syntax

Command Format

az <group> <subgroup> <command> [arguments] [--options]

Examples:

az vm create --resource-group MyGroup --name MyVM --image UbuntuLTS
az storage account list --resource-group MyGroup

Getting Help

# Get general help
az --help
az -h

# Get help for a command group
az vm --help

# Get help for a specific command
az vm create --help

# Get examples for a command
az find "create a vm"

# Interactive mode
az interactive

Output Formatting

# Control output format
az vm list --output table  # table format
az vm list --output json   # JSON format (default)
az vm list --output jsonc  # JSON with colors
az vm list --output yaml   # YAML format
az vm list --output tsv    # Tab-separated values

# Use shorthand notation for output
az vm list -o table

# Set default output format
az config set core.output=table

Resource Management

Resource Groups

# Create a resource group
az group create --name MyResourceGroup --location eastus

# List resource groups
az group list

# Filter resource groups by name
az group list --query "[?contains(name, 'web')]"

# Delete a resource group
az group delete --name MyResourceGroup --yes --no-wait

Resource Operations

# List all resources in a resource group
az resource list --resource-group MyResourceGroup

# Get a specific resource
az resource show --resource-group MyResourceGroup --name MyResource --resource-type "Microsoft.Web/sites"

# Create a resource from an ARM template
az deployment group create --resource-group MyResourceGroup --template-file template.json --parameters parameters.json

# Export a resource group to a template
az group export --name MyResourceGroup > template.json

# Delete a specific resource
az resource delete --resource-group MyResourceGroup --name MyResource --resource-type "Microsoft.Web/sites"

Tags Management

# Add tags to a resource group
az group update --name MyResourceGroup --tags Dept=IT Environment=Test Project=Documentation

# Add tags to a resource
az resource tag --tags Dept=IT Environment=Test --resource-group MyResourceGroup --name MyVM --resource-type "Microsoft.Compute/virtualMachines"

# List resources with a specific tag
az resource list --tag Dept=IT

Virtual Machines

VM Creation

# Create a simple Linux VM
az vm create \
    --resource-group MyResourceGroup \
    --name MyLinuxVM \
    --image UbuntuLTS \
    --admin-username azureuser \
    --generate-ssh-keys

# Create a Windows VM
az vm create \
    --resource-group MyResourceGroup \
    --name MyWindowsVM \
    --image Win2019Datacenter \
    --admin-username azureuser \
    --admin-password ComplexPassword123!

# Create VM with existing resources
az vm create \
    --resource-group MyResourceGroup \
    --name MyVM \
    --image UbuntuLTS \
    --vnet-name MyVNet \
    --subnet MySubnet \
    --public-ip-address MyPublicIP \
    --nsg MyNSG

VM Management

# List all VMs
az vm list

# List all VMs in a resource group with table output
az vm list --resource-group MyResourceGroup --output table

# Start a VM
az vm start --resource-group MyResourceGroup --name MyVM

# Stop a VM (still incurs charges)
az vm stop --resource-group MyResourceGroup --name MyVM

# Deallocate a VM (stop billing)
az vm deallocate --resource-group MyResourceGroup --name MyVM

# Resize a VM
az vm resize --resource-group MyResourceGroup --name MyVM --size Standard_DS3_v2

# Delete a VM
az vm delete --resource-group MyResourceGroup --name MyVM --yes

VM Information & Operations

# Get VM details
az vm show --resource-group MyResourceGroup --name MyVM

# Get VM public IP
az vm list-ip-addresses --resource-group MyResourceGroup --name MyVM

# Run a command on a VM
az vm run-command invoke \
    --resource-group MyResourceGroup \
    --name MyVM \
    --command-id RunShellScript \
    --scripts "apt update && apt upgrade -y"

# Connect to VM via SSH
az ssh vm --resource-group MyResourceGroup --name MyVM --local-user azureuser

Storage Accounts

Storage Account Management

# Create a storage account
az storage account create \
    --name mystorageaccount \
    --resource-group MyResourceGroup \
    --location eastus \
    --sku Standard_LRS \
    --kind StorageV2

# List storage accounts
az storage account list --output table

# Get storage account connection string
az storage account show-connection-string \
    --name mystorageaccount \
    --resource-group MyResourceGroup

# Update storage account
az storage account update \
    --name mystorageaccount \
    --resource-group MyResourceGroup \
    --sku Standard_GRS

# Delete storage account
az storage account delete \
    --name mystorageaccount \
    --resource-group MyResourceGroup \
    --yes

Blob Storage Operations

# Create a container
az storage container create \
    --name mycontainer \
    --account-name mystorageaccount \
    --auth-mode login

# Upload a file to blob storage
az storage blob upload \
    --container-name mycontainer \
    --name blobname \
    --file /path/to/file \
    --account-name mystorageaccount \
    --auth-mode login

# List blobs in a container
az storage blob list \
    --container-name mycontainer \
    --account-name mystorageaccount \
    --auth-mode login \
    --output table

# Download a blob
az storage blob download \
    --container-name mycontainer \
    --name blobname \
    --file /path/to/download/location \
    --account-name mystorageaccount \
    --auth-mode login

File Share Operations

# Create a file share
az storage share create \
    --name myfileshare \
    --account-name mystorageaccount \
    --quota 1024 \
    --auth-mode login

# Upload a file to a file share
az storage file upload \
    --share-name myfileshare \
    --source /path/to/file \
    --path directory/filename \
    --account-name mystorageaccount \
    --auth-mode login

# List files in a file share
az storage file list \
    --share-name myfileshare \
    --path directory \
    --account-name mystorageaccount \
    --auth-mode login \
    --output table

Networking

Virtual Networks

# Create a virtual network
az network vnet create \
    --resource-group MyResourceGroup \
    --name MyVNet \
    --address-prefix 10.0.0.0/16 \
    --subnet-name default \
    --subnet-prefix 10.0.0.0/24

# List virtual networks
az network vnet list --output table

# Create additional subnet
az network vnet subnet create \
    --resource-group MyResourceGroup \
    --vnet-name MyVNet \
    --name MySubnet \
    --address-prefix 10.0.1.0/24

# List subnets in a VNet
az network vnet subnet list \
    --resource-group MyResourceGroup \
    --vnet-name MyVNet \
    --output table

Network Security Groups

# Create a network security group
az network nsg create \
    --resource-group MyResourceGroup \
    --name MyNSG

# Add a security rule
az network nsg rule create \
    --resource-group MyResourceGroup \
    --nsg-name MyNSG \
    --name AllowSSH \
    --priority 1000 \
    --direction Inbound \
    --access Allow \
    --protocol Tcp \
    --source-address-prefixes '*' \
    --source-port-ranges '*' \
    --destination-address-prefixes '*' \
    --destination-port-ranges 22

# List NSG rules
az network nsg rule list \
    --resource-group MyResourceGroup \
    --nsg-name MyNSG \
    --output table

# Associate NSG with subnet
az network vnet subnet update \
    --resource-group MyResourceGroup \
    --vnet-name MyVNet \
    --name MySubnet \
    --network-security-group MyNSG

Public IP Addresses

# Create a public IP address
az network public-ip create \
    --resource-group MyResourceGroup \
    --name MyPublicIP \
    --allocation-method Static

# List public IP addresses
az network public-ip list --output table

# Show public IP address
az network public-ip show \
    --resource-group MyResourceGroup \
    --name MyPublicIP \
    --query ipAddress \
    --output tsv

Web Apps & App Service

App Service Plans

# Create an App Service plan
az appservice plan create \
    --name MyPlan \
    --resource-group MyResourceGroup \
    --sku B1 \
    --is-linux

# List App Service plans
az appservice plan list --output table

# Scale up an App Service plan
az appservice plan update \
    --name MyPlan \
    --resource-group MyResourceGroup \
    --sku S1

Web Apps

# Create a web app
az webapp create \
    --name MyWebApp \
    --resource-group MyResourceGroup \
    --plan MyPlan \
    --runtime "NODE|14-lts"

# List web apps
az webapp list --output table

# Set application settings
az webapp config appsettings set \
    --name MyWebApp \
    --resource-group MyResourceGroup \
    --settings WEBSITE_NODE_DEFAULT_VERSION=14.17.0 DB_HOST=mydb.mysql.database.azure.com

# Deploy code from a GitHub repository
az webapp deployment source config \
    --name MyWebApp \
    --resource-group MyResourceGroup \
    --repo-url https://github.com/username/repo \
    --branch main \
    --manual-integration

# Enable continuous deployment
az webapp deployment source config \
    --name MyWebApp \
    --resource-group MyResourceGroup \
    --repo-url https://github.com/username/repo \
    --branch main \
    --git-token <github-token>

Databases

Azure SQL Database

# Create an Azure SQL server
az sql server create \
    --name mysqlserver \
    --resource-group MyResourceGroup \
    --location eastus \
    --admin-user serveradmin \
    --admin-password ComplexPassword123!

# Create a firewall rule
az sql server firewall-rule create \
    --resource-group MyResourceGroup \
    --server mysqlserver \
    --name AllowMyIP \
    --start-ip-address <your-ip-address> \
    --end-ip-address <your-ip-address>

# Create a database
az sql db create \
    --resource-group MyResourceGroup \
    --server mysqlserver \
    --name mydatabase \
    --compute-model Serverless \
    --family Gen5 \
    --capacity 2

# List databases
az sql db list \
    --resource-group MyResourceGroup \
    --server mysqlserver \
    --output table

Cosmos DB

# Create a Cosmos DB account
az cosmosdb create \
    --name mycosmosaccount \
    --resource-group MyResourceGroup \
    --kind MongoDB

# Create a database
az cosmosdb mongodb database create \
    --account-name mycosmosaccount \
    --resource-group MyResourceGroup \
    --name mymongodbdatabase

# Create a collection
az cosmosdb mongodb collection create \
    --account-name mycosmosaccount \
    --resource-group MyResourceGroup \
    --database-name mymongodbdatabase \
    --name mycollection \
    --throughput 400

Monitoring & Diagnostics

Monitoring Basics

# Enable diagnostic settings for a VM
az monitor diagnostic-settings create \
    --resource "/subscriptions/<subscription-id>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/MyVM" \
    --name mydiagnosticsetting \
    --storage-account mystorageaccount \
    --logs '[{"category":"AllMetrics","enabled":true}]' \
    --metrics '[{"category":"AllLogs","enabled":true}]'

# List metrics for a VM
az monitor metrics list \
    --resource "/subscriptions/<subscription-id>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/MyVM" \
    --metric "Percentage CPU"

# Create a metric alert
az monitor metrics alert create \
    --name "CPU Alert" \
    --resource-group MyResourceGroup \
    --scopes "/subscriptions/<subscription-id>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/MyVM" \
    --condition "avg Percentage CPU > 80" \
    --window-size 5m \
    --evaluation-frequency 1m \
    --severity 2

Log Analytics

# Create a Log Analytics workspace
az monitor log-analytics workspace create \
    --resource-group MyResourceGroup \
    --name MyWorkspace

# List Log Analytics workspaces
az monitor log-analytics workspace list --output table

# Query Log Analytics
az monitor log-analytics query \
    --workspace MyWorkspace \
    --analytics-query "Heartbeat | summarize count() by Computer | order by count_ desc" \
    --output table

Container Services

Azure Container Registry

# Create a container registry
az acr create \
    --resource-group MyResourceGroup \
    --name myregistry \
    --sku Basic

# Log in to ACR
az acr login --name myregistry

# List repositories
az acr repository list --name myregistry

# List tags for a repository
az acr repository show-tags \
    --name myregistry \
    --repository myapp

Azure Kubernetes Service (AKS)

# Create an AKS cluster
az aks create \
    --resource-group MyResourceGroup \
    --name MyAKSCluster \
    --node-count 2 \
    --enable-addons monitoring \
    --generate-ssh-keys

# List AKS clusters
az aks list --output table

# Get AKS credentials
az aks get-credentials \
    --resource-group MyResourceGroup \
    --name MyAKSCluster

# Scale AKS cluster
az aks scale \
    --resource-group MyResourceGroup \
    --name MyAKSCluster \
    --node-count 3

# Upgrade AKS cluster
az aks upgrade \
    --resource-group MyResourceGroup \
    --name MyAKSCluster \
    --kubernetes-version 1.23.8

Azure Functions

# Create a function app
az functionapp create \
    --resource-group MyResourceGroup \
    --consumption-plan-location eastus \
    --runtime node \
    --runtime-version 14 \
    --functions-version 4 \
    --name MyFunctionApp \
    --storage-account mystorageaccount

# List function apps
az functionapp list --output table

# Get function app publish profile
az functionapp deployment list-publishing-profiles \
    --name MyFunctionApp \
    --resource-group MyResourceGroup \
    --xml

# Deploy function app from ZIP
az functionapp deployment source config-zip \
    --resource-group MyResourceGroup \
    --name MyFunctionApp \
    --src /path/to/function.zip

Security & Identity

Role-Based Access Control (RBAC)

# List role definitions
az role definition list --name "Contributor" --output table

# List role assignments
az role assignment list --all --output table

# Create a role assignment
az role assignment create \
    --assignee "user@example.com" \
    --role "Reader" \
    --resource-group MyResourceGroup

# Delete a role assignment
az role assignment delete \
    --assignee "user@example.com" \
    --role "Reader" \
    --resource-group MyResourceGroup

Key Vault

# Create a Key Vault
az keyvault create \
    --name MyKeyVault \
    --resource-group MyResourceGroup \
    --location eastus

# Set a secret
az keyvault secret set \
    --vault-name MyKeyVault \
    --name MySecret \
    --value "SecretValue"

# Get a secret
az keyvault secret show \
    --vault-name MyKeyVault \
    --name MySecret

# Create a key
az keyvault key create \
    --vault-name MyKeyVault \
    --name MyKey \
    --protection software

# Create a certificate
az keyvault certificate create \
    --vault-name MyKeyVault \
    --name MyCertificate \
    --policy "$(az keyvault certificate get-default-policy)"

Query & Filtering Data

JMESPath Queries

# Filter resources by name
az resource list --query "[?name=='MyVM']"

# Select specific properties
az vm list --query "[].{Name:name, Group:resourceGroup, Status:powerState}" --output table

# Filter and count
az vm list --query "length([?powerState=='VM running'])"

# Sort results
az vm list --query "sort_by([].{Name:name, Size:hardwareProfile.vmSize}, &Name)" --output table

# Complex filtering
az vm list --query "[?tags.Environment=='Production' && location=='eastus'].{Name:name, Size:hardwareProfile.vmSize}" --output table

Common Query Patterns

# Get resource ID
az vm show --resource-group MyResourceGroup --name MyVM --query id --output tsv

# Extract single value
az vm show --resource-group MyResourceGroup --name MyVM --query "powerState" --output tsv

# First item in array
az vm list --query "[0]"

# Count items with specific property
az vm list --query "length([?storageProfile.osDisk.osType=='Linux'])"

# Conditional output
az vm list --query "[].{Name:name, OS:storageProfile.osDisk.osType == 'Linux' ? 'Linux' : 'Windows'}" --output table

Automation Techniques

Working with ARM Templates

# Validate template
az deployment group validate \
    --resource-group MyResourceGroup \
    --template-file template.json \
    --parameters parameters.json

# Deploy template
az deployment group create \
    --resource-group MyResourceGroup \
    --template-file template.json \
    --parameters parameters.json

# Export template from existing resource group
az group export \
    --name MyResourceGroup \
    --include-parameter-default-value \
    --include-comments \
    --output-file exported-template.json

Bicep Files

# Install Bicep CLI
az bicep install

# Build ARM template from Bicep file
az bicep build --file main.bicep

# Deploy Bicep file directly
az deployment group create \
    --resource-group MyResourceGroup \
    --template-file main.bicep \
    --parameters parameters.json

# Decompile ARM template to Bicep
az bicep decompile --file template.json

Automation with Scripts

# Run commands in parallel
az vm list-ip-addresses --ids $(az vm list -g MyResourceGroup --query "[].id" -o tsv)

# Loop through resources
for id in $(az vm list --query "[].id" -o tsv); do
  az vm show --ids $id --query "name" -o tsv
done

# Export results to CSV
az vm list --query "[].{Name:name,Group:resourceGroup,Location:location}" -o tsv > vms.csv

Productivity Tips & Tricks

CLI Configuration

# Set defaults to reduce typing
az config set defaults.group=MyResourceGroup
az config set defaults.location=eastus

# Create command aliases
az config set extension.alias.vm-logs="vm run-command invoke --command-id RunShellScript --scripts 'tail -n 100 /var/log/syslog'"

# Use the alias
az vm-logs --resource-group MyResourceGroup --name MyVM

Extensions

# List available extensions
az extension list-available --output table

# Add an extension
az extension add --name <extension-name>

# Update all extensions
az extension update --all

# Remove an extension
az extension remove --name <extension-name>

Batch Operations

# Create multiple VMs with a single command
az vm create -g MyResourceGroup -n MyVM --image UbuntuLTS --count 3 --generate-ssh-keys

# Delete multiple resources
az resource delete --ids $(az resource list --query "[?tags.Environment=='Test'].id" -o tsv)

# Start multiple VMs
az vm start --ids $(az vm list -g MyResourceGroup --query "[].id" -o tsv)

Best Practices

Security Best Practices

  • Use service principals with minimum required permissions
  • Rotate credentials regularly
  • Store secrets in Key Vault, not in scripts
  • Use managed identities where possible
  • Enable just-in-time access for privileged operations
# Create a service principal with minimum permissions
az ad sp create-for-rbac --name "MyApp" --role "Reader" --scopes /subscriptions/<subscription-id>/resourceGroups/MyResourceGroup

# Configure service principal to use certificate
az ad sp credential reset --name "MyApp" --cert @cert.pem --append

# Use managed identity for Azure resources
az vm identity assign --resource-group MyResourceGroup --name MyVM --identities [system]

Performance Best Practices

  • Use the --no-wait flag for long operations
  • Use the --query parameter to limit returned data
  • Batch operations when possible
  • Use the --ids parameter for bulk operations
# Start operation and continue immediately
az vm create --resource-group MyResourceGroup --name MyVM --image UbuntuLTS --no-wait

# Check status of asynchronous operations
az group deployment operation list --resource-group MyResourceGroup --name DeploymentName

Resources for Further Learning

Official Documentation

Getting Help

Advanced Learning

Scroll to Top