☁️
CTHFM: Azure
  • Welcome
  • Getting Started
    • Account Setup
      • Account Creation Instructions
  • Azure Fundamentals
    • Azure Fundamentals Overview
      • Azure Documentation
      • Azure Entra
      • Azure Hierarchy
      • Identities
      • Azure Entra Roles
      • Azure RBAC
      • Azure Licensing Overview
        • Azure Entra ID Premium Licenses Comparison
      • Azure Shared Responsibility Model
      • Azure Frameworks
      • Azure Security Services
      • Conditional Access Policies
        • How Conditional Access Policies Work
        • Benefits of Conditional Access
        • Best Practices for Conditional Access
        • Conditions for Conditional Access
        • Conditional Access Controls
        • Sign-In Risk and Identity Protection
        • Conditional Access Session Control
        • Name Locations IP Location
      • Azure Quotas
      • Azure Tokens
        • Access Tokens
        • ID Tokens
        • Refresh Tokens
          • Invalidate Refresh Tokens
        • Primary Refresh Tokens
        • Continuous Access Evaluation (CAE)
        • Token Protection: Conditional Access (Public Preview)
  • Azure CLI
    • Introduction to Azure CLI
    • Installing Azure CLI
    • CLI Commands
    • Resource Group Management
    • Creating and Managing Resources with Azure CLI
    • Managing IAM
    • Azure CLI Automation
    • Monitoring and Troubleshooting in Azure CLI
    • Azure CLI Overview
      • Azure CLI: Linux
      • Azure CLI: Windows
      • Azure CLI: MacOS
  • KQL
    • KQL Overview
      • KQL Introduction
      • Data Types
      • Quick Reference
      • Render
      • Basic Queries
  • Powershell
    • PowerShell for Azure
      • Powershell Documentation
      • Powershell Basics
      • Understanding Powershell Variables
      • Understanding Cmdlets
      • Powershell Console & ISE
      • Powershell: Entra Module
        • Module Reference & Getting Started
      • Powershell: Azure Module
        • Installation Instructions
        • Powershell Azure CLI: Windows
        • Powershell Azure CLI: Linux
        • Powershell Azure CLI: MacOS
        • Example Azure Cmdlets
  • Bicep
    • Bicep File Structure
    • Variable Types
  • Azure Logging References
    • Logging
      • Log Retention Strategies
      • Azure Log Types
      • Azure Activity Logs
        • Administrative Event Schema
        • Service Health Notification Schema
        • Resource Health
        • Alert Category
        • Autoscale
        • Security
        • Recommendation
        • Policy
      • Entra ID Logging
        • Identity Based Logs
          • Audit Logs
          • Sign-In Logs
            • AADNonInteractiveUserSignInLogs
            • AADManagedIdentitySignInLogs
            • AADServicePrincipalSignInLogs
            • First Party Sign-In Activity
          • Provisioning Logs (AADProvisioningLogs)
          • Microsoft Graph Activity
          • Identity Protection
            • Risk Detections
            • AADRiskyServicePrincipals
            • AADRiskyUsers
            • AADUserRiskEvents
            • AADServicePrincipalRiskEvents
        • Additional Entra ID Logs
      • Azure Key Vault
        • Azure Key Vault Logging Overview
      • Network Watcher
        • RBAC Permissions
        • Flow Log Types
          • NSG Flow Log Schema
          • VNET Flow Log Schema
        • Enabling Logs
          • NSG Flow Logs
          • VNET Flow Logs
        • Packet Capture
          • Packet Capture: VM
          • Packet Capture: Scale Sets
      • Compute Resources
        • Azure Monitor Agent
        • VM Insights
          • VM Insights Tables
      • Storage Accounts
        • Storage Account Logging
          • File
            • Enable StorageFileLogs
            • StorageFileLogs
          • Blob
            • Enable Blob Logging
            • StorageBlobLogs
          • Queue
            • Enable Queue Logging
            • StorageQueueLogs Table
          • Table
            • Enable Table Logging
            • StorageTableLogs Table
      • Azure App Service
        • Log Types
        • Enabling Logging
      • Azure Monitor
        • Resource Logs
          • Resource Log Top Level Documentation
        • Log Analytics Workspace
          • Setup
        • Workbooks
        • Dashboards
        • Alerts
        • Azure Monitor Documentation
      • Defender for Cloud
      • Intune
      • Sysmon
      • Purview Audit Log Schema
      • Kubernetes Audit Log (AKS)
  • Threat Hunting
    • Threat Hunting in Azure
      • Threat Hunting Introduction
      • Threat Hunting Process
        • Hypothesis Generation
        • Investigation
        • Identification
        • Resolution & Follow Up
      • Pyramid of Pain
      • Azure Threat Hunting Ideas
      • Hands On Threat Hunting Examples
      • OSINT Feeds
  • Sigma
    • Sigma Rule Structure
  • Microsoft Defender TI
    • Microsoft Defender Threat Intelligence
      • Data Sets
      • Reputational Scoring
      • Analyst Insights
      • Microsoft Defender TI: Copilot Integration
  • MITRE Att&ck
    • MITRE Att&ck
      • MITRE Att&ck Concepts
      • MITRE Data Sources
      • MITRE Att&ck Mitigations
      • MITRE Att&ck: Azure
        • MITRE Att&CK: Azure Security Control Mapping
  • Microsoft Resources
    • Microsoft Incident Response Ninja Hub
    • Microsoft Defender XDR Ninja Hub
  • Azure Threat Research Matrix (ATRM)
  • Security Research & Resources
    • Azure Goat
    • Azure Security Research
      • Azure Related CVEs
  • Defender XDR
    • Defender XDR Overview
    • Defender XDR Licensing
    • Defender XDR Default Retention
    • Defender XDR Advanced Hunting Table Schemas
    • Automated Response Requirements
    • Supported Response Actions
  • Azure Sentinel
    • Sentinel Overview
    • Azure Sentinel Deployments
    • Supported Data
    • Workbook, Playbook, Notebook Comparison
    • Sentinel Workbooks
    • Entities
    • User and Entity Behavior Analytics
    • Anomaly Detection
    • Mult-Stage Attack Detection
    • Sentinel: Az CLI
  • Microsoft Defender
    • Microsoft Defender for Cloud References
    • Defender for Cloud: Az CLI
  • Azure Policy
    • Azure Policy
    • Azure Policy Components
    • Azure Policy Rules
    • Scope Azure Policy
    • Policy Assignments
    • Policy Effect
    • Initiative Definition
    • Policy Parameters
    • Remediation Task Structure
    • Use Cases for Azure Policy
    • Azure Policy: Az CLI
  • Intune
    • Intune Overview
    • Intune Licensing
    • Intune API Permission Scopes
    • Intune Sample Script Resources
  • Intune Logging
    • Configure Logging
    • Logging Schema References
    • Intune Queries and Resources
  • Windows Host Security
    • Windows System Architecture and OS Fundamentals
    • SysInternals
    • Basic vs Advanced Security Auditing
    • Sysmon
  • Adversary Emulation
    • AzureHound
    • AADInternals
      • Install
    • RoadTools
      • Install
    • Oh365UserFinder
    • GraphRunner
  • Incident Response
    • Incident Response
      • Azure IR Program Development Cheat Sheet
      • Azure IR Playbooks (MS Guidance)
      • Ransomware (MS Guidance)
  • Automation
    • Automation Overview
    • Logic Apps
      • How Logic Apps Work
      • Logic App Types
      • Triggers
      • Connectors
      • Conditional Logic and Control Flow
      • APIs in Logic Apps
      • Handling Large Workflows with Stateful Logic Apps
      • External Service Integration
      • Securing, Managing, and Scaling Azure Logic Apps
      • Logic Apps: Az CLI
  • Packet Analysis
    • Wireshark Cheatsheet
    • TShark Cheatsheet
    • TCPDUMP Cheatsheet
    • Protocol Analysis Basics
    • HTTP Response Code Cheatsheet
    • RFC Protocol Mappings
    • PCAP Acquisition
  • Detection Lab
    • Detection Lab Introduction
    • Account Creation Instructions
    • Enable MFA Within Azure Tenant
    • Create an Azure Admin With Cloud Shell
    • Setup and Install Instructions
  • VSCode and Code Setup
  • Deploying Code
  • Enabling Logs for Log Analytics Workspace
  • Logging Into Windows VM
  • Verifying Logs in Log Analytics Workspace
  • Creating Detections: Azure Monitor
  • Cost Management: Billing Alarms
