#!/usr/bin/env bash # Shared template builder. Each .sh sets the variables below and calls build_template. # # VM_ID VM_NAME CPU_CORE CPU_SOCKET RAM DISK - template hardware (DISK in GB) # IMAGE_URL - cloud image to start from # PACKAGES - extra apt packages, comma separated # DOCKER=1 - install Docker from get.docker.com # GROW_CMD - grows the root fs (default: ext4 on sda1) # # Override where it lands with environment variables: # STORAGE=ssd BRIDGE=vmbr1 ./Ubuntu-LTS-Small.sh set -euo pipefail STORAGE="${STORAGE:-ssd}" # pvebox: ssd (SSD raidz1) or tank (SAS raidz1) BRIDGE="${BRIDGE:-vmbr1}" # vmbr1 = VM-Ekstern (VLAN 4), intern = Proxmox NAT, vmbr0 = Lab IMAGE_DIR="${IMAGE_DIR:-/var/lib/vz/template/cloud}" build_template() { if qm status "$VM_ID" >/dev/null 2>&1; then echo "VM $VM_ID finnes allerede - slett den først: qm destroy $VM_ID --purge" >&2 exit 1 fi command -v virt-customize >/dev/null || apt install -y libguestfs-tools # Download once into a cache (only again when the image changed upstream); # customize a copy so every script starts from a clean image. mkdir -p "$IMAGE_DIR" wget -q --show-progress -N -P "$IMAGE_DIR" "$IMAGE_URL" local work; work=$(mktemp -d) local disk="$work/disk.qcow2" cp "$IMAGE_DIR/$(basename "$IMAGE_URL")" "$disk" # The cloud image's root filesystem is only ~2 GB, too small for Docker. # Grow the image by 4 GB and the root partition with it. qemu-img resize -q "$disk" +4G virt-customize -a "$disk" --run-command "${GROW_CMD:-growpart /dev/sda 1 && resize2fs /dev/sda1}" # Guest agent, extra packages, optional Docker, and an empty machine-id so clones get their own DHCP lease virt-customize -a "$disk" --install "qemu-guest-agent${PACKAGES:+,$PACKAGES}" if [ "${DOCKER:-0}" = 1 ]; then virt-customize -a "$disk" --run-command "curl -fsSL https://get.docker.com | sh" fi virt-customize -a "$disk" --truncate /etc/machine-id # cpu host: AlmaLinux 9 needs x86-64-v2 and won't boot on the old kvm64 default qm create "$VM_ID" --name "$VM_NAME" --cpu host --net0 "virtio,bridge=$BRIDGE" qm set "$VM_ID" --cores "$CPU_CORE" --sockets "$CPU_SOCKET" --memory "$RAM" qm set "$VM_ID" --scsihw virtio-scsi-pci --scsi0 "$STORAGE:0,import-from=$disk,discard=on" qm set "$VM_ID" --ide2 "$STORAGE:cloudinit" qm set "$VM_ID" --boot order=scsi0 qm set "$VM_ID" --serial0 socket --vga serial0 qm resize "$VM_ID" scsi0 "${DISK}G" qm set "$VM_ID" --ipconfig0 ip=dhcp qm set "$VM_ID" --agent enabled=1 qm template "$VM_ID" rm -rf "$work" echo "Template er ferdig med id $VM_ID ($VM_NAME) på $STORAGE, nett $BRIDGE" }