Knowledge Overview

Prerequisites

  • Basic Linux terminal navigation and command execution
  • Understanding of command-line interfaces and shell environments
  • Familiarity with package managers (apt, dnf, yum)
  • Basic cloud computing concepts and terminology
  • Knowledge of SSH keys and authentication methods

Time Investment

14 minutes reading time
28-42 minutes hands-on practice

Guide Content

What is Azure Cli on Linux?

Azure CLI Linux integration enables system administrators and DevOps engineers to manage Microsoft Azure resources directly from their Linux terminals. The Azure CLI provides a unified command-line interface for deploying, configuring, and monitoring Azure services without requiring the Azure portal web interface.

Table of Contents

  1. How to Install Azure CLI on Linux Distributions
  2. What is Azure CLI and Why Use It
  3. How to Configure Azure CLI Authentication
  4. How to Manage Azure Virtual Machines from Linux
  5. How to Work with Azure Storage from Linux Terminal
  6. How to Deploy and Monitor Azure Resources
  7. How to Automate Azure Tasks with Shell Scripts
  8. FAQ
  9. Troubleshooting
  10. Additional Resources

How to Install Azure CLI on Linux Distributions

Installing Azure CLI Linux requires different approaches depending on your distribution. Here are proven installation methods for major Linux distributions.

Installing Azure CLI on Ubuntu/Debian

The most straightforward method for Ubuntu and Debian uses Microsoft's official repository:

Bash
# Update package index
sudo apt-get update

# Install prerequisites
sudo apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release

# Download and install Microsoft signing key
curl -sL https://packages.microsoft.com/keys/microsoft.asc | \
    gpg --dearmor | \
    sudo tee /etc/apt/keyrings/microsoft.gpg > /dev/null

# Set proper permissions
sudo chmod go+r /etc/apt/keyrings/microsoft.gpg

# Add Azure CLI repository
AZ_DIST=$(lsb_release -cs)
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/microsoft.gpg] https://packages.microsoft.com/repos/azure-cli/ $AZ_DIST main" | \
    sudo tee /etc/apt/sources.list.d/azure-cli.list

# Update package index and install Azure CLI
sudo apt-get update
sudo apt-get install azure-cli

Installing Azure CLI on CentOS/RHEL/Fedora

For Red Hat-based distributions, use the RPM repository:

Bash
# Import Microsoft signing key
sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc

# Add Azure CLI repository
sudo sh -c 'echo -e "[azure-cli]
name=Azure CLI
baseurl=https://packages.microsoft.com/yumrepos/azure-cli
enabled=1
gpgcheck=1
gpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/azure-cli.repo'

# Install Azure CLI
sudo dnf install azure-cli

Universal Installation Script

For other Linux distributions or custom installations:

Bash
# Download and execute installation script
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

Verify Installation

Confirm Azure CLI installation and check version:

Bash
# Check Azure CLI version
az version

# View available commands
az --help

# Verify installation directory
which az

What is Azure CLI and Why Use It

Azure CLI provides a cross-platform command-line interface for managing Azure resources directly from Linux terminals, offering several advantages over graphical interfaces.

Key Features of Azure CLI Linux Integration

Unified Command Structure: Azure CLI follows consistent syntax patterns across all Azure services, making it easier to learn and use efficiently.

Cross-Platform Compatibility: The same commands work identically across Ubuntu, CentOS, Debian, and other Linux distributions.

Scriptable Automation: Every Azure CLI command can be incorporated into shell scripts, Python scripts, or CI/CD pipelines for automated infrastructure management.

JSON Output Format: All commands return structured JSON output, making it easy to parse results and chain commands together.

Benefits for Linux System Administrators

Native Terminal Integration: Manage Azure resources without leaving your Linux terminal environment, maintaining familiar workflow patterns.

Infrastructure as Code: Combine Azure CLI with tools like Terraform or Ansible for comprehensive infrastructure automation.

Batch Operations: Perform bulk operations on multiple resources using shell scripting and Azure CLI commands.

Development Workflow Integration: Seamlessly integrate Azure resource management into Linux-based development and deployment workflows.

How to Configure Azure CLI Authentication

Proper authentication configuration enables secure access to your Azure subscription resources from Linux systems.

Interactive Login Method

The interactive login method opens a web browser for authentication:

Bash
# Initiate interactive login
az login