Powered by GitBook
On this page
  • 7.1 Why Automate Azure CLI?
  • πŸ› οΈ 7.2 Basic Structure of an Azure CLI Script
  • 🧩 7.3 Using Environment Variables
  • πŸ“¦ 7.4 Passing Parameters into a Script
  • ⚑ 7.5 Best Practices for Azure CLI Automation
  • ✨ 7.6 Real-World Use Case Example
  • πŸ“ Module 7 Summary
  1. Azure CLI

Azure CLI Automation

7.1 Why Automate Azure CLI?

Automation helps you:

Benefit
Why It’s Important

Save time

Avoid manually repeating the same steps

Reduce errors

Scripts are consistent and repeatable

Enable DevOps workflows

Easily integrate into CI/CD pipelines

Improve scalability

Create hundreds of resources with one script

βœ… Scripting Azure CLI = Power and Speed.


πŸ› οΈ 7.2 Basic Structure of an Azure CLI Script

At its core, an Azure CLI script is just a series of CLI commands placed in a file.


πŸ–₯️ Example (Bash Script)

bashCopyEdit#!/bin/bash

# Variables
RESOURCE_GROUP="myScriptRG"
LOCATION="eastus"

# Create a Resource Group
az group create --name $RESOURCE_GROUP --location $LOCATION

