我试图并行启动/关闭虚拟机,同时还要检查电源状态以确保其正在运行/已取消分配。当前,我的脚本在每个VM上等待完成操作,然后再移至下一个VM。我希望能够启动/停止,检查电源状态,移至下一个电源状态,再次检查电源状态并保持循环运行直到满足所有条件。
#!/usr/bin/env bash
VM_IDS="$(az resource list --tag Nonessential=Yes --query "[?type=='Microsoft.Compute/virtualMachines'].{VM:name, RG:resourceGroup}" -o tsv >> vm.txt)"
cat vm.txt
if [[ "${OPTIONS}" == "stop" ]]; then
while read VM RG; do
timeout 10s az vm deallocate -g $RG -n $VM --no-wait
#PS=$(az vm show -g $RG -n $VM --show-details --query powerState -o tsv | tr -d '"')
echo "$VM is shutting down & deallocating..."
while [[ `az vm show -g $RG -n $VM --show-details --query powerState` != "VM deallocated" ]]; do
sleep 5
PS=`az vm show -g $RG -n $VM --show-details --query powerState -o tsv | tr -d '"'`
if [[ "${PS}" == "VM deallocated" ]]; then
echo "$VM has deallocated successfully..."
echo "--------------------------------------------------"
echo
break
else
echo "$VM is still deallocating..."
fi
done
done <vm.txt
elif [[ "${OPTIONS}" == "start" ]]; then
while read VM RG; do
timeout 10s az vm start -g $RG -n $VM --no-wait
#PS=$(az vm show -g $RG -n $VM --show-details --query powerState -o tsv | tr -d '"')
echo "$VM is starting..."
while [[ `az vm show -g $RG -n $VM --show-details --query powerState` != "VM running" ]]; do
sleep 5
PS=`az vm show -g $RG -n $VM --show-details --query powerState -o tsv | tr -d '"'`
if [[ "${PS}" == "VM running" ]]; then
echo "$VM has started successfully..."
echo "--------------------------------------------------"
echo
break
else
echo "$VM is still starting..."
fi
done
done <vm.txt
else
echo "Try again..."
exit 1
fi
exit 0