# Login with specific tenant
az login --tenant YOUR_TENANT_ID

# Login to specific Azure cloud (useful for government or China clouds)
az login --cloud AzureGovernment

Service Principal Authentication

For automated scripts and CI/CD pipelines, use service principal authentication:

Bash
# Create service principal
az ad sp create-for-rbac --name "MyAppServicePrincipal" \
    --role contributor \
    --scopes /subscriptions/YOUR_SUBSCRIPTION_ID

# Login with service principal
az login --service-principal \
    --username YOUR_APP_ID \
    --password YOUR_PASSWORD \
    --tenant YOUR_TENANT_ID

Managed Identity Authentication

When running on Azure VMs, use managed identity:

Bash
# Login with system-assigned managed identity
az login --identity

# Login with user-assigned managed identity
az login --identity --username YOUR_CLIENT_ID

Configuration Management

View and manage Azure CLI configuration:

Bash
# Show current account information
az account show

# List available subscriptions
az account list --output table

# Set default subscription
az account set --subscription "YOUR_SUBSCRIPTION_NAME"

# Show current configuration
az configure --list-defaults

# Set default resource group and location
az configure --defaults group=myResourceGroup location=eastus

How to Manage Azure Virtual Machines from Linux

Azure CLI enables comprehensive virtual machine lifecycle management directly from Linux terminals.

Creating Azure Virtual Machines

Create and configure VMs with single commands:

Bash
# Create resource group
az group create --name myResourceGroup --location eastus

# Create virtual network
az network vnet create \
    --resource-group myResourceGroup \
    --name myVNet \
    --address-prefix 10.0.0.0/16 \
    --subnet-name mySubnet \
    --subnet-prefix 10.0.1.0/24

# Create public IP
az network public-ip create \
    --resource-group myResourceGroup \
    --name myPublicIP \
    --allocation-method Dynamic

# Create Network Security Group and rule
az network nsg create \
    --resource-group myResourceGroup \
    --name myNetworkSecurityGroup

az network nsg rule create \
    --resource-group myResourceGroup \
    --nsg-name myNetworkSecurityGroup \
    --name myNetworkSecurityGroupRuleSSH \
    --protocol tcp \
    --priority 1000 \
    --destination-port-range 22 \
    --access allow

# Create virtual NIC
az network nic create \
    --resource-group myResourceGroup \
    --name myNic \
    --vnet-name myVNet \
    --subnet mySubnet \
    --public-ip-address myPublicIP \
    --network-security-group myNetworkSecurityGroup

# Create virtual machine
az vm create \
    --resource-group myResourceGroup \
    --name myVM \
    --nics myNic \
    --image UbuntuLTS \
    --size Standard_B2s \
    --admin-username azureuser \
    --generate-ssh-keys

Managing Virtual Machine States

Control VM power states and configurations:

Bash
# Start virtual machine
az vm start --resource-group myResourceGroup --name myVM

# Stop virtual machine (deallocated)
az vm deallocate --resource-group myResourceGroup --name myVM

# Restart virtual machine
az vm restart --resource-group myResourceGroup --name myVM

# Show VM status
az vm show --resource-group myResourceGroup --name myVM --show-details

# List all VMs in subscription
az vm list --output table

# Resize virtual machine
az vm resize --resource-group myResourceGroup --name myVM --size Standard_B4ms

VM Monitoring and Diagnostics

Monitor performance and troubleshoot issues:

Bash
# Enable boot diagnostics
az vm boot-diagnostics enable \
    --resource-group myResourceGroup \
    --name myVM

# Get boot diagnostics data
az vm boot-diagnostics get-boot-log \
    --resource-group myResourceGroup \
    --name myVM

# Get VM sizes available in region
az vm list-sizes --location eastus --output table

# Show VM usage statistics
az vm list-usage --location eastus --output table

How to Work with Azure Storage from Linux Terminal

Azure CLI provides comprehensive storage management capabilities for blobs, files, queues, and tables.

Creating and Managing Storage Accounts

Set up Azure storage infrastructure:

Bash
# Create storage account
az storage account create \
    --resource-group myResourceGroup \
    --name mystorageaccount \
    --location eastus \
    --sku Standard_LRS

# Get storage account keys
az storage account keys list \
    --resource-group myResourceGroup \
    --account-name mystorageaccount

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