# Create a Storage Account
az storage account create \
  --name mystorageaccount$RANDOM \
  --resource-group $RESOURCE_GROUP \
  --location $LOCATION \
  --sku Standard_LRS

# List the Storage Accounts
az storage account list --resource-group $RESOURCE_GROUP --output table

βœ… Save this as create_resources.sh and run:

bashCopyEditbash create_resources.sh

πŸ–₯️ Example (PowerShell Script)

powershellCopyEdit# Variables
$ResourceGroup = "myScriptRG"
$Location = "eastus"

# Create a Resource Group
az group create --name $ResourceGroup --location $Location

# Create a Storage Account
$Random = Get-Random
az storage account create `
  --name "mystorageaccount$Random" `
  --resource-group $ResourceGroup `
  --location $Location `
  --sku Standard_LRS

# List Storage Accounts
az storage account list --resource-group $ResourceGroup --output table

βœ… Save this as create_resources.ps1 and run:

powershellCopyEdit.\create_resources.ps1

🧩 7.3 Using Environment Variables

You can inject dynamic values into your scripts using environment variables.


Setting Environment Variables (Bash)

bashCopyEditexport RESOURCE_GROUP=myResourceGroup
export LOCATION=eastus

Then reference them in your script:

bashCopyEditaz group create --name $RESOURCE_GROUP --location $LOCATION

Setting Environment Variables (PowerShell)

powershellCopyEdit$env:RESOURCE_GROUP = "myResourceGroup"
$env:LOCATION = "eastus"

And use:

powershellCopyEditaz group create --name $env:RESOURCE_GROUP --location $env:LOCATION

βœ… Using environment variables makes your scripts portable and easier to maintain.


πŸ“¦ 7.4 Passing Parameters into a Script

Scripts can accept input at runtime.


Bash Example with Parameters

bashCopyEdit#!/bin/bash

RESOURCE_GROUP=$1
LOCATION=$2

az group create --name $RESOURCE_GROUP --location $LOCATION

Run the script:

bashCopyEditbash create_rg.sh myDynamicRG eastus

βœ… $1, $2, etc. are positional parameters.


PowerShell Example with Parameters

powershellCopyEditparam(
  [string]$ResourceGroup,
  [string]$Location
)

az group create --name $ResourceGroup --location $Location

Run the script:

powershellCopyEdit.\create_rg.ps1 -ResourceGroup myDynamicRG -Location eastus

βœ… Parameterization = More reusable scripts.


⚑ 7.5 Best Practices for Azure CLI Automation

Best Practice
Why It Matters

Use variables and parameters

Make scripts reusable and configurable

Check if resources exist before creating

Avoid duplicate deployments

Add comments to your scripts

Make your scripts readable and maintainable

Always validate input

Prevent unexpected errors

Handle errors gracefully

Use try-catch (PowerShell) or exit codes (Bash)

Secure sensitive data

Never hard-code passwords in scripts


✨ 7.6 Real-World Use Case Example

Deploy a VM Automatically

Bash Script Example:

bashCopyEdit#!/bin/bash

RESOURCE_GROUP="autoRG"
VM_NAME="autoVM"
LOCATION="eastus"

# Create Resource Group
az group create --name $RESOURCE_GROUP --location $LOCATION

# Deploy VM
az vm create \
  --resource-group $RESOURCE_GROUP \
  --name $VM_NAME \
  --image UbuntuLTS \
  --admin-username azureuser \
  --generate-ssh-keys

# Output public IP
az vm list-ip-addresses --resource-group $RESOURCE_GROUP --name $VM_NAME --output table

βœ… In just a few seconds, you’ve automated your infrastructure!


πŸ“ Module 7 Summary

Topic
Key Points

Why automate?

Save time, reduce errors, scale easily

Structure of a script

Series of Azure CLI commands

Using environment variables

Makes scripts dynamic and maintainable

Passing parameters

Makes scripts flexible

Best practices

Secure coding, validation, reusability

Last updated 2 months ago