I need an Azure CLI script file for the below requirements.
1. Verifying the Azure Subscription
2. Validating the VM's Tag Values
3. VM Status (Running / Deallocated)
4. if deallocated, run the VM.
I need an Azure CLI script file for the below requirements.
1. Verifying the Azure Subscription
2. Validating the VM's Tag Values
3. VM Status (Running / Deallocated)
4. if deallocated, run the VM.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Ali BenchaabanRank #925 · 2.2K reputationPosted Jan 4, 2024, 12:16 PM EST
Hello,
az account show --output table tagValue=$(az vm show --resource-group --name --query tags --output tsv) [ -z "$tagValue" ] && echo "VM tags are missing or empty." || echo "VM tags are set as: $tagValue" vmStatus=$(az vm show --resource-group --name --query powerState --output tsv) if [ "$vmStatus" == "VM deallocated" ]; then az vm start --resource-group --name elif [ "$vmStatus" == "VM running" ]; then echo "VM is running." else echo "Unable to determine VM status." fi echo "Script execution completed."Regards,
Naimish MakwanaRank #324 · 7.7K reputationPosted Jan 5, 2024, 12:18 AM EST
Here is a basic Azure CLI script that should help you with your requirements. Please replace
,,, andwith your actual values.#!/bin/bash # 1. Verifying the Azure Subscription az account set --subscription # 2. Validating the VM's Tag Values vm_tags=$(az vm show --resource-group --name --query tags) echo "VM's Tags: $vm_tags" # Check if a specific tag exists if [[ $vm_tags == *""* ]]; then echo "Tag exists." else echo "Tag does not exist." fi # 3. Checking VM Status (Running / Deallocated) vm_status=$(az vm get-instance-view --name --resource-group --query instanceView.statuses[1] --output tsv) echo "VM Status: $vm_status" # 4. If deallocated, start the VM if [[ $vm_status == *"deallocated"* ]]; then echo "Starting VM..." az vm start --resource-group --name else echo "VM is already running." fiThis script assumes that you’re already logged in to Azure CLI. If not, you’ll need to log in using
az loginbefore running this script. Also, please note that this is a basic script, and you might need to modify it according to your specific needs or handle errors and edge cases as necessary. Always test scripts in a safe environment before using them in production.Remember to replace
,,, andwith your actual values.is your Azure Subscription ID,is the name of the resource group where your VM is located,is the name of your VM, andis the name of the tag you want to validate.Thanks