How to Interact with Azure CLI from a Batch Script
Cloud automation is vital for maintaining modern IT infrastructure, and the Azure Command-Line Interface (Azure CLI) is Microsoft's primary tool for managing Azure resources. Integrating az commands into a Batch script enables powerful automation tasks like starting/stopping Virtual Machines, querying resource groups, or managing storage accounts.
In this guide, we will demonstrate how to authenticate and execute Azure CLI commands directly from a Batch script.
Setup: Installing the Azure CLI
First, ensure the Azure CLI is installed on your Windows machine and available in the system PATH. You can download it directly from Microsoft or install it via winget:
winget install -e --id Microsoft.AzureCLI
Method 1: The Interactive Login (Service Principals)
For an automated script, interactive logins (where a browser window pops up) will pause execution indefinitely. You must use a Service Principal (an identity created in Azure AD specifically for applications) to authenticate silently.
Getting a Service Principal
Run this manually once to create a service principal and obtain the credentials:
az ad sp create-for-rbac --name MyBatchApp
Save the appId, password, and tenant values.
Implementation Script
@echo off
setlocal enabledelayedexpansion
:: 1. Define Authentication Variables
:: NEVER hardcode these in production; pass them as secure arguments
:: or store them securely in the environment.
set "appId=YOUR_APP_ID"
set "password=YOUR_PASSWORD"
set "tenantId=YOUR_TENANT_ID"
set "subscriptionId=YOUR_SUBSCRIPTION_ID"
:: 2. Verify Azure CLI is installed
where az >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Azure CLI is not installed or not in PATH.
pause
exit /b 1
)
echo Authenticating to Azure...
:: 3. Silent Login via Service Principal
call az login --service-principal -u "%appId%" -p "%password%" --tenant "%tenantId%" >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Failed to authenticate to Azure.
pause
exit /b 1
)
:: 4. Set the active subscription (optional if SP only has one)
call az account set --subscription "%subscriptionId%"
if !errorlevel! neq 0 (
echo [ERROR] Failed to set subscription "%subscriptionId%".
pause
exit /b 1
)
echo Successfully connected.
echo.
:: 5. Example AZ Command: List all Virtual Machines
echo Generating VM list...
:: Using -o table formats the JSON output neatly for the console
call az vm list -o table
if !errorlevel! neq 0 (
echo [ERROR] Failed to list VMs.
pause
exit /b 1
)
:: 6. Example AZ Command: Start a specific VM
set "resourceGroup=DevEnvironment"
set "vmName=Web-Test-01"
echo.
echo Starting %vmName%...
call az vm start -g "%resourceGroup%" -n "%vmName%"
if !errorlevel! neq 0 (
echo [ERROR] Failed to start VM "%vmName%".
pause
exit /b 1
)
echo.
echo [SUCCESS] Process complete.
endlocal
pause
exit /b 0
Parsing Azure Output into Batch Variables
Often, you need a specific value from Azure (like a Public IP address) to use later in your script. The Azure CLI defaults to JSON output, which you can format to TSV (Tab Separated Values) for easy parsing with FOR /F.
@echo off
setlocal enabledelayedexpansion
:: Assuming already authenticated
set "resourceGroup=Prod-Network"
set "vmName=Web-Frontend-01"
:: Get the Public IP Address formatted as TSV, without headers
set "publicIp="
for /f "tokens=*" %%A in ('call az vm show -g "%resourceGroup%" -n "%vmName%" --show-details --query "publicIps" -o tsv 2^>nul') do set "publicIp=%%A"
if not defined publicIp (
echo [ERROR] Failed to retrieve the public IP for "%vmName%".
pause
exit /b 1
)
echo The public IP address of %vmName% is: !publicIp!
endlocal
pause
exit /b 0
Why Integrate Azure CLI with Batch?
- Cost Management: A script that automatically shuts down all development VMs at 7:00 PM and restarts them at 8:00 AM using Windows Task Scheduler.
- Resource Auditing: Extracting a list of all storage accounts and passing the list into a secondary process that verifies compliance standards.
- Deployment Pipelines: After compiling code locally, appending a process that uploads the binaries directly to an Azure Storage Blob.
Important Considerations
- Variable Security: Never store the Service Principal
passwordinside the batch file. Instead, set it as an Environment Variable beforehand, or prompt the user for it interactively when the script launches. - Using
call: Becauseaz.cmdis itself a batch script in Windows, invoking it inside your own script without thecallcommand will terminate your script immediately after theazcommand finishes. Always prefix Azure commands withcall. - JSON Queries: The
--queryparameter uses JMESPath syntax to filter JSON output efficiently. Mastering it is essential for extracting specific values without writing complex string manipulation loops in Batch.
Conclusion
Interfacing with the Azure CLI empowers simple Windows scripts to manage global cloud infrastructure. By using Service Principals for silent authentication and formatting output strictly to TSV, you bridge the gap between local system automation and enterprise-grade Azure resource management.