Manage Resources with Azure CLI
Learn to manage Azure resources efficiently using the Azure CLI. This hands-on lesson covers core concepts, practical steps, troubleshooting, and what to study next in the Azure Tutorial track.
Focus: manage resources with azure cli
You’ve provisioned resources through the portal and maybe automated a few scripts, but now you’re staring at a growing list of resource groups and wondering how to keep it all under control without clicking through endless blades. The Azure CLI is your command-line superpower: it turns every Azure management task into a fast, repeatable, scriptable operation. In this lesson, you’ll learn to manage resources with Azure CLI — from querying and tagging to scaling and cleaning up — so you can work smarter, not harder.
The problem this lesson solves
Azure’s portal is perfect for exploring, but it’s terrible for repeatable, predictable operations. Imagine you need to update 10 virtual machines with a new tag, or you want to check the status of every web app in your subscription. Doing that through the portal means dozens of clicks and a high chance of missing something. The pain is real: manual resource management leads to configuration drift, slow responses to incidents, and hours wasted on mundane tasks.
This lesson tackles that problem head-on. By the end, you’ll be able to manage resources with Azure CLI — a skill that lets you automate everything from tagging to scaling, and brings your cloud operations into the world of scripts, CI/CD, and Infrastructure as Code.
Core concept / mental model
Think of Azure CLI as a remote control for your Azure subscription. Instead of navigating the portal’s graphical interface, you send text commands — like a conversation with Azure. Each command targets a resource (a VM, a storage account, a web app) inside a resource group (a logical container).
The CLI is built on the Azure REST API, but it hides the complexity. You don’t need to understand HTTP requests; you just type az vm list or az group create. The CLI handles authentication, JSON formatting, and error checking.
A useful analogy: the portal is like using a GUI file manager, while the CLI is like using a terminal — both achieve the same goal, but the CLI is faster and scriptable. Here’s a simple diagram of the hierarchy you’ll be working with:
Subscription
└── Resource Group
├── Virtual Network
├── Storage Account
├── Virtual Machine
└── ... (any Azure resource)
Pro tip: Always organize resources by resource group — it makes management and cleanup far easier. Many Azure CLI commands operate at the resource group level, so a good grouping strategy saves you time.
How it works step by step
The core workflow for managing resources with Azure CLI follows a predictable pattern. Once you understand this, every management task becomes a variation on the same theme.
- Authenticate – Ensure you are logged in with
az login(or using a service principal for automation). - Set your subscription – If you have multiple subscriptions, set the active one with
az account set --subscription <id>. - Identify the resource – Use the
resource-groupandnameparameters to pinpoint the resource you need. - Execute the management operation – Whether it’s listing, tagging, scaling, or deleting, each task is a specific
az <resource-type> <command>. - Verify the result – Use query parameters or
--output tableto confirm the change.
This pattern is reusable. For example, to tag every VM in a resource group, you’d loop over the list from az vm list and apply az vm update with the new tag. Cause and effect are direct: each command produces a JSON response that you can parse for automation.
Hands-on walkthrough
Let’s put the theory into practice. The hands-on example below will walk you through a typical scenario: listing, tagging, and scaling a virtual machine.
Step 1: Authenticate and set the subscription
First, log in and set your subscription (if needed):
az login
# List your subscriptions and copy the ID you want to use
az account list --output table
# Set the active subscription
az account set --subscription "Your-Subscription-ID"
Expected output for az login will open a browser window; after success, you’ll see a JSON array with your subscriptions. az account list --output table shows a table with your subscription names and IDs.
Step 2: List resources in a resource group
Now let’s see what you have in a specific resource group:
# List all resources in the group 'myResourceGroup'
az resource list --resource-group myResourceGroup --output table
Expected output (simplified):
Name Type Location
------------ -------------------- ----------
myVM Microsoft.Compute/virtualMachines eastus
myStorage Microsoft.Storage/storageAccounts eastus
Step 3: Tag a resource
Tags help with cost tracking and organization. Let’s add a tag to the VM:
# Add a tag 'Environment=Production' to the VM
az resource tag --resource-group myResourceGroup \
--name myVM \
--tags Environment=Production
The command returns a JSON object with the updated tags. You can see the result with:
az resource show --resource-group myResourceGroup --name myVM --query tags
Expected output:
{
"Environment": "Production"
}
Step 4: Scale a virtual machine
Scaling a VM’s size is a common management task. Use az vm resize:
az vm resize --resource-group myResourceGroup \
--name myVM \
--size Standard_DS2_v2
Expected output: a JSON object summarizing the VM’s new hardware profile, including the hardwareProfile.vmSize field. The command may take a few minutes to complete as it deallocates and reallocates the VM.
Step 5: Clean up (delete) a resource group
Finally, when you’re done, you can delete the whole resource group to avoid ongoing costs:
az group delete --name myResourceGroup --yes
This command will prompt for confirmation unless you pass --yes. It deletes all resources inside the group. Expected output is a long-running JSON status that ends with "provisioningState": "Succeeded".
Pro tip: Always use
--yesin automation scripts to avoid interactive prompts. For safety, consider--no-waitto return immediately and let the deletion run in the background.
Compare options / when to choose what
Azure provides several ways to manage resources. The Azure CLI is not always the best fit. Here’s a quick comparison:
| Tool | Best for | Limitations |
|---|---|---|
| Azure CLI | Quick commands, scripting, automation, CI/CD pipelines | Requires shell knowledge, can be verbose |
| Azure Portal | Visual exploration, one-off changes, learning | Not repeatable, slow for bulk operations |
| PowerShell | Windows-centric automation, deep integration with PowerShell | Not cross-platform (though Azure PowerShell is) |
| ARM/Bicep | Infrastructure as code, declarative deployments | Steeper learning curve, not for ad-hoc tasks |
| REST API | Full control, custom integrations | Requires HTTP knowledge, more code |
When to choose what: - Use Azure CLI for day-to-day management, scripting, and quick fixes. - Use Bicep when you need to deploy and manage entire environments reproducibly. - Use Azure Portal for quick visual checks or when explaining concepts to others. - Use REST API only when you need integration in a custom application.
Remember: The CLI is your friend for operational tasks; IaC tools are better for long‑term infrastructure definitions. Also, the CLI supports
--output json,--output table, or--output yamlto suit your needs.
Troubleshooting & edge cases
Error: az: command not found
Cause: The Azure CLI is not installed.
Fix: Install it per the official guide for your OS (e.g., brew install azure-cli on macOS, winget install Microsoft.AzureCLI on Windows, or the apt package on Ubuntu).
Error: Please run 'az login' to setup account.
Cause: You are not authenticated.
Fix: Run az login and complete the interactive browser flow. If you are in a headless environment, use a service principal with az login --service-principal -u <appId> -p <password> --tenant <tenant>.
Error: (ResourceGroupNotFound) ResourceGroup 'myResourceGroup' could not be found.
Cause: The resource group does not exist in your current subscription.
Fix: Check the name spelling and the active subscription (az account show). Use az group list --output table to see all groups.
Error: (Conflict) OperationNotAllowed
Cause: You’re trying to resize a VM that is not deallocated, or the VM’s current size doesn’t support the target size.
Fix: First stop and deallocate the VM with az vm deallocate. Then resize. Also verify that the target size is available in your region (use az vm list-sizes --location <region>).
Edge case: Tags on large numbers of resources
If you have hundreds of VMs, applying tags one by one is slow. Use a loop in bash or PowerShell:
for id in $(az vm list --resource-group myResourceGroup --query "[].id" -o tsv); do
az resource tag --id $id --tags Environment=Production
done
This iterates over each VM ID and applies the tag. Always test on a small sample before running on a production environment.
Edge case: Output parsing
When scripting, you’ll often need a specific value (like a resource ID). Use --query with JMESPath to extract it:
vm_id=$(az vm show --resource-group myResourceGroup --name myVM --query id -o tsv)
echo "VM ID is: $vm_id"
What you learned & what's next
Congratulations! You now know how to manage resources with Azure CLI: authenticating, setting subscriptions, listing, tagging, scaling, and deleting resources. You also understand when to use the CLI versus other tools like Bicep or the portal.
You’ve achieved the core objectives: - Explain the core idea behind Manage resources with Azure CLI – It’s a scriptable remote control for your Azure resources. - Complete a practical exercise for Manage resources with Azure CLI – You tagged and resized a VM, and cleaned up a resource group.
Now you’re ready to take the next step in the Azure Tutorial track. The natural progression is to automate these CLI commands in CI/CD pipelines or to move towards Infrastructure as Code with Bicep. Master the CLI first — it’s a foundational skill for any Azure developer or DevOps engineer. Keep practicing, and soon you’ll manage entire environments from your terminal.
Practice recap
Try this mini-exercise: create a resource group, add a Linux VM with az vm create, then tag it and resize it using the commands from this lesson. Finally, delete the resource group to clean up. This will solidify the workflow and prepare you for automating it in a pipeline.
Common mistakes
- Forgetting to set the correct subscription before running commands — always verify with
az account show. - Using
az vm resizewithout deallocating the VM first — you'll get a conflict error. Remember toaz vm deallocatefirst. - Deleting a resource group without
--yesin scripts — this will hang waiting for confirmation. Use--yesfor automation. - Assuming the CLI is installed on all machines — always check with
az versionor install it explicitly in your dev container/CI. - Ignoring the output format — piping JSON straight into scripts can break if you don't use
--queryto extract just what you need.
Variations
- Use
az resource list --query "[?type=='Microsoft.Compute/virtualMachines']"to filter resources by type without extra loops. - For Windows environments, use PowerShell with
azcommands — output formatting and variables differ, but the commands are identical. - Consider using
az deployment group createwith a Bicep file for reproducible, declarative resource management instead of imperative CLI commands.
Real-world use cases
- Automated tagging of all VMs in a resource group for cost allocation in a multi-team subscription.
- Scheduled scaling down of non-production VMs after hours via a cron job that runs
az vm deallocate. - Cleanup of stale resource groups in a CI/CD pipeline to avoid monthly billing surprises.
Key takeaways
- The Azure CLI is a scriptable interface to manage Azure resources — faster and more repeatable than the portal.
- Always set your subscription explicitly with
az account setto avoid operating on the wrong one. - Tagging, scaling, and cleanup are straightforward with
az resource tag,az vm resize, andaz group delete. - Use
--queryand--output tableto parse command output efficiently in scripts. - For bulk operations, loop over resource IDs instead of writing repetitive commands.
- The CLI complements IaC tools like Bicep — use it for operational tasks, not for deploying entire environments.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.