From 052083992530116750d5f9b50eb1a1aa61c4942c Mon Sep 17 00:00:00 2001 From: Eric Liu Date: Sat, 14 Dec 2024 19:47:23 -0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20(cloud-init.sh):=20dynamically=20ge?= =?UTF-8?q?nerate=20VMID=20and=20IP=20based=20on=20the=20last=20octet=20of?= =?UTF-8?q?=20the=20host=20machine's=20IP=20address=20=F0=9F=90=9B=20(clou?= =?UTF-8?q?d-init.sh):=20fix=20IP=20address=20assignment=20to=20use=20CIDR?= =?UTF-8?q?=20notation=20=F0=9F=90=9B=20(cloud-init.sh):=20add=20validatio?= =?UTF-8?q?n=20for=20IP=20last=20octet=20to=20ensure=20it=20is=20between?= =?UTF-8?q?=201=20and=20254?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cloud-init.sh | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/cloud-init.sh b/cloud-init.sh index c88e050..5a54864 100755 --- a/cloud-init.sh +++ b/cloud-init.sh @@ -1,6 +1,21 @@ #!/usr/bin/env bash set -x +# Get IP address of the local machine and extract the last octet +LOCAL_IP=$(ip -4 addr show vmbr0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1) +if [ -z "$LOCAL_IP" ]; then + echo "Error: Could not detect IP address on vmbr0 interface" + exit 1 +fi + +IP_LAST_OCTET=$(echo "$LOCAL_IP" | cut -d. -f4) + +# Validate IP last octet +if ! [[ $IP_LAST_OCTET =~ ^[0-9]+$ ]] || [ $IP_LAST_OCTET -lt 1 ] || [ $IP_LAST_OCTET -gt 254 ]; then + echo "Error: Detected IP last octet ($IP_LAST_OCTET) is invalid. Must be between 1 and 254" + exit 1 +fi + # Define the Debian version (e.g., 11, 12, 13) DEBIAN_VERSION="12" @@ -65,8 +80,9 @@ 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 +IP_ADDRESS="10.10.0.${IP_LAST_OCTET}" +VMID="90${IP_LAST_OCTET}" # VMID will be 9050 for IP 10.10.0.50 TEMPL_NAME="debian-${DEBIAN_VERSION}-generic-$(date +%Y%m%d)" -VMID="9004" MEM="2048" DISK_SIZE="64G" DISK_STOR="local-lvm" @@ -80,7 +96,7 @@ 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 set $VMID --ipconfig0 ip=${IP_ADDRESS}/24,gw=10.10.0.1 qm resize $VMID scsi0 $DISK_SIZE qm template $VMID