# Set container public access
az storage container set-permission \
    --account-name mystorageaccount \
    --name mycontainer \
    --public-access blob

Blob Storage Operations

Upload, download, and manage blob storage:

Bash
# Upload file to blob storage
az storage blob upload \
    --account-name mystorageaccount \
    --container-name mycontainer \
    --name myblob.txt \
    --file /path/to/local/file.txt \
    --auth-mode login

# Download blob from storage
az storage blob download \
    --account-name mystorageaccount \
    --container-name mycontainer \
    --name myblob.txt \
    --file /path/to/download/file.txt \
    --auth-mode login

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

# Copy blob between containers
az storage blob copy start \
    --source-account-name mystorageaccount \
    --source-container mycontainer \
    --source-blob myblob.txt \
    --destination-account-name mystorageaccount \
    --destination-container targetcontainer \
    --destination-blob copied-blob.txt

File Share Management

Create and manage Azure File shares:

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

# Upload file to share
az storage file upload \
    --account-name mystorageaccount \
    --share-name myfileshare \
    --source /path/to/local/file.txt \
    --path file.txt \
    --auth-mode login

# Mount Azure File share on Linux
sudo mkdir /mnt/myfileshare
sudo mount -t cifs //mystorageaccount.file.core.windows.net/myfileshare /mnt/myfileshare \
    -o vers=3.0,credentials=/etc/samba/credentials,dir_mode=0777,file_mode=0777

How to Deploy and Monitor Azure Resources

Azure CLI enables infrastructure deployment and comprehensive monitoring from Linux systems.

Resource Group Management

Organize and manage Azure resources efficiently:

Bash
# Create resource group with tags
az group create \
    --name myResourceGroup \
    --location eastus \
    --tags Environment=Production Project=WebApp

# List resource groups
az group list --output table

# Show resource group details
az group show --name myResourceGroup

# Delete resource group and all resources
az group delete --name myResourceGroup --yes --no-wait

# Export resource group template
az group export \
    --name myResourceGroup \
    --output-format json > myResourceGroup-template.json

Azure Resource Manager (ARM) Template Deployment

Deploy infrastructure using ARM templates:

Bash
# Deploy ARM template
az deployment group create \
    --resource-group myResourceGroup \
    --template-file azuredeploy.json \
    --parameters azuredeploy.parameters.json

# Validate ARM template before deployment
az deployment group validate \
    --resource-group myResourceGroup \
    --template-file azuredeploy.json \
    --parameters azuredeploy.parameters.json

# Monitor deployment progress
az deployment group show \
    --resource-group myResourceGroup \
    --name myDeployment

# List deployments
az deployment group list --resource-group myResourceGroup --output table

Resource Monitoring and Metrics

Monitor Azure resource performance and health:

Bash
# Get VM metrics
az monitor metrics list \
    --resource /subscriptions/YOUR_SUBSCRIPTION/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM \
    --metric "Percentage CPU" \
    --start-time 2025-01-01T00:00:00Z \
    --end-time 2025-01-01T23:59:59Z

# Create metric alert
az monitor metrics alert create \
    --name "High CPU Alert" \
    --resource-group myResourceGroup \
    --scopes /subscriptions/YOUR_SUBSCRIPTION/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM \
    --condition "avg Percentage CPU > 80" \
    --description "Alert when CPU exceeds 80%"

# List available metrics for resource
az monitor metrics list-definitions \
    --resource /subscriptions/YOUR_SUBSCRIPTION/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM

How to Automate Azure Tasks with Shell Scripts

Combine Azure CLI commands with shell scripting for powerful automation workflows.

Automated VM Deployment Script

Create reusable VM deployment automation:

Bash
#!/bin/bash
# azure-vm-deploy.sh

set -e

# Configuration variables
RESOURCE_GROUP="automated-vms"
LOCATION="eastus"
VM_SIZE="Standard_B2s"
IMAGE="UbuntuLTS"
ADMIN_USERNAME="azureuser"

# Function to create VM with error handling
create_vm() {
    local vm_name=$1
    local vm_number=$2
    
    echo "Creating VM: $vm_name"
    
    # Create VM
    az vm create \
        --resource-group $RESOURCE_GROUP \
        --name $vm_name \
        --image $IMAGE \
        --size $VM_SIZE \
        --admin-username $ADMIN_USERNAME \
        --generate-ssh-keys \
        --public-ip-sku Standard \
        --tags Environment=Development Number=$vm_number \
        --output none
    
    echo "VM $vm_name created successfully"
}

