Azure CLI
Complete the full lesson to earn 25 points
Work through each section, then tap “Mark as Complete” on the last one.
✦ Skip the page breaks and see fewer ads — read each lesson on a single page with Pro
Mastering Azure CLI: Managing and Deploying Cloud Infrastructure
Introduction: Why Command Line Matters in the Cloud
In the early days of cloud computing, many engineers relied heavily on the graphical user interface (GUI) provided by the Azure Portal. While the Portal is excellent for exploring services, visualizing resource relationships, and performing one-off tasks, it quickly becomes a bottleneck for professional cloud operations. As your infrastructure grows from a handful of virtual machines to complex, multi-region environments, manual clicking becomes error-prone, slow, and impossible to audit. This is where the Azure Command-Line Interface (CLI) becomes an essential tool in your professional toolkit.
The Azure CLI is a cross-platform command-line tool that allows you to connect to Azure and execute administrative commands on your resources. It is designed for developers, system administrators, and DevOps engineers who prioritize efficiency, repeatability, and automation. By using the CLI, you move away from "point-and-click" management toward "infrastructure-as-code" principles. You can script your deployments, version control your commands, and integrate your cloud management into automated CI/CD pipelines.
Understanding the Azure CLI is not just about memorizing commands; it is about changing your mindset toward cloud management. When you use the CLI, you are interacting with the Azure Resource Manager (ARM) API directly. This provides a level of precision and speed that the web interface simply cannot match. Whether you are creating a simple storage account, scaling a Kubernetes cluster, or managing user access, the CLI provides a consistent, predictable way to interact with your cloud footprint.
Getting Started: Installation and Configuration
Before you can issue commands to Azure, you must install the CLI on your local machine or your preferred development environment. The Azure CLI is built using Python and is designed to run on Windows, macOS, and various Linux distributions. It is also available as a Docker container, which is a popular choice for build agents and CI/CD runners.
Installation Options
- Windows: You can use the MSI installer provided by Microsoft, or use a package manager like
wingetorchocolatey. - macOS: The most common approach is using
Homebrew, which simplifies the update process significantly. - Linux: Microsoft provides specific instructions for major distributions like Ubuntu, Debian, CentOS, and Fedora, typically involving adding a Microsoft repository to your system.
- Docker: If you prefer to keep your host machine clean, you can pull the official
mcr.microsoft.com/azure-cliimage and run it as a container.
Once installed, the first command you will likely run is az login. This command opens a browser window or provides a device code to authenticate your identity against your Azure tenant. After authentication, the CLI stores a token locally, allowing you to run subsequent commands without re-authenticating every time.
Tip: Managing Multiple Subscriptions If your organization has multiple subscriptions, you will quickly find that the CLI needs to know which one to target. Use
az account list --output tableto see all available subscriptions, and then useaz account set --subscription "Name or ID"to switch your active context.
Navigating the Command Structure
The Azure CLI follows a logical, hierarchical structure. Understanding this structure is the key to becoming proficient, as you won't need to memorize every single flag for every command. Most commands follow the pattern: az [group] [subgroup] [action] [parameters].
Breaking Down the Hierarchy
az: The base command that invokes the Azure CLI.group: The category of the service, such asvm,storage,network, orgroup(for resource groups).subgroup: Sometimes needed for more specific categorization, such asvm extensionorstorage account.action: The verb that defines what you are doing, such ascreate,list,delete, orshow.parameters: The specific arguments like--name,--resource-group, or--location.
For example, if you want to create a new resource group, the command is az group create --name MyResourceGroup --location eastus. This structure is consistent across the entire product. Once you learn how to create a resource group, you have essentially learned how to create a storage account, a virtual network, or a SQL database; you simply swap the group and the parameters.
Practical Deployment: Managing Resources
Deploying resources via the CLI is a fundamental skill. Let's walk through a real-world scenario: deploying a standard virtual machine. While the Portal might ask you to navigate through a dozen screens, the CLI lets you define the entire state in a single command.
Example: Creating a Virtual Machine
To create a Linux virtual machine, you would run a command similar to this:
az vm create \
--resource-group MyResourceGroup \
--name MyWebVM \
--image Ubuntu2204 \
--admin-username azureuser \
--generate-ssh-keys
This command performs several actions at once: it provisions the VM, sets up the network interface, creates a public IP address, and generates SSH keys for secure access. The --generate-ssh-keys parameter is particularly useful because it automatically creates the private/public key pair in your .ssh directory, saving you the effort of manual key generation.
Callout: CLI vs. PowerShell vs. Portal Many users wonder when to use the CLI versus Azure PowerShell. The Azure CLI is cross-platform and uses JSON output, making it the preferred choice for developers and those working in Linux or macOS environments. Azure PowerShell is built on the .NET framework and is generally more comfortable for those coming from a Windows-heavy administrative background. Both tools use the same underlying REST APIs.
Working with JSON Output
One of the most powerful features of the Azure CLI is its ability to output data in JSON format. This allows you to pipe the output of one command into another tool, such as jq, which is a command-line JSON processor.
# Get the public IP of the VM we just created and save it to a variable
IP_ADDRESS=$(az vm list-ip-addresses \
--resource-group MyResourceGroup \
--name MyWebVM \
--query "[].virtualMachine.network.publicIpAddresses[0].ipAddress" \
--output tsv)
echo "The VM IP address is: $IP_ADDRESS"
The --query parameter uses JMESPath, a query language for JSON. By mastering JMESPath, you can extract exactly the information you need from the JSON response, filtering out the "noise" that often clutters the output of cloud management tools.
Best Practices for CLI Usage
As you move toward using the CLI for production environments, you must adopt professional habits to ensure security and maintainability.
1. Use Resource Groups Constantly
Always group your resources logically. If you are deploying a test environment, put all components—VMs, disks, networks, and storage—into a single resource group. This makes cleanup trivial: az group delete --name MyTestGroup --yes --no-wait.
2. Leverage --no-wait
Many CLI commands are "blocking," meaning the terminal will hang until the resource is fully provisioned. If you are running multiple deployments, use the --no-wait flag. This sends the request to Azure and immediately returns control to your terminal, allowing you to initiate other tasks in parallel.
3. Version Control Your Scripts
Never run complex deployments manually from your terminal history. Instead, write your commands into a bash script or a PowerShell file. Store these scripts in a Git repository. This provides a history of who changed what, allows you to peer-review your deployment logic, and enables you to redeploy the exact same infrastructure whenever necessary.
4. Implement Naming Conventions
Use consistent naming conventions for your resources (e.g., prod-web-vm-01). This makes it significantly easier to identify resources when listing them via the CLI. It also allows you to use wildcards and filtering effectively.
5. Secure Your Credentials
Never hardcode secrets like passwords or connection strings in your scripts. Use environment variables or a secret management tool like Azure Key Vault. If you are running in a CI/CD environment, use Managed Identities or Service Principals with limited RBAC permissions.
Common Pitfalls and Troubleshooting
Even experienced engineers run into issues with the CLI. Here are some of the most common mistakes and how to avoid them.
- The "Default" Trap: If you don't specify a resource group in every command, the CLI will often prompt you or default to a previously used group. This can lead to accidentally deploying resources in the wrong place. Always explicitly define your resource group.
- Ignoring Default Locations: If you don't specify a
--location(e.g.,eastus), the CLI may default to a region you didn't intend to use. Always be explicit about where your data and compute resources live to avoid latency and compliance issues. - Forgetting to Update: The Azure CLI is updated frequently. If you experience strange behavior or missing features, your local installation might be outdated. Run
az upgradeperiodically to ensure you are on the latest version. - Over-reliance on
list: When troubleshooting, users often runaz vm list. If you have hundreds of VMs, this output will be unreadable. Use the--queryfilter to limit the output to only the fields you care about (e.g.,--query "[].{Name:name, State:powerState}").
Warning: The
deleteCommand Theaz resource deleteoraz group deletecommands are destructive. Once a resource is deleted, recovery is often difficult or impossible without a backup. Always double-check the resource group and name before hitting enter. In production environments, consider using "Resource Locks" to prevent accidental deletion of critical infrastructure.
Advanced Automation: Integrating CLI into Pipelines
The ultimate goal of using the Azure CLI is to move beyond manual interaction and into the realm of automated operations. When you incorporate the CLI into a pipeline (like GitHub Actions, Azure DevOps, or Jenkins), you gain the ability to deploy infrastructure in a repeatable, documented manner.
The CI/CD Workflow
- Authentication: The pipeline runner authenticates using a Service Principal or Managed Identity.
- Environment Setup: The runner ensures the Azure CLI is installed and updated.
- Deployment: The pipeline executes your scripted CLI commands.
- Verification: The pipeline runs a "check" command (like
az vm get-instance-view) to confirm the resource is healthy. - Reporting: The pipeline outputs the result to the build log, providing an audit trail.
When writing scripts for pipelines, always use the --output json flag. This ensures the output is machine-readable, which is essential if you need to parse the results of a deployment to trigger subsequent tasks. For example, if you deploy a database, you might need to capture its connection string and inject it into your application's configuration file automatically.
Comparison Table: Azure CLI vs. Alternatives
| Feature | Azure CLI | Azure PowerShell | Azure Portal |
|---|---|---|---|
| Platform | Cross-platform | Windows-focused | Web-based |
| Primary User | Developers/DevOps | SysAdmins | Beginners/Explorers |
| Automation | Excellent (Scriptable) | Excellent (Scriptable) | None |
| Consistency | High | High | Low |
| Learning Curve | Moderate | Moderate | Low |
| Best For | CI/CD, Linux, Automation | Windows, Complex Mgmt | Visualizing, Learning |
Deep Dive: Managing Networking with CLI
Networking is often the most complex part of cloud infrastructure. With the CLI, you can define virtual networks (VNets), subnets, and network security groups (NSGs) with surgical precision.
Creating a Network Infrastructure
Instead of relying on the default network configurations, create your own:
# Create a VNet
az network vnet create \
--resource-group MyResourceGroup \
--name MyVNet \
--address-prefix 10.0.0.0/16
# Create a Subnet
az network vnet subnet create \
--resource-group MyResourceGroup \
--vnet-name MyVNet \
--name MySubnet \
--address-prefix 10.0.1.0/24
This modular approach allows you to build your network topology piece by piece. By scripting these commands, you ensure that your development, staging, and production environments are identical, which eliminates the "it worked in dev but not in prod" configuration drift that plagues many organizations.
Frequently Asked Questions (FAQ)
1. Can I use the Azure CLI from my web browser?
Yes. Azure provides the "Cloud Shell," which is a browser-based terminal accessible directly from the Azure Portal. It comes pre-installed with the Azure CLI, Git, and other useful tools. It is an excellent way to manage resources on the go without installing anything locally.
2. How do I get help for a specific command?
You don't need to go to the documentation website for everything. You can use the --help flag after any command group. For example, az vm --help will list all available subcommands for virtual machines. az vm create --help will show you every available parameter for the create command.
3. Is the Azure CLI free to use?
Yes, the Azure CLI is an open-source tool provided by Microsoft at no cost. You only pay for the Azure resources you create and manage using the tool.
4. Can I write custom extensions for the CLI?
Yes, the Azure CLI supports extensions. Extensions allow you to add new commands or functionality that isn't included in the core CLI package. You can list available extensions with az extension list-available and add them with az extension add.
5. How do I handle sensitive data in my scripts?
Never store passwords in plain text. Use Azure Key Vault to store secrets and retrieve them at runtime using the CLI. For example: az keyvault secret show --vault-name MyVault --name MySecret --query value -o tsv.
Security Considerations
Security is paramount in any cloud environment. When using the CLI, you must be aware of how your commands interact with Azure's security model.
- Role-Based Access Control (RBAC): Your CLI session is tied to your identity. If you are a Contributor on a subscription, you can delete resources. If you are a Reader, you can only view them. Always use the principle of least privilege.
- Service Principals: For automated scripts, never use your personal user account. Use a Service Principal—a dedicated identity for your application or script—and assign it the minimum necessary permissions.
- Conditional Access: If your organization uses Microsoft Entra ID (formerly Azure AD) Conditional Access policies, your CLI login will respect those policies (e.g., requiring Multi-Factor Authentication).
Callout: The Power of
az interactiveIf you are new to the CLI, try runningaz interactive. This launches an interactive shell that provides auto-completion, command descriptions, and real-time documentation. It is essentially a "guided" version of the CLI that makes it much easier to learn the syntax and discover available commands without constantly switching back to your browser.
Final Review: Key Takeaways
As you conclude this lesson, remember that the Azure CLI is a journey, not a destination. You will not learn every command overnight, and that is perfectly acceptable. The goal is to build a foundation that allows you to manage the cloud with confidence and efficiency.
- Efficiency Through Automation: The CLI transforms manual tasks into repeatable, auditable scripts. This is the foundation of modern DevOps and infrastructure-as-code.
- Consistency is King: By using the CLI, you ensure that every resource is deployed with the exact same configuration, reducing the risk of human error.
- Master the Query Engine: The
--queryparameter and JMESPath are your best friends. Learning to filter and format output will save you hours of manual data parsing. - Prioritize Security: Treat your CLI scripts as code. Use Service Principals, avoid hardcoded credentials, and always apply the principle of least privilege.
- Stay Up to Date: The cloud moves fast. Keep your CLI updated to benefit from the latest features, security patches, and performance improvements.
- Use the Right Tools: While the Portal is great for visualization, use the CLI for day-to-day operations and CI/CD integration.
- Embrace the Community: The Azure CLI is open-source. If you find a bug or think of a feature, you can contribute to the project on GitHub.
By moving from the Portal to the CLI, you are leveling up your career as a cloud professional. You are no longer just an operator of a web interface; you are an architect of cloud infrastructure. Start small by automating one task this week, and slowly build your library of scripts. Before you know it, you will be managing complex enterprise environments with nothing more than a terminal window and a well-structured script.
Continue the course
Enjoying the courses?
Everything stays free. Pro shows fewer ads, doubles your daily points limit so you progress twice as fast, and lets you read each lesson on one page.
- ✓ Fewer advertisements
- ✓ 2× daily points limit
- ✓ Distraction-free lessons