Skip to main content

Build VMware templates with Packer, Ansible and Terraform

10 min read
#packer #ansible #terraform #vmware #linux

Packer, Ansible and Terraform building VMware templates

These are the steps for my VMware template upgrade using Packer project.

Overview

This project rebuilds the RHEL 9 and Ubuntu 22.04 VMware templates every month and deploys VMs from them.

  • Packer clones the current template in vCenter, gives the clone a temporary IP, runs Ansible on it, shuts it down and converts it to a new template.
  • Ansible patches the clone, cleans it up and renames it to include the OS version.
  • Terraform creates VMs from the finished template.
current template --Packer clone--> <name>_building --Ansible patch, clean, rename--> new template --Terraform--> new VM

The current template is never changed, so it stays available as a fallback.

Placeholders

Everything in <...> is a placeholder. Replace it with your own value.

Placeholder Meaning
<REPO_URL>, <PLAYBOOKS_REPO_URL> Git URLs of this project and of the shared Ansible roles
<SITE_A>, <SITE_B> Short site names used in file names, one per vCenter
<VCENTER_HOST>, <VCENTER_USER> vCenter address and login
<DATACENTER>, <CLUSTER>, <FOLDER> vCenter inventory names
<DATASTORE> A single datastore, used by Packer
<DATASTORE_CLUSTER> A datastore cluster, used by Terraform
<VAPP>, <PORT_GROUP> vApp and network port group
<BUILD_IP>, <VM_IP>, <GATEWAY>, <DNS_1>, <DNS_2> Network values
<DOMAIN> DNS domain
<SSH_USER>, <SSH_PASSWORD>, <VAULT_PASSWORD> RHEL template login and Ansible vault password
<JUMPBOX> The server that holds the root SSH key for Ubuntu
<RHEL_TEMPLATE>, <UBUNTU_TEMPLATE> Names of existing templates

Project layout

packer/
  common.pkr.hcl            plugin versions, template date
  variables.pkr.hcl         input variables
  rhel9.pkr.hcl             RHEL 9 build
  ubuntu2204.pkr.hcl        Ubuntu 22.04 build
  <SITE_A>.pkrvars.hcl      values for site A
  <SITE_B>.pkrvars.hcl      values for site B
  ansible/rhel9.yml         RHEL playbook
  ansible/ubuntu2204.yml    Ubuntu playbook
  ansible/rename_template.yml
  vault-pass.sh             passes VAULT_PASS to Ansible
  requirements.txt          Python packages
  requirements.yml          Ansible collections
  .env                      your credentials, never committed
terraform/build_template_test/
  rhel/                     test VM from the RHEL template
  ubuntu/                   test VM from the Ubuntu template

Part 1: Installation

Do this once on each machine that runs the tools.

1.1 What you need first

  • Linux or WSL with git, curl, unzip and Python 3 with venv
  • Internet access to GitHub, PyPI, Ansible Galaxy and HashiCorp, or a proxy for them
  • Network access to vCenter on port 443, and to the build IP on port 22
  • A vCenter account that can clone, customize, rename, delete and convert VMs to templates
  • One free static IP per site for the build VM
Build Where to run it
RHEL 9 Any machine that meets the list above. It logs in with a username and password.
Ubuntu 22.04 Only on <JUMPBOX>. It logs in as root with an SSH key that must stay there.
Terraform Any machine that can reach vCenter. It never connects to the VM itself.

1.2 Get the project

git clone <REPO_URL> ~/vm-templates
cd ~/vm-templates
git checkout dev

1.3 Install Packer

This installs one binary in your home folder and needs no root access.

V=1.16.3
mkdir -p ~/bin ~/packer-download
cd ~/packer-download
curl -fLO https://releases.hashicorp.com/packer/${V}/packer_${V}_linux_amd64.zip
curl -fLO https://releases.hashicorp.com/packer/${V}/packer_${V}_SHA256SUMS
sha256sum --ignore-missing -c packer_${V}_SHA256SUMS

The last command must print OK. Then:

unzip packer_${V}_linux_amd64.zip packer -d ~/bin
export PATH="$HOME/bin:$PATH"
packer version

Add the export PATH line to ~/.bashrc or ~/.zshrc to keep it.

1.4 Install Ansible

cd ~/vm-templates/packer
python3 -m venv ~/.venv/packer
~/.venv/packer/bin/pip install -r requirements.txt
~/.venv/packer/bin/ansible-galaxy collection install -r requirements.yml
~/.venv/packer/bin/python -c 'import pyVmomi; print("pyvmomi ok")'

requirements.txt keeps pyvmomi on version 8, because version 9 breaks the VMware collection.

On a shared machine, the ansible-galaxy command can affect other playbooks that use the same account. Check which version is installed first with ansible-galaxy collection list community.vmware.

1.5 Create the credentials file

Create ~/vm-templates/packer/.env:

PKR_VAR_vcenter_username='<VCENTER_USER>'
PKR_VAR_ansible_playbook='/home/<you>/.venv/packer/bin/ansible-playbook'
PKR_VAR_ssh_username='<SSH_USER>'
PKR_VAR_ssh_password='<SSH_PASSWORD>'
VAULT_PASS='<VAULT_PASSWORD>'
PKR_VAR_playbooks_repo='<PLAYBOOKS_REPO_URL>'
chmod 600 .env
  • The ssh_*, VAULT_PASS and playbooks_repo lines are only needed for RHEL.
  • The vCenter password is not in this file. You type it at the start of each session.
  • .env is in .gitignore. Never commit it.

1.6 Download the Packer plugins

cd ~/vm-templates/packer
packer init .
packer plugins installed

If packer init fails with permission denied in /tmp, then /tmp does not allow programs to run. Use another folder, and add the same TMPDIR line to .env:

mkdir -p ~/temp
export TMPDIR=~/temp
packer init .

1.7 Install Terraform

There is nothing to install by hand. terraswitch.sh downloads the right Terraform version into .bin the first time you run it, then passes your arguments to Terraform.

cd ~/vm-templates/terraform/build_template_test/ubuntu
./terraswitch.sh version

Part 2: Configure the sites

2.1 Packer

Each site has one file, <SITE>.pkrvars.hcl:

vcenter_server = "<VCENTER_HOST>"

datacenter      = "<DATACENTER>"
cluster         = "<CLUSTER>"
datastore       = "<DATASTORE>"
folder          = "<FOLDER>"
network         = "<PORT_GROUP>"
rhel9_template  = "<RHEL_TEMPLATE>"
ubuntu_template = "<UBUNTU_TEMPLATE>"

build_ip      = "<BUILD_IP>"
build_netmask = 28
build_gateway = "<GATEWAY>"
dns_servers   = ["<DNS_1>", "<DNS_2>"]
dns_suffixes  = ["<DOMAIN>"]

rhel9_template and ubuntu_template are the existing templates to clone from.

2.2 Terraform

Each OS folder has one terraform.tfvars.template.<SITE> per site:

VCENTER_URL = "<VCENTER_HOST>"
USER        = "<VCENTER_USER>"

DATACENTER = "<DATACENTER>"
CLUSTER    = "<CLUSTER>"
DATASTORE  = "<DATASTORE_CLUSTER>"
vAPP       = "<VAPP>"
VLAN1      = "<PORT_GROUP>"
VMTEMPLATE = "<UBUNTU_TEMPLATE>"

number_of_cpu   = "2"
number_of_cores = "2"
memory_in_mb    = "4096"
domain          = "<DOMAIN>"
vm_list         = ["testubuntutemplate"]
disk_count      = 1

ipaddress             = ["<VM_IP>"]
network_netmask_index = "28"
gateway               = "<GATEWAY>"
dns                   = ["<DNS_1>", "<DNS_2>"]
dns_suffix            = ["<DOMAIN>"]
  • VMTEMPLATE is the template to deploy, so set it to the one Packer just built.
  • DATASTORE must be a datastore cluster. A single datastore does not work here.
  • disk_count must match the number of disks in the template.
  • vm_list and ipaddress are matched in order. Two VMs need two names and two IPs.
  • Do not use Packer’s build IP for a VM.
  • The firmware (BIOS or EFI) is read from the template, so you do not set it.

Part 3: Build a template with Packer

3.1 Start of every session

cd ~/vm-templates/packer
git pull
set -a; source .env; set +a
read -s PW; echo

read -s PW waits for you to type the vCenter password and does not show it. If the password changes later, run that line again.

For Ubuntu, also check on <JUMPBOX> that the root key is loaded:

ssh-add -l

3.2 Check the configuration

This changes nothing in vCenter.

packer validate -only=vsphere-clone.rhel9 -var-file=<SITE_A>.pkrvars.hcl -var="PW=$PW" .
packer validate -only=vsphere-clone.ubuntu2204 -var-file=<SITE_B>.pkrvars.hcl -var="PW=$PW" .

3.3 Test build without patching

Use this to check that everything works. Delete the resulting template afterwards, because it is not patched.

packer build -only=vsphere-clone.ubuntu2204 -force -on-error=ask -var-file=<SITE_B>.pkrvars.hcl -var="PW=$PW" -var run_patch=false .

3.4 Real build

RHEL 9:

packer build -only=vsphere-clone.rhel9 -force -on-error=ask -var-file=<SITE_A>.pkrvars.hcl -var="PW=$PW" .

Ubuntu 22.04, on <JUMPBOX>:

packer build -only=vsphere-clone.ubuntu2204 -force -on-error=ask -var-file=<SITE_B>.pkrvars.hcl -var="PW=$PW" .

Run builds at the same site one after another, because they share the build IP.

Part of the command Meaning
-only= Which OS to build. Always needed, because both builds are in this folder.
-var-file= Which site to build at
-force Replace a leftover _building VM with the same name
-on-error=ask Pause when something fails
-var="PW=$PW" The vCenter password you typed
-var run_patch=false Skip patching
. Use the Packer files in this folder

3.5 When a build fails

Packer stops and asks what to do:

Key What it does
r Try the step again. Fix the problem in a second terminal first.
a Stop and keep the VM so you can look at it
c Stop and delete the VM

