Spot azure vm start if deallocated
Jump to navigation
Jump to search
Code
#!/bin/bash # Set environment variables RESOURCE_GROUP="your-resource-group" VM_NAME="your-vm-name" CHECK_INTERVAL=60 # Check every 60 seconds # Function to check the VM state check_vm_state() { az vm get-instance-view --resource-group $RESOURCE_GROUP --name $VM_NAME --query "instanceView.statuses[?code=='PowerState/deallocated']" -o tsv } # Function to start the VM start_vm() { az vm start --resource-group $RESOURCE_GROUP --name $VM_NAME } # Main loop to watch the VM state and start it if deallocated while true; do VM_STATE=$(check_vm_state) if [ -n "$VM_STATE" ]; then echo "VM $VM_NAME is deallocated. Attempting to start..." start_vm if [ $? -eq 0 ]; then echo "VM $VM_NAME started successfully." else echo "Failed to start VM $VM_NAME." fi else echo "VM $VM_NAME is running." fi sleep $CHECK_INTERVAL done