fbpx

Azure CLI is a powerful tool for managing Azure resources from the command line. It enables developers and system administrators to perform a wide range of tasks, from creating and managing resources to automating deployment and monitoring. In this article, we’ll explore Azure CLI in depth and cover the advanced concepts, tips, and best practices for using it effectively.


What is Azure CLI?

The Azure CLI is a command-line tool that provides a way to manage Azure resources from the terminal or command prompt. It is available for Windows, macOS, and Linux, and supports many Azure services and resource types.

With Azure CLI, you can perform a wide range of tasks, such as creating and managing resources, deploying applications, and monitoring resource usage. Azure CLI supports both interactive and script-based operation, allowing you to perform actions either through a terminal prompt or by executing a script.

Installing Azure CLI

Before you can start using Azure CLI, you need to install it on your local machine. Here’s how to install Azure CLI on different operating systems:

Windows

To install Azure CLI on Windows, follow these steps:

  1. Download the Azure CLI installer for Windows from the official Microsoft website.
  2. Run the installer and follow the prompts to install Azure CLI.
  3. Once the installation is complete, open a new terminal window and type az login to authenticate with your Azure account.

macOS

To install Azure CLI on macOS, follow these steps:

Open a terminal window and type the following command:

brew update && brew install azure-cli

Wait for the installation to complete, then type az login to authenticate with your Azure account.

Linux

To install Azure CLI on Linux, follow these steps:

Open a terminal window and type the following command to install the Azure CLI using a single command:

curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

Wait for the installation to complete, then type az login to authenticate with your Azure account.

Use Azure CLI in a Docker container

Here are the steps to install and run the Azure CLI using a Docker container:

Step 1: Install Docker

Install DockerDocker is required to run the Azure CLI in a container. If you don’t have Docker installed, follow the installation instructions for your operating system from the official Docker website.

Step 2: Pull the Azure CLI image

You can pull the official Azure CLI Docker image from the Docker Hub registry. Use the following command to pull the latest Azure CLI image:

docker pull mcr.microsoft.com/azure-cli

This command will download the latest Azure CLI image to your local machine.

Step 3: Run the Azure CLI container

Once you have pulled the Azure CLI image, you can run a container using the following command:

docker run -it mcr.microsoft.com/azure-cli

This command will start a new container and open an interactive terminal session where you can run Azure CLI commands.

Alternatively, you can also mount a local directory to the container to access files on your local machine. Use the following command to mount a local directory to the container:

docker run -it -v <local_path>:/mnt mcr.microsoft.com/azure-cli

Replace <local_path> with the absolute path of the directory on your local machine that you want to mount. This will mount the specified directory to the /mnt directory in the container.

Once you have successfully installed and started the Azure CLI using a Docker container, you can now run any Azure CLI commands inside the container just as you would on your local machine.

Step 4: Update Azure CLI Docker container

Over time, as you use the Azure CLI there will eventually be updates made to the Docker container. Docker makes it really simple to update to newer versions using the docker pull command.

Use the following command to update your local azure-cli Docker container image:

docker pull mcr.microsoft.com/azure-cli

Uninstall Azure CLI Docker image

If you need to uninstall, or remove, the Azure CLI Docker container image from. your machine, you can use the following command:

docker rmi mcr.microsoft.com/azure-cli

Azure CLI Basic Commands

Once you’ve installed Azure CLI, you can start using it to manage Azure resources. The first step is to authenticate with your Azure account using the az login command. This will open a web page where you can enter your Azure credentials and grant Azure CLI access to your resources.

Azure Login

Before you can use the Azure CLI, you need to log in to your Azure account. To do this, open the command prompt or Terminal app and type the following command:

az login

This will prompt you to open a web page and enter the code displayed in the command prompt. Once you have successfully authenticated, you can start using the Azure CLI.

Azure CLI Help

After you’ve logged in, you can start exploring the available Azure CLI commands. To view a list of available commands, type az in the terminal. You can also get help on a specific command by typing az [command] --help.

The following screenshot shows the help output for the Azure CLI group commands for managing Azure Resource Groups:

