AZURE CLI - REFERENCE

 

Table of Contents

  1. Installation & Setup

  2. Authentication & Login

  3. Subscription Management

  4. Resource Group Operations

  5. User & Access Management

  6. Virtual Machine Management

  7. Networking & Security

  8. Storage Management

  9. Monitoring & Troubleshooting

  10. Best Practices & Cleanup


1. Installation & Setup

Windows 11 Azure CLI Installation

bash
# Download and install Azure CLI from:
# https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows

# Verify installation
az --version
# What: Checks Azure CLI version and confirms successful installation
# Why: Essential first step to ensure CLI is properly installed

Initial Setup Verification

bash
# Check if Azure CLI is ready to use
az --help
# What: Displays main help menu with available commands
# Why: Confirms basic functionality and shows command structure

2. Authentication & Login

Basic Login

bash
# Interactive browser login
az login
# What: Opens default browser for Azure authentication
# Why: Establishes secure session with Azure; required for all operations

# Login with specific browser
az login --use-device-code
# What: Provides device code for authentication at https://microsoft.com/devicelogin
# Why: Useful when working on remote systems or without browser access

Multi-Account Management

bash
# List all logged-in accounts
az account list --output table
# What: Shows all Azure accounts currently authenticated
# Why: Helpful when managing multiple accounts or tenants

# Logout from current session
az logout
# What: Ends current Azure CLI session
# Why: Security best practice; clears cached credentials

# Login to specific tenant
az login --tenant "your-tenant-id"
# What: Authenticates to specific Azure AD tenant
# Why: Necessary when user has access to multiple directories

3. Subscription Management

Subscription Discovery & Selection

bash
# List all accessible subscriptions
az account list --output table
# What: Displays all subscriptions available to current user
# Why: First step to identify which subscription to work with

# Set default subscription context
az account set --subscription "Pay-As-You-Go"
# What: Sets specified subscription as default for all subsequent commands
# Why: Avoids needing to specify subscription in every command

# Show current subscription details
az account show --output table
# What: Displays currently active subscription information
# Why: Verifies subscription context is set correctly

# Get subscription ID only
az account show --query id --output tsv
# What: Extracts just the subscription ID
# Why: Useful for scripts and automation

Subscription Context Verification Script

bash
#!/bin/bash
# Complete subscription context setup and verification

echo "=== Azure Subscription Setup ==="

# Step 1: Login if not already authenticated
az account show > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "Not logged in. Starting authentication..."
    az login
fi

# Step 2: List available subscriptions
echo "Available subscriptions:"
az account list --query "[].{Name:name, State:state, IsDefault:isDefault}" --output table

# Step 3: Set specific subscription (replace with your subscription name)
TARGET_SUB="Pay-As-You-Go"
echo "Setting subscription to: $TARGET_SUB"
az account set --subscription "$TARGET_SUB"

# Step 4: Verify context
echo "Current context:"
az account show --query "{Subscription:name, ID:id, State:state}" --output table

# Step 5: Test access
echo "Testing resource access..."
az group list --output table

4. Resource Group Operations

Basic Resource Group Management

bash
# Create a new resource group
az group create --name "rg-training" --location "eastus" --tags "Environment=Training" "Project=AzureCLI"
# What: Creates a new resource group in specified region
# Why: Resource groups are containers for Azure resources; required for most services

# List all resource groups
az group list --output table
# What: Displays all resource groups in current subscription
# Why: Overview of existing resource containers

# Show specific resource group details
az group show --name "rg-training" --output table
# What: Displays detailed information about specific resource group
# Why: Verify resource group properties and location

# Delete resource group (careful!)
az group delete --name "rg-training" --yes --no-wait
# What: Permanently deletes resource group and all contained resources
# Why: Cleanup unused resources; --yes avoids confirmation, --no-wait returns immediately

Resource Group Lifecycle Script

bash
#!/bin/bash
# Complete resource group lifecycle management

echo "=== Resource Group Lifecycle Management ==="

# Variables
RG_NAME="rg-training-$(date +%Y%m%d)"
LOCATION="eastus"

