cloud-init/install.sh

91 lines
3.0 KiB
Bash

#!/bin/bash
set -e
set +x
# Default Variables (Can be overridden with command-line arguments)
IMG_URL=${1:-"https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img"}
IMG_NAME=${2:-"noble-server-cloudimg-amd64.img"}
DISTRO=${3:-"ubuntu"} # Default to "ubuntu"
VERSION=${4:-"2404"} # Default to "2404"
STORAGE=${5:-"proxmox"} # Default to "proxmox"}
# Ask for starting VM ID if running with manual inputs
if [[ -z $1 ]]; then
read -p "Enter the starting VM ID (e.g., 8000): " STARTING_VM_ID
else
STARTING_VM_ID=8000
fi
check_command() {
if [ $? -ne 0 ]; then
echo "Error: $1 failed."
exit 1
fi
}
delete_existing_vm() {
local vm_id=$1
if qm status $vm_id &> /dev/null; then
echo "Deleting existing VM with ID $vm_id..."
qm destroy $vm_id --purge
check_command "Deleting existing VM"
fi
}
create_vm() {
local vm_id=$1
local vm_name=$2
local memory=$3
delete_existing_vm $vm_id
if [ -f "$IMG_NAME" ]; then
echo "Image file already exists at: $(realpath $IMG_NAME)"
echo "Skipping download..."
else
echo "Downloading cloud image..."
wget $IMG_URL -O $IMG_NAME
check_command "Downloading cloud image"
fi
echo "Creating a new virtual machine with name $vm_name..."
qm create $vm_id --memory $memory --core 1 --name $vm_name --net0 virtio,bridge=vmbr0
check_command "Creating virtual machine"
echo "Importing the downloaded cloud image disk to storage ($STORAGE)..."
qm disk import $vm_id $IMG_NAME $STORAGE
check_command "Importing disk to storage"
echo "Attaching the imported disk to the VM..."
qm set $vm_id --scsihw virtio-scsi-pci --scsi0 ${STORAGE}:$vm_id/vm-$vm_id-disk-0.raw
check_command "Attaching disk to VM"
echo "Adding cloud init drive..."
qm set $vm_id --ide2 $STORAGE:cloudinit
check_command "Adding cloud init drive"
echo "Making cloud init drive bootable and restricting BIOS..."
qm set $vm_id --boot c --bootdisk scsi0
check_command "Setting boot options"
echo "Adding serial console..."
qm set $vm_id --serial0 socket --vga serial0
check_command "Adding serial console"
echo "VM $vm_name ($vm_id) with $memory MB RAM created successfully!"
echo "IMPORTANT: Before converting $vm_name to a template, do not forget to configure the cloud-init options."
echo "DO NOT boot the VM before setting the cloud-init options, as this will solidify the VM's hostname and other settings!"
}
# Create VMs with different memory configurations
create_vm $STARTING_VM_ID "${DISTRO}-${VERSION}-512mb" 512
create_vm $((STARTING_VM_ID + 1)) "${DISTRO}-${VERSION}-1gb" 1024
create_vm $((STARTING_VM_ID + 2)) "${DISTRO}-${VERSION}-2gb" 2048
create_vm $((STARTING_VM_ID + 3)) "${DISTRO}-${VERSION}-4gb" 4096
create_vm $((STARTING_VM_ID + 4)) "${DISTRO}-${VERSION}-8gb" 8192
create_vm $((STARTING_VM_ID + 5)) "${DISTRO}-${VERSION}-12gb" 12288
echo "All VMs created successfully!"