Skip to content

Skrypt do tworzenia template

Skrypt do tworzenia template, wykorzystującego mechanizm cloud-init.

#!/usr/bin/env bash

# stop after failure
set -euo pipefail

################################ CHANGE THAT SECTION ################################
template_name="ubuntu-24.04-template"
template_id="99001"
cloudimg_link="https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img"
shared_storage_name="local-lvm"

#####################################################################################

# Refuse to overwrite an existing VM/template
if qm status "$template_id" &>/dev/null; then
    echo "!! VM $template_id already exists - remove it first: qm destroy $template_id"
    exit 1
fi

# Create VM with 2GB RAM, 2 cores without network interface
qm create "$template_id" \
  --name "$template_name" \
  --memory 2048 \
  --cores 2 \
  --agent enabled=1 \
  --serial0 socket \
  --ostype l26

# Download image
wget -O "$template_name".img "$cloudimg_link"

# Check image format, if is not qcow2 -> parse to qcow2
fmt=$(qemu-img info "$template_name".img | awk -F': *' '/^file format:/ {print $2}')

if [[ "$fmt" == "qcow2" ]]; then
    echo ">> ${template_name}.img is qcow2 file, renaming only"
    mv -n "${template_name}".img "${template_name}".qcow2
else
    echo ">> not valid format: $fmt - converting to qcow2"
    qemu-img convert -p -O qcow2 "${template_name}.img" "${template_name}.qcow2"
    rm "${template_name}.img"
fi

# Increase disk size
qemu-img resize "${template_name}.qcow2" 32G

# Import disk to VM
qm importdisk "$template_id" "${template_name}.qcow2" "$shared_storage_name"

# Mount imported disk to VM
qm set "$template_id" \
  --scsihw virtio-scsi-pci \
  --scsi0 "${shared_storage_name}":vm-"${template_id}"-disk-0

# Create Cloud-Init disk
qm set "$template_id" \
  --ide2 "${shared_storage_name}":cloudinit

# Set boot order from imported disk
qm set "$template_id" --boot order=scsi0

# Remove old QCOW image
rm "${template_name}.qcow2"

# Convert VM to Template
qm template "$template_id"