# Create resource group
echo "Creating resource group: $RG_NAME"
az group create --name $RG_NAME --location $LOCATION --tags "CreatedBy=CLI" "Temporary=true"

# Verify creation
echo "Resource group details:"
az group show --name $RG_NAME --query "{Name:name, Location:location, ProvisioningState:properties.provisioningState}"

# List resources in group (will be empty initially)
echo "Resources in group:"
az resource list --resource-group $RG_NAME --output table

# Export template (infrastructure as code)
echo "Exporting template..."
az group export --name $RG_NAME > exported_template.json

# Cleanup (comment out to keep resources)
echo "Deleting resource group..."
az group delete --name $RG_NAME --yes --no-wait
echo "Resource group deletion initiated"

5. User & Access Management

Azure AD User Management

bash
# List all users in directory
az ad user list --query "[].{DisplayName:displayName, UserPrincipalName:userPrincipalName, ObjectId:id}" --output table
# What: Displays all users in current Azure AD tenant
# Why: Overview of directory users and their properties

# Get specific user details
az ad user show --id "trainee3@systemsfaithinfotech.onmicrosoft.com"
# What: Shows detailed information about specific user
# Why: Verify user existence and properties before role assignment

Role Assignment & Permissions

bash
# Grant Contributor role at subscription level
az role assignment create --assignee "trainee3@systemsfaithinfotech.onmicrosoft.com" --role "Contributor" --scope "/subscriptions/2db12407-4535-42ee-b91d-3dfadd7a0455"
# What: Grants full resource management permissions to user at subscription level
# Why: Allows user to create, manage, and delete Azure resources

# Grant Reader role at resource group level
az role assignment create --assignee "user@company.com" --role "Reader" --resource-group "rg-training"
# What: Grants read-only access to specific resource group
# Why: Limited permissions for monitoring or auditing purposes

# List current role assignments
az role assignment list --subscription "2db12407-4535-42ee-b91d-3dfadd7a0455" --include-inherited --output table
# What: Shows all role assignments in current subscription
# Why: Audit who has what access permissions

# Remove role assignment
az role assignment delete --assignee "user@company.com" --role "Contributor" --scope "/subscriptions/2db12407-4535-42ee-b91d-3dfadd7a0455"
# What: Removes previously granted permissions
# Why: Security cleanup when access is no longer needed

Complete User Onboarding Script

bash
#!/bin/bash
# Complete user onboarding with role assignments

echo "=== User Onboarding Process ==="

# Variables
SUBSCRIPTION_ID="2db12407-4535-42ee-b91d-3dfadd7a0455"
SUBSCRIPTION_NAME="Pay-As-You-Go"
NEW_USER="trainee3@systemsfaithinfotech.onmicrosoft.com"
ROLE="Contributor"

# Set subscription context
echo "Setting subscription context: $SUBSCRIPTION_NAME"
az account set --subscription "$SUBSCRIPTION_NAME"

# Verify user exists
echo "Verifying user: $NEW_USER"
USER_EXISTS=$(az ad user show --id "$NEW_USER" --query "id" -o tsv 2>/dev/null)

if [ -z "$USER_EXISTS" ]; then
    echo "❌ User not found: $NEW_USER"
    echo "Please ensure the user exists in Azure AD"
    exit 1
fi

# Assign role
echo "Assigning $ROLE role to $NEW_USER"
az role assignment create \
    --assignee "$NEW_USER" \
    --role "$ROLE" \
    --scope "/subscriptions/$SUBSCRIPTION_ID"

# Verify assignment
echo "Role assignment verification:"
az role assignment list \
    --assignee "$NEW_USER" \
    --subscription "$SUBSCRIPTION_ID" \
    --query "[].{Principal:principalName, Role:roleDefinitionName, Scope:scope}" \
    --output table

echo "✅ User onboarding completed successfully"
echo "Instructions for $NEW_USER:"
echo "1. Run: az login"
echo "2. Run: az account set --subscription '$SUBSCRIPTION_NAME'"
echo "3. Run: az group list --output table"

6. Virtual Machine Management

VM Creation & Management