After a successful r, Packer can still end with errored and no artifacts were created, because it remembers the first failure. Check the Ansible recap for failed=0, then check in vCenter that the template exists.

To cancel a running build, press Ctrl+C once and wait for Packer to delete the VM.

3.6 Template names

OS Example
RHEL 9 TEMPLATE_RHEL9.9_SECURE-04Dec2026
Ubuntu 22.04 TEMPLATE_UBUNTU22.04.5-04Dec2026

Ansible reads the OS version after patching. The date is in UTC, so an evening build can get the next day’s date.

A second build on the same day with the same OS version stops with already exists. Delete or rename the first template, then run the build again.

Part 4: Deploy a VM with Terraform

This example uses Ubuntu. For RHEL, use the rhel folder.

4.1 Prepare

cd ~/vm-templates/terraform/build_template_test/ubuntu
cp terraform.tfvars.template.<SITE_B> terraform.tfvars
read -s PW; echo
./terraswitch.sh init

Open terraform.tfvars and check VMTEMPLATE, vm_list and ipaddress.

4.2 Plan

./terraswitch.sh plan -var="PW=$PW"

For one new VM, the plan must end with Plan: 1 to add, 0 to change, 0 to destroy. If it wants to destroy or change something you did not expect, stop.

4.3 Create the VM

./terraswitch.sh apply -var="PW=$PW"

Read the plan again and type yes.

4.4 Check the VM

ssh <user>@<VM_IP>
ls /etc/ssh/ssh_host_*
cat /etc/machine-id
hostname

You should see SSH host keys, a 32-character machine ID and the name from vm_list. The keys and the ID are created at first boot, so every VM has its own.

If SSH says REMOTE HOST IDENTIFICATION HAS CHANGED and you know this IP was used by an older VM, remove the old key and connect again:

ssh-keygen -R <VM_IP>

4.5 Remove the test VM

./terraswitch.sh destroy -var="PW=$PW"

Check that the plan lists only the test VM, then type yes.

4.6 Keep the state safe

Terraform records the VMs it manages in terraform.tfstate and terraform.tfstate.d/.

  • Never copy these files into another folder. Running destroy there would delete the real VMs.
  • Use a separate workspace for each VM or group of VMs that you want to keep:
./terraswitch.sh workspace list
./terraswitch.sh workspace new <name>
./terraswitch.sh workspace select <name>
  • Changing vm_list in a workspace that already has a VM makes Terraform plan to destroy the old one.
  • Delete VMs with destroy, not in vCenter, so the state stays correct.

Part 5: Monthly checklist

  1. In each <SITE>.pkrvars.hcl, set rhel9_template and ubuntu_template to the newest good templates.
  2. Run the real build for each OS and site.
  3. Check in vCenter that each new template exists and that no _building VM is left.
  4. Set VMTEMPLATE in the Terraform files to the new names.
  5. Deploy a test VM, check it, then destroy it.
  6. Delete old templates when you no longer need them as a fallback.

Part 6: Change what goes into a template

Edit ansible/rhel9.yml or ansible/ubuntu2204.yml. Add tasks after patching and before Template cleanup. On RHEL, they must also come before the task that unregisters the VM, because the package repositories are gone after that.

    - name: Run uptime
      ansible.builtin.command: uptime
      register: uptime_out
      changed_when: false

    - name: Show uptime
      ansible.builtin.debug:
        msg: "{{ uptime_out.stdout }}"

Keep anything that is unique to one server, such as agent registration, out of the template. Do that after the VM is deployed.

RHEL roles come from <PLAYBOOKS_REPO_URL>. Push role changes before you build, because Packer downloads a fresh copy each time.

Part 7: Troubleshooting

Problem What to check
Packer stays at Waiting for IP In the template, the network adapter must have Connected and Connect At Power On ticked. Also check that VMware Tools is running and guest customization is allowed.
Packer stays at Waiting for SSH The build IP must be free and reachable on port 22. For Ubuntu, run ssh-add -l.
ansible-playbook: executable file not found Set PKR_VAR_ansible_playbook in .env, then load .env again.
No longer supported. Use pyVmomi.VmomiJSONEncoder Run pip install -r requirements.txt in the venv to get pyvmomi 8.
packer init says permission denied in /tmp Set TMPDIR as in step 1.6.
Ansible says failed to transfer file Keep ansible_ssh_transfer_method=piped in the Packer file.
vCenter login fails The password may have changed. Run read -s PW; echo again.
Terraform cannot find the datastore DATASTORE must be a datastore cluster.
A new VM does not boot Check that its firmware matches the template.

Part 8: Security

  • Keep passwords only in .env with chmod 600, or type them with read -s.
  • Never commit .env, private keys or Terraform state files.
  • Keep the Ubuntu root key on <JUMPBOX>. Do not copy it to a laptop.
  • Do not share full Packer logs. The Executing Ansible: line can show part of the vCenter password.
  • -var="PW=$PW" makes the password visible in the process list to other users on the same machine while the command runs.
  • The Packer and Terraform files here skip the vCenter certificate check (insecure_connection and allow_unverified_ssl). Use trusted certificates if you can.