Step 1: Creating the VM Template with Packer
- A reference template is essential for Terraform and then Ansible.
- Packer and Vates' XCP-ng plugin build a golden Rocky Linux 10 image.
- Kickstart, ansible-windows account, customization scripts.
- Copying the template to multiple Xen Orchestra pools; project files available.
Introduction
For creating the Kubernetes cluster as described in the previous article, it is necessary to start from a reference template. This will be used to deploy all nodes of the cluster via Terraform, and each server can then be configured via Ansible.
The idea is to stick with the simplest possible template. As it stands, it does not need any particular features, but it must be usable later via an SSH connection from Ansible.
By the way, on this point, I will reuse my logic for using Ansible from my W11 workstation via WSL (Windows Subsystem For Linux).
I encourage you to read the article detailing the creation of a dedicated account, named ansible-windows, for which I have generated an SSH key pair consisting of a private key and a public key.
This is the method I will use to authenticate with this account, which I need to integrate into my template so that it is recognized at the level of each server deployed from it.
To create our template, we could simply manually install a first VM under XCP-ng and then convert it into a template. But to further automate this process, we will use a specific tool: Packer.
Click the image to enlarge.
Introducing Packer
Packer is an open source tool published by HashiCorp (the company behind Terraform, Vault, Consul, Nomad…, acquired by IBM in early 2025), created in 2013 by Mitchell Hashimoto. It shares the DNA of Terraform: the same configuration language HCL2 (HashiCorp Configuration Language), the same declarative philosophy… and since 2023, the same BSL (Business Source License).
Packer automates the creation of a machine image, often referred to as a Golden Image. Instead of manually installing our reference operating system, we describe its configuration in a specific language to define how to build the image. This allows us to version and track its settings, much like we would with an application. It is also easily reproducible and traceable.
If needed, instead of modifying a production server, we rebuild a clean image and redeploy it. The image configuration resides in a code sourcing tool like Git, rather than in the administrator's head.
Packer interprets the configuration description to implement it on the target platform. Similar to Terraform, Packer requires plugins related to where the image will be deployed. In our case, this is XCP-ng. Fortunately, Vates offers an official plugin available here: packer-plugin-xenserver.
Click the image to enlarge.
Choosing Rocky Linux
In terms of operating systems, as described in the previous article, I have chosen Rocky Linux 10. It was created at the end of 2020 following a surprising announcement: Red Hat's decision to abandon CentOS Linux (the stable version) in favor of CentOS Stream (a continuous development version). In response to this change, Gregory Kurtzer, the original founder of the CentOS project, launched Rocky Linux to fill the void and once again offer a stable, free, and community-supported operating system for production environments.
A common alternative is Alma Linux. It shares the same philosophy but offers slightly more freedom regarding patching. CloudLinux, its publisher, does not necessarily wait for a Red Hat patch to be released before fixing a vulnerability.
In summary, Rocky Linux is a strict and absolute clone of RHEL (Red Hat Enterprise Linux). Alma Linux is faster with certain patches and has a broader hardware support policy, but it deviates slightly from RHEL. Both are excellent choices for an enterprise operating system.
How Packer Works
When using Packer, we chain together three components:
- Builder: Where and how to build the image?: This is the platform-specific driver. It starts a temporary VM (in this case, on XCP-ng via the xenserver-iso builder), boots it from an ISO, performs the installation, connects to it (SSH), and then, at the end of the process, freezes the VM into an image/template and destroys the temporary instance.
- Provisioners: What to install/configure?: This includes the specific configurations to inject into the template, such as custom scripts, user creation, file transfers, etc.
- Post-processors: What to do afterwards?: We won't use this here, but you can define what to do with the resulting image, such as compressing it or sending it to a registry.
Everything is described in HCL2 within files named *.pkr.hcl, with variables for everything that changes from one environment to another (secrets, SR names, network settings, etc.). A plugin per platform (required_plugins) provides the appropriate builder, vatesfr/xenserver for XCP-ng.
Packer is not Terraform
I'm providing an important piece of information right away: Packer is not Terraform, and vice versa. We could design all the nodes with Packer by creating multiple images. But that's not the goal. It would be time-consuming because, unlike Terraform, which relies on cloning to create VMs, Packer will deploy the OS on each server.
Furthermore, Packer and Terraform don't have the same role: Packer creates the mold, Terraform casts the pieces. While our future Terraform tasks will be specific to the K8S cluster, here the template is generic and could very well serve other purposes.
Installation and Project Structure
Packer is a simple executable that you can download directly from the vendor's website. Just download the version for your OS and make sure the binary can be called from your command prompt.
Click the image to enlarge.
Click the image to enlarge.
Click the image to enlarge.
Next, we will organize our project structure. It will consist of the following:
rocky10-base.pkr.hcl # packer{} (plugin), source xenserver-iso, build{} (provisioners)
variables.pkr.hcl # toutes les variables (descriptions FR)
example.pkrvars.hcl # modèle à copier en xkub.auto.pkrvars.hcl (gitignored)
http/ks.cfg # kickstart servi par le serveur HTTP de Packer
http/ansible-windows.pub # clé PUBLIQUE servie au kickstart (versionnée, = ../keys/...)
scripts/10-guest-tools.sh # EPEL + xe-guest-utilities + dnf update
scripts/20-cloud-init.sh # datasource NoCloud
scripts/90-cleanup.sh # généralisation (machine-id, clés SSH, seed cloud-init)
Project tree for Packer.
Our Claude Code subagent, packer-builder.md, introduced in the first article, will be in charge of this tree structure.
You'll notice the use of an http folder. This is because Packer exposes an internal web server during its execution to present the necessary files for configuration to the OS being built. Keep this in mind if a firewall is present between your Packer instance and the platform where the server is deployed.
Key Files
We will focus on a few files.
rocky10-base.pkr.hcl - I won't go into detail; my Claude agent has already commented on the files extensively. In general, we load the necessary plugins, retrieve the variables we need, then start building the VM, and finally complete the customization, including injecting the XCP-ng drivers (the equivalent of VMware tools).
# ============================================================================
# rocky10-base.pkr.hcl — Source + build du template Rocky Linux 10
# Plugin : vatesfr/xenserver (builder xenserver-iso). Cf. cookbook 01.
# ============================================================================
packer {
required_plugins {
xenserver = {
version = ">= 0.9.0"
source = "github.com/vatesfr/xenserver"
}
}
}
source "xenserver-iso" "rocky10" {
# --- Connexion à l'hôte XCP-ng (XAPI) ---
remote_host = var.remote_host
remote_username = var.remote_username
remote_password = var.remote_password
remote_ssh_port = var.remote_ssh_port
# --- Emplacements XCP-ng ---
sr_name = var.sr_name
sr_iso_name = var.sr_iso_name
network_names = var.network_names
# --- Source ISO ---
iso_url = var.iso_url
iso_checksum = var.iso_checksum
# --- VM de build / futur template ---
vm_name = var.vm_name
vm_description = var.vm_description
vcpus_max = var.vcpus
vcpus_atstartup = var.vcpus
vm_memory = var.vm_memory
disk_size = var.disk_size
firmware = "bios"
# --- Kickstart servi par le serveur HTTP intégré de Packer ---
# Le dossier http/ contient ks.cfg ET ansible-windows.pub (clé publique servie
# au kickstart, qui la récupère par curl — pas de mot de passe nécessaire).
http_directory = "http"
boot_wait = var.boot_wait
install_timeout = var.install_timeout
# Détection d'IP par phone-home HTTP : la VM de build (DHCP) télécharge le kickstart
# depuis le serveur HTTP de Packer, qui capture l'IP source. Le plugin vatesfr/xenserver
# n'expose pas de ssh_host fixe ; "tools" est exclu (guest tools installés seulement au
# provisioning). L'IP reste la même avant/après reboot (bail DHCP stable sur la MAC).
ip_getter = "http"
# PIÈGE EL10 : Rocky Linux 10 amorce l'ISO avec GRUB2 (et non isolinux), même en
# BIOS. Les touches d'édition diffèrent : 'e' pour éditer l'entrée (pas <tab>),
# on complète la ligne 'linux ...', puis Ctrl-X pour démarrer.
boot_command = [
"<wait5>",
"<up><wait>", # sélectionner « Install Rocky Linux Minimal 10.2 »
"e<wait>", # éditer l'entrée GRUB2
"<down><down><end>", # fin de la ligne « linux /images/pxeboot/vmlinuz ... »
" inst.text inst.ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/ks.cfg",
"<wait><leftCtrlOn>x<leftCtrlOff>", # démarrer
]
# --- Connexion SSH post-install (par clé ansible-windows) ---
ssh_username = var.ssh_username
ssh_key_path = var.ssh_private_key_path
ssh_wait_timeout = "60m"
# --- Finalisation : convertir la VM en template ET la conserver sur l'hôte ---
# keep_vm = "always" : le template reste dans XCP-ng à la fin du build (objectif
# phase 1 = template réutilisable dans XO, pas seulement un fichier XVA local).
# Avec "never" (défaut du plugin), la VM était convertie en template, exportée en
# XVA dans output-rocky10/, puis DÉTRUITE de l'hôte → invisible dans XO.
skip_set_template = false
keep_vm = "always"
}
build {
name = "rocky10-base"
sources = ["source.xenserver-iso.rocky10"]
# Hostname OS aligné sur le nom de la VM/template (source unique = var.vm_name).
# Il sera de toute façon redéfini par clone via cloud-init (Terraform, phase 2) ;
# ici c'est surtout une question de cohérence VM XCP-ng <-> hostname OS.
provisioner "shell" {
inline = ["sudo hostnamectl set-hostname ${var.vm_name}"]
}
# ansible-windows dispose de sudo NOPASSWD (posé par le kickstart).
provisioner "shell" {
execute_command = "sudo -E bash '{{ .Path }}'"
scripts = [
"scripts/10-guest-tools.sh",
"scripts/20-cloud-init.sh",
"scripts/90-cleanup.sh",
]
}
}
rocky10-base.pkr.hcl
variables.pkr.hcl - This file contains the definition of all the variables we will need, which are used by what we just saw in the previous file. Their naming is governed by my CONVENTIONS.md file, which the packer-builder.md agent follows in Claude. Note that this is also where we specify where to get our Rocky Linux ISO image, and therefore the version of the OS to install (iso_url). As you can see, the image can be fetched directly online.
# ============================================================================
# variables.pkr.hcl — Template Rocky Linux 10 (xkub.coolcorp.priv)
# Toutes les variables du build. Les secrets ne portent PAS de valeur ici :
# ils sont fournis par variables d'environnement PKR_VAR_* (cf. CONVENTIONS.md).
# ============================================================================
# --- Connexion à l'hôte XCP-ng (API XAPI) -----------------------------------
variable "remote_host" {
type = string
description = "Adresse de l'hôte XCP-ng (pool master) sur lequel Packer construit la VM."
}
variable "remote_username" {
type = string
default = "root"
description = "Compte XAPI de l'hôte XCP-ng."
}
variable "remote_password" {
type = string
sensitive = true
description = "Mot de passe XAPI. À fournir via PKR_VAR_remote_password (jamais en clair dans un fichier versionné)."
}
variable "remote_ssh_port" {
type = number
default = 22
description = "Port SSH de l'hôte XCP-ng (utilisé par le plugin pour piloter le build)."
}
# --- Emplacements XCP-ng ----------------------------------------------------
variable "sr_name" {
type = string
description = "Nom du Storage Repository où créer le disque de la VM puis le template."
}
variable "sr_iso_name" {
type = string
description = "Nom du SR de type ISO où Packer téléverse l'ISO Rocky Linux."
}
variable "network_names" {
type = list(string)
description = "Réseau(x) XCP-ng à attacher à la VM de build (DHCP + accès aux dépôts requis)."
}
# --- Source ISO Rocky Linux 10 ----------------------------------------------
variable "iso_url" {
type = string
default = "https://download.rockylinux.org/pub/rocky/10/isos/x86_64/Rocky-10.2-x86_64-minimal.iso"
description = "URL de l'ISO Rocky Linux 10 minimal."
}
variable "iso_checksum" {
type = string
default = "sha256:aac6ac3ce781b91a91ce78463405f66c611a5dca4b3840c79e5e01d97302f6c8"
description = "Empreinte de l'ISO (Rocky-10.2-x86_64-minimal.iso)."
}
# --- Définition de la VM de build / template --------------------------------
variable "vm_name" {
type = string
default = "prdtplroc501"
description = "Nom du template produit (convention de nommage prd du projet)."
}
variable "vm_description" {
type = string
default = "Template generique Rocky Linux 10 - xkub.coolcorp.priv (Packer)"
description = "Description du template dans XO."
}
variable "vcpus" {
type = number
default = 2
description = "vCPU de la VM de build (le dimensionnement final est fait par Terraform au clone)."
}
variable "vm_memory" {
type = number
default = 2048
description = "RAM (Mo) de la VM de build."
}
variable "disk_size" {
type = number
default = 20480
description = "Taille (Mo) du disque du template. Étendu par rôle au clone (cloud-init growpart)."
}
# --- Connexion SSH post-install ---------------------------------------------
variable "ssh_username" {
type = string
default = "ansible-windows"
description = "Compte utilisé par Packer pour provisionner la VM (créé par le kickstart)."
}
variable "ssh_private_key_path" {
type = string
description = "Chemin LOCAL (poste W11) vers la clé PRIVÉE ansible-windows. Hors dépôt."
}
# --- Timings -----------------------------------------------------------------
variable "boot_wait" {
type = string
default = "10s"
description = "Délai avant l'envoi du boot_command (laisser le menu d'amorçage s'afficher)."
}
variable "install_timeout" {
type = string
default = "60m"
description = "Durée maximale de l'installation Anaconda."
}
variables.pkr.hcl
http/ks.cfg - This is the traditional file associated with the automated installation of an OS like RedHat. It contains standard parameters such as keyboard, network, and partitioning configuration. This is where you need to act if you want to modify the global configuration of our image. We depend on a DHCP server for IP address acquisition; this is something to keep in mind for this example. Importantly, here we also create the ansible-windows account and add it to a sudo file to allow it to become root if necessary. We will not create a specific password for this user and will block authentication via password (passwd -l). The public key ansible-windows.pub, located in the same http subdirectory as ks.cfg, will be used. This means that any machine derived from this future image can only be connected using the private ssh key of ansible-windows.
A slight deviation from a classic template: here, SWAP is disabled (recommended with Kubernetes). We could have handled this later (using Ansible, for example), but in this way, we don't create partitions unnecessarily.
# ============================================================================
# ks.cfg — Kickstart Rocky Linux 10, template générique xkub.coolcorp.priv
# Servi par le serveur HTTP intégré de Packer (http/). Voir cookbook 01.
# Aucun secret ici : ansible-windows reçoit sa clé publique par curl et a son
# mot de passe verrouillé ; Packer se connecte ensuite par clé privée.
# ============================================================================
text
lang en_US.UTF-8
keyboard --vckeymap=fr --xlayouts='fr'
timezone Europe/Paris --utc
# Source d'installation : dépôts en ligne (ISO minimal + accès réseau au build)
url --mirrorlist="https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=BaseOS-10"
repo --name=AppStream --mirrorlist="https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=AppStream-10"
# Réseau : DHCP au build. La VM de build est éphémère ; Packer découvre son IP via
# ip_getter=http (le système garde la même IP au reboot, bail DHCP stable sur la MAC).
# Le template reste générique : chaque clone reçoit son réseau via cloud-init NoCloud
# (Terraform, phase 2). Les IP FIXES des nœuds du cluster, c'est phase 2, pas ici.
# Le hostname n'est PAS fixé ici : il est aligné sur var.vm_name par un provisioner
# (cf. rocky10-base.pkr.hcl), puis redéfini par clone via cloud-init.
network --bootproto=dhcp --device=link --activate
# Comptes
rootpw --lock
# ansible-windows est créé en %post (clé SSH + sudoers NOPASSWD)
# Sécurité : SELinux enforcing, firewalld actif (cf. CLAUDE.md règle 11)
selinux --enforcing
firewall --enabled --ssh
services --enabled=sshd,chronyd
# Partitionnement : LVM, PAS de swap (prérequis kubelet)
# PIÈGE EL10 : Rocky 10 étiquette le disque en GPT. Un système BIOS sur disque GPT
# exige une partition 'biosboot' de 1 MiB (sinon « Kickstart insufficient » au build).
clearpart --all --initlabel
part biosboot --fstype=biosboot --size=1
part /boot --fstype=xfs --size=1024
part pv.01 --size=1 --grow
volgroup vg00 pv.01
logvol / --fstype=xfs --name=root --vgname=vg00 --size=1 --grow
bootloader --location=mbr
%packages
@^minimal-environment
cloud-init
chrony
python3
tar
curl-minimal
policycoreutils-python-utils
-iwl*-firmware
%end
%post --erroronfail --log=/root/ks-post.log
set -x
# --- Compte d'automatisation ansible-windows ---
useradd -m -G wheel -s /bin/bash ansible-windows
passwd -l ansible-windows
echo 'ansible-windows ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/ansible-windows
chmod 0440 /etc/sudoers.d/ansible-windows
# --- Clé publique récupérée depuis le serveur HTTP de Packer ---
# (même dossier que ce kickstart ; on déduit l'URL de /proc/cmdline)
KSURL=$(sed -n 's/.*inst.ks=\([^ ]*\).*/\1/p' /proc/cmdline)
BASE=$(dirname "$KSURL")
install -d -m 0700 -o ansible-windows -g ansible-windows /home/ansible-windows/.ssh
curl -fsSL "$BASE/ansible-windows.pub" -o /home/ansible-windows/.ssh/authorized_keys || true
# Garde-fou : sans clé valide, le template serait inutilisable (SSH par clé uniquement).
# Couplé à « %post --erroronfail », ce exit 1 fait échouer l'install AU BUILD (et non
# 8 min plus tard au SSH) si ansible-windows.pub manque sur le serveur HTTP de Packer.
if ! grep -q '^ssh-' /home/ansible-windows/.ssh/authorized_keys 2>/dev/null; then
echo "ERREUR: ansible-windows.pub absent/illisible depuis le serveur HTTP de Packer" >&2
exit 1
fi
chmod 0600 /home/ansible-windows/.ssh/authorized_keys
chown ansible-windows:ansible-windows /home/ansible-windows/.ssh/authorized_keys
restorecon -R /home/ansible-windows/.ssh
# --- Durcissement SSH ---
sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
# --- Phone-home : permet à Packer (ip_getter=http) d'apprendre l'IP de la VM ---
curl -fsS "$BASE/ks.cfg" > /dev/null || true
%end
reboot
http/ks.cfg
10-guest-tools.sh - This is the first customization script that needs to be run after the build phase. Its purpose is to install and activate the drivers specific to the Xen hypervisor used by XCP-ng. This is equivalent to installing the xe-guest-utilities-latest package. It's a mandatory dependency for subsequent steps, as it allows the IPs of VMs deployed later to be reported at the level of Xen Orchestra and XCP-ng.
#!/usr/bin/env bash
# ----------------------------------------------------------------------------
# 10-guest-tools.sh — Guest tools XCP-ng + mise à jour système
# PIÈGE EL10 : sur Rocky Linux 10, xe-guest-utilities n'est PAS dans les dépôts
# de base. Le paquet 'xe-guest-utilities-latest' est fourni par EPEL 10.
# Sans ces guest tools, XO/Terraform ne remontent pas l'IP des VMs.
# ----------------------------------------------------------------------------
set -euxo pipefail
dnf -y update
# EPEL pour disposer de xe-guest-utilities-latest
dnf -y install epel-release
dnf -y install xe-guest-utilities-latest
# Agent invité Xen : sur EL10, xe-linux-distribution.service EST le service principal
# (il lance le démon xe-daemon, qui remonte l'IP/metrics vers XenStore → lues par XO et
# Terraform en phase 2). Il n'existe PAS de xe-daemon.service séparé. On enable sans
# « || true » : si ça échoue, on veut que le build s'arrête (guest tools = critiques).
systemctl enable xe-linux-distribution.service
scripts/10-guest-tools.sh
20-cloud-init.sh - Here, the cloud-init dependencies will be deployed. This will be used later by Terraform to customize the VMs that it creates from a clone of the image we are currently building with Packer.
#!/usr/bin/env bash
# ----------------------------------------------------------------------------
# 20-cloud-init.sh — Configuration cloud-init pour le datasource NoCloud
# C'est ce datasource qu'utilise ensuite le provider Terraform xenorchestra
# (attributs cloud_config / cloud_network_config) pour injecter hostname/IP.
# ----------------------------------------------------------------------------
set -euxo pipefail
dnf -y install cloud-init
# Restreindre cloud-init au seul datasource NoCloud (évite les sondes inutiles)
cat > /etc/cloud/cloud.cfg.d/90-datasource.cfg <<'EOF'
datasource_list: [ NoCloud, None ]
EOF
systemctl enable cloud-init-local.service cloud-init.service cloud-config.service cloud-final.service
scripts/20-cloud-init.sh
90-cleanup.sh - This is also important; it's the final phase where we clean up traces of the deployment so that the image does not contain elements that could cause problems during cloning operations. Once again, my packer-builder subagent has well-commented the file.
#!/usr/bin/env bash
# ----------------------------------------------------------------------------
# 90-cleanup.sh — Généralisation du template (DOIT être le dernier provisioner)
# Objectif : chaque clone obtient un machine-id, des clés SSH hôte et un seed
# cloud-init uniques. Sans ça, tous les clones partageraient la même identité.
# ----------------------------------------------------------------------------
set -euxo pipefail
# Effacer les profils réseau du build (connexion DHCP créée par l'installeur) : le
# template reste générique. Chaque clone reçoit son réseau via cloud-init NoCloud
# (provider Terraform xenorchestra, phase 2), sans hériter d'un profil du build.
rm -f /etc/NetworkManager/system-connections/*
rm -f /etc/sysconfig/network-scripts/ifcfg-*
# Réinitialiser cloud-init (seed + logs) pour qu'il rejoue au 1er boot du clone
cloud-init clean --logs --seed || true
# machine-id régénéré au prochain boot
truncate -s 0 /etc/machine-id
# /var/lib/dbus/machine-id : compat ancienne ; sur Rocky 10 minimal le dossier
# /var/lib/dbus n'existe pas (systemd/dbus-broker lit directement /etc/machine-id).
# Ne recréer le lien que si le dossier existe, sinon le build échoue (set -e).
if [ -d /var/lib/dbus ]; then
rm -f /var/lib/dbus/machine-id
ln -sf /etc/machine-id /var/lib/dbus/machine-id
fi
# Clés d'hôte SSH régénérées au 1er boot (unités sshd-keygen de Rocky)
rm -f /etc/ssh/ssh_host_*
# Caches et journaux
dnf clean all
rm -rf /var/cache/dnf/* /tmp/* /var/tmp/*
find /var/log -type f -exec truncate -s 0 {} \;
rm -f /root/ks-post.log
# Historique shell
: > /root/.bash_history || true
: > /home/ansible-windows/.bash_history || true
scripts/90-cleanup.sh
Configuring Variables
We will first specify the variables needed for the deployment. You should not modify the definition of the variables in the variables.pkr.hcl file, but rather copy the example.pkrvars.hcl file to xkub.auto.pkrvars.hcl:
Copy-Item example.pkrvars.hcl xkub.auto.pkrvars.hcl
Click the image to enlarge.
I haven't talked about these files yet, but they simply provide an example of how to declare the necessary variables, example.pkrvars.hcl, to create a file specific to your deployment where you will fill in the values specific to your use case, xkub.auto.pkrvars.hcl.
# ============================================================================
# example.pkrvars.hcl — MODÈLE de variables (versionné, valeurs fictives)
# Copier en « xkub.auto.pkrvars.hcl » (ignoré par git) puis renseigner.
# PowerShell : Copy-Item example.pkrvars.hcl xkub.auto.pkrvars.hcl
# Le mot de passe XCP-ng NE figure PAS ici : il passe par la variable
# d'environnement PKR_VAR_remote_password.
# ============================================================================
# --- Hôte XCP-ng ---
remote_host = "192.168.10.10" # adresse XAPI du pool master XCP-ng
remote_username = "root"
# --- Emplacements XCP-ng (noms tels qu'affichés dans Xen Orchestra) ---
sr_name = "Local storage" # SR du disque/template
sr_iso_name = "ISOs" # SR de type ISO
network_names = ["Pool-wide network associated with eth0"] # réseau LAN (DHCP + Internet)
# --- Clé privée ansible-windows (sur le poste W11, hors dépôt) ---
ssh_private_key_path = "C:/Users/vburgun/.ssh/ansible-windows"
# --- (Optionnel) surcharges ---
# vm_name = "prdtplroc501"
# disk_size = 20480
example.pkrvars.hcl
It is important to note that the addon provided by Vates for Packer relies on access to an XCP-ng server, not Xen Orchestra.
Therefore, you need to select a server from our XCP pool and specify its IP address as the connection source. You will then need to choose the location of the Storage Repository that will contain the RockyLinux 10 ISO retrieved by Packer (NFS-ISO-Library) on that server.
Click the image to enlarge.
Similarly, you will need to specify the SR (Storage Repository) that will be used to host the template (XOSTOR). The network that should be connected to the VM must also be indicated. All of this can be retrieved directly from the GUI of Xen Orchestra. If this doesn't make sense to you, I invite you to consult the details of my LAB under XCP-ng.
Click the image to enlarge.
Click the image to enlarge.
Click the image to enlarge.
Since the private key for the Ansible account is required, I don't store it within the project directory because it's too sensitive. Instead, I point to its actual location on my machine, which is a VeraCrypt volume.
Note that if you are using a different platform, the logic remains exactly the same. You need to adapt it to your target environment and use a different addon if necessary.
Starting Image Creation
To start creating the image, you need to be in the root directory of our project structure. First, we verify that the Packer executable we retrieved earlier is accessible here by checking its version.
packer --version
Click the image to enlarge.
Then, we run the first command packer init. This will retrieve the dependencies for the XCP-ng addon directly from the Vates repository.
packer init .
Click the image to enlarge.
Next, we check the syntax of the entire configuration to ensure that everything is correct.
packer fmt .
Click the image to enlarge.
Now it's time to provide the confidential variables. Since we didn't specify their values in the xkub.auto.pkrvars.hcl file, but they are defined in variables.pkr.hcl, we will now populate them using environment variables in the shell (in this case, PowerShell). This is the root password for the XCP-ng server that we will use to create the VM.
$env:PKR_VAR_remote_password = 'MOT_DE_PASSE_ROOT_XCPNG'
Click the image to enlarge.
This is the password to use to connect to the XCP-ng server selected for creating the image. After checking the syntax, we ensure that all necessary variables are present using the command.
packer validate .
Click the image to enlarge.
Finally, we can start the deployment.
packer build .
Now, just let the magic happen 😊
Click the image to enlarge.
Click the image to enlarge.
You can see the VM being created and booting in real-time
Click the image to enlarge.
Click the image to enlarge.
Click the image to enlarge.
Result and Multi-Pool Copy
If everything goes well, after several minutes (17 for me), you should see our template (which we named prdtplroc501) appear in the list of templates associated with the XCP-ng server we selected (here, prdxcpsrv002).
Click the image to enlarge.
Click the image to enlarge.
Everything is ready for the next step, except for one detail. In XCP-ng, a template attached to a host can only be used on other servers that belong to the same pool as that host.
In my case, I have a pool xcp-pool with three servers, including prdxcpsrv002. Therefore, the template can be used to create VMs on prdxcpsrv001 and prdxcpsrv003. Unfortunately, it is impossible to use the template on my servers prdxcpsrv004 and prdxcpsrv005, which are in separate pools due to their significantly different hardware (I need a third server to create a second group).
We would therefore need to create two more templates on the same model, one on prdxcpsrv004 and one on prdxcpsrv005... and so run Packer twice more with different settings for the xcp-ng target. This is unnecessary, because Xen Orchestra can copy a template directly from one pool to another.
To do this, simply select the template we just created, then use the copy template function to send it to another SR belonging to a server in a different pool.
Click the image to enlarge.
After repeating this process twice, within minutes (it's very fast), I have three templates with the same name but attached to three different pools. In the next article, we will be able to deploy Kubernetes nodes across all of these pools.
Click the image to enlarge.
Note that we could easily automate, in a script, running Packer and then copying the template to all the pools managed by my Xen Orchestra instance, should the "golden image" need to be updated.
Conclusion
This is the first step completed. We now have a reference image with the prerequisites for cloning all the nodes of our future Kubernetes cluster.
Using AI here allowed me to save valuable time in generating the files specific to Packer. However, I didn't just let the AI run without trying to understand how Packer works. I took the time to review and evaluate the generated files.
Nevertheless, I got Packer-specific files that were commented and optimized for my needs. It is worth noting that I had to try several times, because the first suggestions did not work. But with a few prompts in Claude Code, and by asking it to carefully analyze the Git repository containing the Vates addon, I quickly got there.
Packer works perfectly with XCP-ng, and using a tool like Claude Code correctly can simplify onboarding and accelerate implementation. I am providing you with all the files used here on my GitHub; you will also find the file specific to the Packer subagent that I used with Claude.
We can now proceed with Terraform, but that will be covered in the next article.