Get Started with Azure CLI infrastructure as code scripting 3
Azure CLI help output form “group” commands

Managing Azure Resources with Azure CLI

Azure CLI provides a wide range of commands for managing Azure resources. Here are some of the most commonly used commands for managing Azure resources:

Creating a Resource Group

To create a new resource group, use the az group create command:

# Create Resource Group command format
az group create --name <resource-group> --location <azure-region>

# Example with Resource Group name and Azure location set
az group create --name "myResourceGroup" --location eastus

This command creates a new resource group named MyResourceGroup in the eastus location.

Creating a Virtual Machine

To create a new virtual machine, use the az vm create command:

az vm create --resource-group myResourceGroup --name myVM --image UbuntuLTS --admin-username azureuser --generate-ssh-keys

This will create a new virtual machine named myVM in the myResourceGroup resource group, using the UbuntuLTS image. The --admin-username and --generate-ssh-keys options are used to create a new user account and generate SSH keys for authentication.

Creating a Storage Account

To create a storage account using the Azure CLI, use the following command:

az storage account create --name mystorageaccount --location eastus --resource-group myResourceGroup --sku Standard_LRS

This will create a new storage account named mystorageaccount in the myResourceGroup resource group, using the Standard_LRS SKU.

Advanced Azure CLI Concepts

In addition to the basic commands covered in the previous section, the Azure CLI also offers more advanced features that can help you streamline your workflow and achieve more complex tasks. Here are some advanced Azure CLI concepts to help you get the most out of the tool:

Azure Resource Manager templates

Azure Resource Manager templates are a powerful way to manage your resources and deploy complex infrastructure to Azure. You can use Azure CLI to create, validate, and deploy Resource Manager templates, making it easier to manage your infrastructure as code.

To create a Resource Manager template using Azure CLI, you can use the az group deployment create command. This command creates a deployment of a template into a resource group, using a JSON file that describes the infrastructure.

az group deployment create -g <resource-group> --template-uri <arm-template-uri> --parameters @myparameters.json

Azure Command Modules

Azure CLI comes with many command modules that provide additional functionality beyond the core set of commands. These modules can be installed using the az extension add command. Some of the most popular modules include:

  • Azure DevOps: Provides commands for managing Azure DevOps resources.
  • Azure Kubernetes Service: Provides commands for managing Kubernetes (k8s) clusters in Azure.
  • Azure IoT: Provides commands for managing Internet of Things (IoT) resources in Azure.
  • Azure Batch: Provides commands for managing Batch processing in Azure.

To install a module, use the following command syntax: az extension add --name <module-name>. For example, to install the Azure Kubernetes Service module, you would run az extension add --name aks.

If you are unsure what Azure CLI extensions are currently installed, you can run the following command to list the currently installed extensions:

az extension list --output table

The following command can be used to list the available Azure CLI extensions. This helps identify the extension name needed to install the extension you’re looking for.

az extension list-available --output table

To install the Azure DevOps extension, you can run the following command:

az extension add --name azure-devops

Querying Data with Azure CLI

Azure CLI provides a query language called the JMESPath query language, which allows you to extract specific data from the output of Azure CLI commands. This can be particularly useful when working with complex output, such as the output of commands that return multiple objects.

The syntax for using JMESPath queries is to include the --query parameter with a query expression enclosed in single quotes. For example, to extract the name of a virtual machine, you can use the following command:

az vm show --name <vm-name> --resource-group <resource-group-name> --query name

Azure CLI Output Formats

By default, Azure CLI outputs data in a human-readable format. However, you can change the output format to suit your needs.

The --output parameter allows you to specify the output format, with several options available. For example, to output data in JSON format, you can use the following command:

az group list --output json

Other output formats include table, tsv, yaml, and json. To see a list of available formats, run az --help-formats.

In addition to using the --output parameter with the Azure CLI to help make the Azure CLI output more readable, you can combine it with the grep command on Linux to more easily find what you’re searching for. For example, to find Azure resources with “blog” in the name more easily, you can use grep in the following command:

az resource list --output table | grep "blog"
Get Started with Azure CLI infrastructure as code scripting 4
Azure CLI resource list combined with grep command

Interactive Mode

Azure CLI also provides an interactive mode that allows you to enter commands without specifying the command and parameter names. Instead, you can navigate a menu-based system that prompts you for the necessary information.

To enter interactive mode, simply run the az interactive command. This will launch a prompt that allows you to enter Azure CLI commands in an interactive way. This can be particularly useful for beginners who are not yet familiar with the command syntax.

Using Azure CLI in CI/CD Pipelines

The Azure CLI can be very useful when it comes to deploying and managing cloud resources in a CI/CD pipeline. This could be a CI/CD pipeline using Azure DevOps, GitHub Actions, or some other CI/CD tool.

There are several ways to use Azure CLI in CI/CD pipelines, including using pre-built tasks in popular CI/CD platforms, such as Azure DevOps, Jenkins, or GitHub Actions. You can also use Azure CLI in your own custom scripts or third-party plugins.

Here are the steps to use Azure CLI in a CI/CD pipeline:

Step 1: Install the Azure CLI

To use Azure CLI in a CI/CD pipeline, you must first install it on the build agent or server where the pipeline will run. You can use the following command to install the latest version of Azure CLI on a Linux build agent:

curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

Step 2: Authenticate with Azure

To deploy resources to Azure, you must authenticate with an Azure subscription. There are several ways to authenticate, such as using a service principal or a managed identity. For CI/CD pipelines, the recommended method is to use a service principal.

You can create a service principal using the Azure CLI with the following command:

az ad sp create-for-rbac --name <SERVICE_PRINCIPAL_NAME> --role contributor \
                        --scopes /subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP_NAME>

This command will create a service principal with the contributor role assigned to the specified resource group. It will also return the credentials (client ID and secret) that you need to use in the pipeline.

Once the Azure service principal has been created, then use the following az login command to authenticate Azure CLI scripts within the CI/CD pipeline:

az login --service-principal -u <app-id> -p <password-or-cert> --tenant <tenant>

The --tenant parameter can be set to either the .onmicrosoft.com domain for your Azure Active Directory (Azure AD) tenant or the Azure AD directory id.

Step 3: Use Azure CLI in the CI/CD Pipeline

Once you have installed the Azure CLI and authenticated with Azure, you can use it in your pipeline scripts to deploy resources to Azure. Here is an example of how to use the Azure CLI to deploy an Azure Web App in a Linux-based Azure App Service:

az webapp create --resource-group <RESOURCE_GROUP_NAME> --plan <APP_SERVICE_PLAN_NAME> \
                 --name <WEB_APP_NAME> --runtime "NODE|12-lts" --deployment-container-image-name <DOCKER_IMAGE_NAME>

This command will create an Azure Web App in the specified resource group and Azure App Service plan, using a specified Docker image.

Step 4: Secure you pipeline

When using Azure CLI in a pipeline, it is important to secure your pipeline and protect your credentials. You should use pipeline variables to store your service principal credentials, and avoid hardcoding them in the pipeline script. You should also restrict access to the pipeline and limit who can modify or execute it.

By using Azure CLI in a CI/CD pipeline, you can automate the deployment of cloud resources to Azure and simplify the process of managing cloud infrastructure.

Troubleshooting Common Issues with Azure CLI

Although the Azure CLI is a powerful tool for managing resources in Azure, sometimes things can go wrong. Let’s look at some common issues that you may encounter while using the Azure CLI and how to troubleshoot them.

Azure CLI Authentication Issues

The most common issue with the Azure CLI is authentication. If you are having issues authenticating with Azure, first verify that you have the correct credentials for your subscription. You can use the following command to check if you are authenticated:

az account show

This command will show the details of the currently authenticated Azure account. If you are not authenticated, use the following command to authenticate:

az login

This command will prompt you to enter your Azure credentials and authenticate with Azure.

Resource Group or Resource Not Found Error

If you are having issues locating a resource group or resource, make sure that you have the correct resource group or resource name. You can use the following command to list all resource groups in your subscription:

az group list

This command will list all resource groups in your subscription. You can use the following command to list all resources in a specific resource group:

az resource list -g <RESOURCE_GROUP_NAME>

This command will list all resources in the specified resource group.

Incorrect Syntax Error

If you are having issues with Azure CLI syntax, make sure that you are using the correct syntax for the command. You can use the following command to get help with a specific command:

az <COMMAND_NAME> --help

This command will show the usage and options for the specified command.

Network Issues

If you are having issues with network connectivity, first verify that you have a working internet connection. You can use the following command to test your network connectivity:

az network ping --destination <DESTINATION_IP_OR_HOSTNAME>

This command will test your network connectivity to the specified IP address or hostname.

Azure Service Issues

If you are having issues with an Azure service, first check the Azure service health status. You can use the following command to check the Azure service health status:

az account list-locations --query '[].{Location:name}' --out table

This command will list all Azure locations and their health status.

By following these troubleshooting steps, you can quickly identify and resolve common issues with the Azure CLI. If you are still having issues, check the Azure CLI documentation or seek assistance from the Azure support team.

Automating Azure CLI Commands using Azure Automation

Azure Automation is a service in Azure that allows you to automate tasks and processes using runbooks. You can use Azure Automation to automate your Azure CLI commands, which can save you time and increase productivity.

  1. Create an Azure Automation Account
    The first step to automating Azure CLI commands using Azure Automation is to create an Azure Automation account. You can create an Azure Automation account using the Azure portal. Once you have created an Azure Automation account, you can start creating runbooks.
  2. Create a runbook
    A runbook is a set of instructions that you want Azure Automation to perform. To create a runbook, go to your Azure Automation account, select “Runbooks” from the menu, and then select “Add a runbook”. You can then create a new runbook or import an existing one.
  3. Azure Azure CLI commands to the runbook
    Once you have created a runbook, you can add Azure CLI commands to it. You can use the “Azure PowerShell” or “Azure CLI” modules to add Azure CLI commands to your runbook. You can use the same Azure CLI commands that you use in the Azure CLI.
  4. Schedule the runbook
    You can schedule the runbook to run at a specific time or on a recurring basis. You can also trigger the runbook manually. To schedule the runbook, go to the “Schedules” tab in the runbook and add a new schedule. You can then select the time and frequency of the schedule.
  5. Monitor the runbook
    Once you have created and scheduled the runbook, you can monitor it to ensure that it is running correctly. You can view the runbook status and output in the Azure Automation portal.

By using Azure Automation to automate your Azure CLI commands, you can save time and increase productivity. You can use Azure Automation to perform tasks such as starting and stopping virtual machines, deploying resources, and monitoring Azure resources.

Conclusion

Azure CLI is a powerful command-line tool that allows you to manage your Azure resources from your terminal. In this article, we have covered various topics related to Azure CLI, starting from the basics of Azure CLI, installation and setup, to advanced concepts such as resource management, role-based access control, and automation.

This article also covered getting started with using Azure CLI in CI/CD pipelines, common issues that you may face while working with Azure CLI, and troubleshooting steps to resolve those issues, and the basic steps necessary to automate Azure CLI commands using Azure Automation.

Using Azure CLI, you can streamline your work, automate repetitive tasks, and manage your Azure resources more efficiently. Azure CLI is a valuable tool for developers, system administrators, DevOps Engineers, and Site Reliability Engineers (SREs) who want to manage their Azure resources in a programmatic way.

I hope that this article has helped you better understand the basics of using the Azure CLI.

Microsoft MVP

Chris Pietschmann is a Microsoft MVP, HashiCorp Ambassador, and Microsoft Certified Trainer (MCT) with 20+ years of experience designing and building Cloud & Enterprise systems. He has worked with companies of all sizes from startups to large enterprises. He has a passion for technology and sharing what he learns with others to help enable them to learn faster and be more productive.
HashiCorp Ambassador Microsoft Certified Trainer (MCT) Microsoft Certified: Azure Solutions Architect