cloud-init/cloud-init.sh
2024-06-23 05:09:21 +00:00

88 lines
2.6 KiB
Bash
Executable File

#!/usr/bin/env bash
set -x
# Define the Debian version (e.g., 11, 12, 13)
DEBIAN_VERSION="12"
# Map Debian version to its codename
case $DEBIAN_VERSION in
11)
CODENAME="bullseye"
;;
12)
CODENAME="bookworm"
;;
13)
CODENAME="trixie" # Update with the correct codename when known
;;
*)
echo "Unsupported Debian version"
exit 1
;;
esac
# Define the Debian cloud image directory URL
DEBIAN_IMG_DIR="https://cloud.debian.org/images/cloud/${CODENAME}/"
# Create the local images directory if it doesn't exist
LOCAL_IMG_DIR="images"
mkdir -p $LOCAL_IMG_DIR
# Get the latest image URL using wget and grep
LATEST_IMG=$(wget -qO- $DEBIAN_IMG_DIR | grep -oP '(?<=href=")[^"]*(?=/")' | grep -E '20[0-9]{6}-[0-9]{3}' | sort -V | tail -n 1)
SRC_IMG="${DEBIAN_IMG_DIR}${LATEST_IMG}/debian-${DEBIAN_VERSION}-generic-amd64-${LATEST_IMG}.qcow2"
IMG_NAME="${LOCAL_IMG_DIR}/debian-${DEBIAN_VERSION}-generic-amd64-${LATEST_IMG}.qcow2"
# Check if Git LFS is installed
if ! which git-lfs > /dev/null; then
echo "git-lfs not found. Please install git-lfs and try again."
exit 1
fi
# Pull the specific image file from Git LFS if it exists in the repository
git lfs pull --include "$IMG_NAME" || true
# Download the image if it doesn't already exist
if [ ! -f "$IMG_NAME" ]; then
echo "New release. Downloading it now..."
wget -O $IMG_NAME $SRC_IMG
fi
# Install libguestfs-tools if virt-customize is not available
if ! which virt-customize > /dev/null; then
apt-get update
apt-get install -y libguestfs-tools
fi
# Check if qm is installed and exit if not
if ! which qm > /dev/null; then
echo "qm tool not found. Please install Proxmox VE tools and try again."
exit 1
fi
# Inject SSH key and install qemu-guest-agent
SSH_KEY_PATH="id_rsa.pub"
virt-customize -v -x --install qemu-guest-agent -a $IMG_NAME --root-password password:coolpass --ssh-inject root:file:$SSH_KEY_PATH |& tee qemu.log
# Define VM parameters
TEMPL_NAME="debian-${DEBIAN_VERSION}-generic-$(date +%Y%m%d)"
VMID="9004"
MEM="2048"
DISK_SIZE="64G"
DISK_STOR="local-lvm"
NET_BRIDGE="vmbr0"
# Create the VM and configure its settings
qm create $VMID --name $TEMPL_NAME --memory $MEM --net0 virtio,bridge=$NET_BRIDGE
qm importdisk $VMID $IMG_NAME $DISK_STOR
qm set $VMID --scsihw virtio-scsi-pci --scsi0 $DISK_STOR:vm-$VMID-disk-0
qm set $VMID --ide2 $DISK_STOR:cloudinit
qm set $VMID --boot c --bootdisk scsi0
qm set $VMID --serial0 socket --vga serial0
qm set $VMID --ipconfig0 ip=dhcp,gw=10.10.0.1
qm resize $VMID scsi0 $DISK_SIZE
qm template $VMID
# Optionally, remove the downloaded image
# rm $IMG_NAME