# Create resource group
echo "Creating resource group: $RESOURCE_GROUP"
az group create --name $RESOURCE_GROUP --location $LOCATION --output none

# Create multiple VMs
for i in {1..3}; do
    vm_name="vm-web-0$i"
    create_vm $vm_name $i
done

echo "All VMs created successfully"

# List created VMs
echo "Created VMs:"
az vm list --resource-group $RESOURCE_GROUP --output table --query "[].{Name:name,Status:powerState,Size:hardwareProfile.vmSize}"

Storage Backup Automation

Automate storage operations and backups:

Bash
#!/bin/bash
# azure-storage-backup.sh

STORAGE_ACCOUNT="backupstorage$(date +%s)"
RESOURCE_GROUP="backup-rg"
CONTAINER_NAME="dailybackups"
BACKUP_DATE=$(date +%Y-%m-%d)

# Create storage account for backups
az storage account create \
    --resource-group $RESOURCE_GROUP \
    --name $STORAGE_ACCOUNT \
    --location eastus \
    --sku Standard_LRS \
    --output none

# Get storage account key
ACCOUNT_KEY=$(az storage account keys list \
    --resource-group $RESOURCE_GROUP \
    --account-name $STORAGE_ACCOUNT \
    --query "[0].value" --output tsv)

# Create backup container
az storage container create \
    --account-name $STORAGE_ACCOUNT \
    --account-key $ACCOUNT_KEY \
    --name $CONTAINER_NAME \
    --output none

# Function to backup files
backup_files() {
    local source_dir=$1
    local backup_name="backup-$BACKUP_DATE.tar.gz"
    
    # Create compressed backup
    tar -czf /tmp/$backup_name -C $source_dir .
    
    # Upload to Azure storage
    az storage blob upload \
        --account-name $STORAGE_ACCOUNT \
        --account-key $ACCOUNT_KEY \
        --container-name $CONTAINER_NAME \
        --file /tmp/$backup_name \
        --name $backup_name \
        --output none
    
    # Clean up local backup file
    rm /tmp/$backup_name
    
    echo "Backup completed: $backup_name"
}

# Backup important directories
backup_files "/home/user/documents"
backup_files "/etc"

echo "All backups completed successfully"

Resource Monitoring Script

Automate resource monitoring and alerting:

Bash
#!/bin/bash
# azure-monitor.sh

RESOURCE_GROUP="monitoring-rg"
SUBSCRIPTION_ID=$(az account show --query id --output tsv)

# Function to check VM status
check_vm_status() {
    local vm_name=$1
    
    vm_status=$(az vm show \
        --resource-group $RESOURCE_GROUP \
        --name $vm_name \
        --show-details \
        --query powerState \
        --output tsv)
    
    if [[ $vm_status != "VM running" ]]; then
        echo "WARNING: VM $vm_name is not running (Status: $vm_status)"
        # Send alert or restart VM
        az vm start --resource-group $RESOURCE_GROUP --name $vm_name --no-wait
    else
        echo "VM $vm_name is running normally"
    fi
}

# Function to check storage usage
check_storage_usage() {
    local storage_account=$1
    
    usage=$(az storage account show-usage \
        --query value \
        --output tsv)
    
    if [[ $usage -gt 80 ]]; then
        echo "WARNING: Storage usage is at ${usage}%"
    else
        echo "Storage usage: ${usage}%"
    fi
}

# Get list of VMs and check status
vm_list=$(az vm list --resource-group $RESOURCE_GROUP --query "[].name" --output tsv)

for vm in $vm_list; do
    check_vm_status $vm
done

echo "Monitoring check completed"

FAQ

How do I install Azure CLI on older Linux distributions?

For distributions not supported by the official repositories, use the universal installation script: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash. This script works with most Linux distributions that have basic dependencies available.

Can I use Azure CLI without a graphical interface?

Absolutely. Azure CLI is designed specifically for command-line environments and doesn't require any graphical components. All authentication can be handled through device code flow or service principals, making it perfect for headless servers.

How do I manage multiple Azure subscriptions?

