Bulk Auto Start VMs

Script to Auto Start VMs in case they are turned off by users.

#!/bin/bash

# Array of VM IDs
VM_IDS=(800 812 911 1903)  # Replace with your VM IDs
DELAY=60            # Delay in seconds between checks
CHECKS=2           # Number of checks to perform

log_file="/var/log/vm_autostart.log" # Path to log file

# Function to log messages with a timestamp
log_message() {
  timestamp=$(date +"%Y-%m-%d %H:%M:%S")
  echo "$timestamp: $1" >> "$log_file"
}

# Function to check if a VM is stopped
check_vm_status() {
  local VMID=$1
  log_message "Checking status of VM $VMID..."
  status=$(/usr/sbin/qm status "$VMID" 2>&1) # Use full path to qm
  log_message "VM $VMID status: $status"
  if [[ "$status" == "status: stopped" ]]; then
    return 0  # VM is stopped
  else
    return 1  # VM is running or does not exist
  fi
}

# Function to handle the VM checks and start if necessary
handle_vm() {
  local VMID=$1
  log_message "Starting check for VM $VMID"

  # Perform the checks
  for ((i = 1; i <= CHECKS; i++)); do
    if check_vm_status "$VMID"; then
      log_message "VM $VMID is stopped (check $i/$CHECKS)."
      if [[ $i -lt $CHECKS ]]; then
        log_message "Waiting $DELAY seconds before the next check..."
        sleep "$DELAY"
      fi
    else
      log_message "VM $VMID is running or does not exist. Skipping further checks."
      return
    fi
  done

  # If all checks confirm the VM is stopped, start it
  if check_vm_status "$VMID"; then
    log_message "VM $VMID is still stopped after $CHECKS checks. Starting VM..."
    /usr/sbin/qm start "$VMID" # Use full path to qm
    log_message "VM $VMID started."
  else
    log_message "VM $VMID status changed during checks. Not starting."
  fi
}

# Clear the log file at the start of the script
> "$log_file"

# Loop through each VM ID and handle it in the background
for VMID in "${VM_IDS[@]}"; do
  handle_vm "$VMID" &
done

# Wait for all background processes to finish
wait

log_message "All VM checks completed."