Issue
I'm trying to get the vm that's deallocated and containing a specific tag
offline=`az vm list --show-details --query "[?tags.\"$REVIVE_TAG\"=='true' && powerState=='VM deallocated'].{Result: join(' ', [name, location, resourceGroup])}" -o tsv
for line in "$offline"; do
echo "$line"
instance_name=`echo "$line" | head -n1 | awk '{print $1}'`
instance_zone=`echo "$line" | head -n1 | awk '{print $2}'`
instance_group=`echo "$line" | head -n1 | awk '{print $3}'`
echo "Rebooting '$instance_name' in zone '$instance_zone' in resource group '$instance_group'..."
az vm start -n "$instance_name" -g "$instance_group"
done
offline looks like
debug-training-script northeurope LORENZO-PLAYGROUND
debug-training-script-2 northeurope LORENZO-PLAYGROUND
but the output of the loop looks like
debug-training-script northeurope LORENZO-PLAYGROUND
debug-training-script-2 northeurope LORENZO-PLAYGROUND
Rebooting 'debug-training-script' in zone 'northeurope' in resource group 'LORENZO-PLAYGROUND'...
instead of
debug-training-script northeurope LORENZO-PLAYGROUND
Rebooting 'debug-training-script' in zone 'northeurope' in resource group 'LORENZO-PLAYGROUND'...
debug-training-script-2 northeurope LORENZO-PLAYGROUND
Rebooting 'debug-training-script-2' in zone 'northeurope' in resource group 'LORENZO-PLAYGROUND'...
Solution
The double quotes tell for
to loop over a single value. Don't read lines with for
anyway. You are probably looking for something like
az vm list --show-details \
--query "[?tags.\"$REVIVE_TAG\"=='true' && powerState=='VM deallocated'].{Result: join(' ', [name, location, resourceGroup])}" -o tsv |
while IFS=$'\t' read -r name zone group; do
echo "Rebooting '$name' in zone '$zone' in resource group '$group'..."
az vm start -n "$name" -g "$group"
done
which also helpfully avoids the antipattern of capturing the entire output into a variable which you use exactly once.
(I abbreviated the variable names for my own convenience; if this is part of a larger script, you might want to add back the instance_
prefix to their names. I also had to guess where the missing closing quote for the --query
option should go.)
Going forward, probably try https://shellcheck.net/ before asking for human assistance, and read When to wrap quotes around a shell variable as well as perhaps How to read variables from file, with multiple variables per line?
Answered By - tripleee Answer Checked By - Willingham (WPSolving Volunteer)