Preparation

Log in to your PVE server via SSH, then download Debian 12 image:

wget https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2

To modify the image we’ll use libguestfs-tools, install them with apt:

sudo apt update -y && sudo apt install libguestfs-tools -y

Modifing the image

First of all let’s install qemu-quest-agent:

sudo virt-customize -a debian-12-genericcloud-amd64.qcow2 --install qemu-guest-agent

Now, to replace default debian user with your own:

sudo virt-customize -a debian-12-genericcloud-amd64.qcow2 --run-command "useradd -m $USER -s /bin/bash"

If you don’t want to use currently logged in user’s name, replace $USER variable.

And to give your user sudo access:

sudo virt-customize -a debian-12-genericcloud-amd64.qcow2 --run-command "echo '$USER ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/$USER"

To inject SSH public key run:

sudo virt-customize -a debian-12-genericcloud-amd64.qcow2 --run-command "mkdir -p /home/$USER/.ssh"
sudo virt-customize -a debian-12-genericcloud-amd64.qcow2 --run-command "chown -R $USER: /home/$USER"
sudo virt-customize -a debian-12-genericcloud-amd64.qcow2 --ssh-inject $USER:file:/home/$USER/.ssh/id_rsa.pub

Creating VM template

Start by creating a virtual machine:

sudo qm create 9000 --name 'debian-12-cloudinit' --memory 4096 --cores 2 --net0 virtio,bridge=vmbr0
sudo qm importdisk 9000 debian-12-genericcloud-amd64.qcow2 DATA
sudo qm set 9000 --scsihw virtio-scsi-pci --scsi0 DATA:vm-9000-disk-0
sudo qm set 9000 --boot c --bootdisk scsi0
sudo qm set 9000 --ide2 DATA:cloudinit
sudo qm set 9000 --serial0 socket --vga serial0
sudo qm set 9000 --agent enabled=1

Replace DATA with your storage pool

If you need to, start the VM and then customize it as you see fit. Shut it down once finished.

Convert VM to a template:

sudo qm template 9000

Wrapping up

Congratulations, your template is complete. Now you can create new VMs by cloning it. Either via GUI, terraform or cli command:

sudo qm clone 9000 999 --name test-cloud-init
sudo qm set 999 --ipconfig0 ip=<ip>/24,gw=<gateway ip>
sudo qm start 999

Sources

How to create a Proxmox Ubuntu cloud-init image