bash
# Create Ubuntu Linux VM
az vm create \
    --resource-group "rg-training" \
    --name "linux-vm" \
    --image "Ubuntu2204" \
    --admin-username "azureuser" \
    --generate-ssh-keys \
    --size "Standard_B1s" \
    --public-ip-sku "Basic"
# What: Creates Ubuntu Linux virtual machine with SSH authentication
# Why: --generate-ssh-keys creates secure keys for password-less access

# Create Windows VM
az vm create \
    --resource-group "rg-training" \
    --name "windows-vm" \
    --image "Win2022AzureEditionCore" \
    --admin-username "azureuser" \
    --admin-password "SecurePassword123!" \
    --size "Standard_B2s"
# What: Creates Windows Server virtual machine
# Why: Windows VMs require password authentication (more complex than SSH keys)

# List all VMs in resource group
az vm list --resource-group "rg-training" --output table
# What: Displays all virtual machines in specified resource group
# Why: Overview of compute resources

# Get VM public IP address
az vm show \
    --name "linux-vm" \
    --resource-group "rg-training" \
    --show-details \
    --query "publicIps" \
    --output tsv
# What: Extracts public IP address of specific VM
# Why: Required for SSH/RDP connections to the VM

VM Lifecycle Management

bash
# Stop and deallocate VM (stops billing)
az vm deallocate --name "linux-vm" --resource-group "rg-training"
# What: Stops VM and releases compute resources
# Why: Cost saving measure when VM not in use

# Start VM
az vm start --name "linux-vm" --resource-group "rg-training"
# What: Starts previously stopped VM
# Why: Resume operations; billing restarts

# Restart running VM
az vm restart --name "linux-vm" --resource-group "rg-training"
# What: Reboots running virtual machine
# Why: Apply configuration changes or troubleshoot issues

# Resize VM (must be stopped first)
az vm resize \
    --resource-group "rg-training" \
    --name "linux-vm" \
    --size "Standard_B2s"
# What: Changes VM size (CPU, memory specifications)
# Why: Scale resources based on performance requirements

# Delete VM (keeps disks by default)
az vm delete --name "linux-vm" --resource-group "rg-training" --yes
# What: Removes virtual machine but preserves attached disks
# Why: Cleanup while keeping data for future use

7. Networking & Security

Network Security Groups & Port Management

bash
# Open HTTP port for web traffic
az vm open-port \
    --resource-group "rg-training" \
    --name "linux-vm" \
    --port 80
# What: Adds inbound rule to NSG allowing HTTP traffic
# Why: Essential for web servers to receive HTTP requests

# Open RDP port for Windows VM
az vm open-port \
    --resource-group "rg-training" \
    --name "windows-vm" \
    --port 3389
# What: Adds inbound rule to NSG allowing RDP connections
# Why: Required for Remote Desktop access to Windows VMs

# List NSG rules
az network nsg rule list \
    --nsg-name "linux-vmNSG" \
    --resource-group "rg-training" \
    --output table
# What: Displays all network security group rules
# Why: Audit security rules and troubleshoot connectivity issues

Virtual Network Management

bash
# Create virtual network
az network vnet create \
    --resource-group "rg-training" \
    --name "vnet-training" \
    --address-prefix "10.0.0.0/16" \
    --subnet-name "default" \
    --subnet-prefix "10.0.1.0/24"
# What: Creates virtual network with specified IP address space
# Why: Provides private network infrastructure for Azure resources

8. Storage Management

Storage Account Operations

bash
# Create storage account
az storage account create \
    --resource-group "rg-training" \
    --name "sttraining123" \
    --sku "Standard_LRS" \
    --kind "StorageV2" \
    --location "eastus"
# What: Creates general-purpose v2 storage account
# Why: Storage accounts are required for blobs, files, queues, and tables

# List storage account keys
az storage account keys list \
    --resource-group "rg-training" \
    --account-name "sttraining123" \
    --output table
# What: Displays access keys for storage account
# Why: Keys are required for applications to connect to storage services

# Create file share
az storage share create \
    --name "training-files" \
    --account-name "sttraining123"
# What: Creates SMB file share
# Why: Provides network file shares accessible from Windows/Linux systems

9. Monitoring & Troubleshooting

Resource Monitoring