Use az account list to view available subscriptions and az account set --subscription "subscription-name" to switch between them. You can also set default subscriptions in your configuration with az configure --defaults.

What's the difference between Azure CLI and Azure PowerShell?

Azure CLI uses bash-style syntax and is cross-platform, while Azure PowerShell uses PowerShell syntax. Both offer the same functionality, but Azure CLI integrates better with Linux workflows and shell scripting.

How do I automate Azure CLI authentication in scripts?

For automation, use service principal authentication: create a service principal with az ad sp create-for-rbac, then use az login --service-principal with the credentials in your scripts.

Can I export Azure CLI commands as ARM templates?

Yes, many Azure CLI commands support the --export-template parameter, or you can use az group export to export entire resource groups as ARM templates for reusability.

How do I handle Azure CLI rate limits?

Azure CLI automatically handles rate limiting with exponential backoff. For high-volume operations, implement delays between commands or use --no-wait parameter for asynchronous operations.

Is Azure CLI output suitable for scripting?

Yes, Azure CLI returns structured JSON by default, making it perfect for parsing with tools like jq. Use --output table for human-readable format or --output tsv for tab-separated values.

Troubleshooting

Azure CLI Installation Fails on Ubuntu/Debian

If you encounter GPG key errors during installation:

Bash
# Remove existing keys and repositories
sudo rm -f /etc/apt/keyrings/microsoft.gpg
sudo rm -f /etc/apt/sources.list.d/azure-cli.list

# Clean apt cache
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/*

# Reinstall with proper key handling
curl -sL https://packages.microsoft.com/keys/microsoft.asc | \
    gpg --dearmor | \
    sudo tee /etc/apt/keyrings/microsoft.gpg > /dev/null

# Verify key installation
gpg --list-packets /etc/apt/keyrings/microsoft.gpg

Authentication Issues with Service Principals

When service principal login fails:

Bash
# Verify service principal exists
az ad sp show --id YOUR_APP_ID

# Check role assignments
az role assignment list --assignee YOUR_APP_ID --output table

# Test with explicit parameters
az login --service-principal \
    --username YOUR_APP_ID \
    --password YOUR_PASSWORD \
    --tenant YOUR_TENANT_ID \
    --debug

Command Execution Timeouts

For operations that timeout:

Bash
# Increase timeout for long-running operations
az configure --defaults timeout=1800

# Use asynchronous operations
az vm create ... --no-wait

# Check operation status
az vm show --name myVM --resource-group myRG --query provisioningState

JSON Parsing Errors

When working with JSON output:

Bash
# Validate JSON output
az vm list --output json | python -m json.tool

# Use specific queries to avoid parsing issues
az vm list --query "[?powerState=='VM running'].name" --output tsv

# Handle special characters in queries
az vm list --query "[?contains(name, 'web')]"

Network Connectivity Issues

If Azure CLI cannot reach Azure endpoints:

Bash
# Test connectivity to Azure endpoints
curl -I https://management.azure.com/
nslookup management.azure.com

# Configure proxy if needed
export HTTPS_PROXY=http://proxy.company.com:8080
az login

# Use specific cloud endpoints
az cloud set --name AzureGovernment
az login

Performance Issues with Large Operations

For slow Azure CLI operations:

Bash
# Enable parallel processing
az configure --defaults parallel=true

# Use batch operations where available
az vm list --output none  # Suppress output for faster execution

# Filter results at source
az vm list --resource-group myRG --query "[?powerState=='VM running']"

Extension Installation Problems

When Azure CLI extensions fail to install:

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

# Install extension with specific version
az extension add --name azure-devops --version 0.25.0

# Update extension index
az extension update --name azure-devops

# Remove and reinstall problematic extensions
az extension remove --name azure-devops
az extension add --name azure-devops

Additional Resources

Official Documentation

Community Resources

Related LinuxTips.pro Articles

Advanced Topics


This article is part of the LinuxTips.pro Linux Mastery Series. Master Azure cloud integration on Linux with comprehensive command-line tools and automation strategies.

Prerequisites: Basic Linux terminal knowledge, Azure account with active subscription, familiarity with command-line interfaces

Learning Outcomes: Install and configure Azure CLI on Linux, manage Azure resources from terminal, automate cloud operations with shell scripts, integrate Azure services into Linux workflows

Estimated Reading Time: 45 minutes Hands-on Practice Time: 2-3 hours