bash
# Check VM performance metrics
az monitor metrics list \
    --resource $(az vm show -g "rg-training" -n "linux-vm" --query id -o tsv) \
    --metric "Percentage CPU" \
    --output table
# What: Displays CPU utilization metrics for specific VM
# Why: Monitor performance and identify resource bottlenecks

# View VM boot diagnostics
az vm boot-diagnostics get-boot-log \
    --name "linux-vm" \
    --resource-group "rg-training"
# What: Retrieves boot log information from VM
# Why: Troubleshoot startup issues and boot failures

# Check activity logs
az monitor activity-log list \
    --resource-group "rg-training" \
    --max-events 5 \
    --output table
# What: Displays recent activity events for resource group
# Why: Audit trail of who did what and when

Troubleshooting Common Issues

bash
# Check resource health
az resource show \
    --name "linux-vm" \
    --resource-group "rg-training" \
    --resource-type "Microsoft.Compute/virtualMachines"
# What: Displays detailed resource properties and status
# Why: Verify resource configuration and identify issues

# Test resource group existence
az group exists --name "rg-training"
# What: Returns boolean indicating if resource group exists
# Why: Quick check before attempting operations on resource group

10. Best Practices & Cleanup

Resource Tagging & Organization

bash
# Add tags to resource group
az group update \
    --name "rg-training" \
    --set tags.Environment=Development tags.Project=Training tags.CreatedBy=$USER
# What: Adds metadata tags to resource group
# Why: Organize resources for billing, management, and automation

# List resources with tags
az resource list \
    --resource-group "rg-training" \
    --query "[].{Name:name, Type:type, Environment:tags.Environment}" \
    --output table
# What: Displays resources with their tags
# Why: Overview of resource organization and categorization

Cleanup Script

bash
#!/bin/bash
# Safe cleanup of training resources

echo "=== Azure Resource Cleanup ==="

# List all resource groups
echo "Current resource groups:"
az group list --query "[].{Name:name, Location:location}" --output table

# Confirm deletion
read -p "Enter resource group name to delete (or 'skip' to cancel): " RG_NAME

if [ "$RG_NAME" != "skip" ]; then
    echo "Deleting resource group: $RG_NAME"
    
    # Double confirmation for safety
    read -p "Are you sure? This will delete ALL resources in $RG_NAME. Type 'yes' to confirm: " CONFIRM
    
    if [ "$CONFIRM" == "yes" ]; then
        az group delete --name "$RG_NAME" --yes --no-wait
        echo "✅ Deletion initiated for resource group: $RG_NAME"
    else
        echo "❌ Deletion cancelled"
    fi
else
    echo "Cleanup cancelled"
fi

Export Configuration for Documentation

bash
# Export resource group as ARM template
az group export --name "rg-training" > training_template.json
# What: Generates Azure Resource Manager template from existing resources
# Why: Infrastructure as code; reproducible deployments

# List all resources for inventory
az resource list \
    --resource-group "rg-training" \
    --query "[].{Name:name, Type:type, Location:location, SKU:sku.name}" \
    --output table
# What: Comprehensive inventory of all resources
# Why: Documentation and cost management

Quick Reference Cheat Sheet

bash
# 🚀 ESSENTIAL COMMANDS FOR BEGINNERS

# Authentication
az login
az account list --output table
az account set --subscription "Your-Subscription-Name"

# Resource Groups
az group create --name "rg-demo" --location "eastus"
az group list --output table
az group delete --name "rg-demo" --yes

# Virtual Machines
az vm create --resource-group "rg-demo" --name "demo-vm" --image "Ubuntu2204" --generate-ssh-keys
az vm list --output table
az vm deallocate --name "demo-vm" --resource-group "rg-demo"

# User Management
az ad user list --output table
az role assignment create --assignee "user@company.com" --role "Contributor" --scope "/subscriptions/your-sub-id"

# Cleanup
az group list --query "[].name" --output tsv | ForEach-Object { az group delete --name $_ --yes --no-wait }


Comments

Popular posts from this blog

Interview Tips: Dot NET Framework vs Net CORE

FREE Webinar: Run Your Own Independent DeepSeek LLM

Delegates and Events