Reproducible On-Prem & Cloud Image Workflows with Packer
When your team runs applications both on-premises and in the cloud, environment drift becomes a daily headache. A server in your local data center might have one version of Python or OpenSSL, while your cloud VM has another. Suddenly, a release that worked in staging breaks in production.
HashiCorp Packer solves this problem by turning machine images into versioned, repeatable code. Instead of manually configuring servers or maintaining separate scripts for every platform, you write one parameterized Packer template and build identical, tagged artifacts for both on-prem hosts and cloud environments in a single command.
- Why environment drift happens in hybrid (on-prem + cloud) setups and how immutable images fix it.
- How to standardize image versioning using Semantic Versioning, Git SHAs, and build metadata.
- How to structure a single HCL2 Packer template for multi-target builds (local Docker/VM and cloud targets).
- Hands-On Lab: Parameterize a Packer template to build both a local Docker image and a cloud-simulated target artifact tagged with a release version, then verify identical runtime versions across both builds.
- Common pitfalls, production best practices, and real-world DevOps interview questions.
1. Why Reproducible Multi-Target Images Matter
In traditional setups, teams install packages on live servers using manual commands or configuration scripts that run at boot time. Over weeks, package repositories update, and two servers built from the same script end up with different software versions.
Packer follows the Immutable Infrastructure model. You bake the operating system, runtimes, security patches, and dependencies into a read-only image once. When you need an update, you bump the version and build a brand-new image.
| Approach | How It Works | Hybrid Consistency | Rollback Speed |
|---|---|---|---|
| Manual / Boot-time scripts | Servers install packages from the internet when they start | Low – packages drift over time | Slow – must re-run scripts |
| Separate platform scripts | One Dockerfile for local, one shell script for AWS/Azure | Medium – scripts quickly go out of sync | Medium |
| Single Packer HCL2 Template | One template + shared provisioner builds all targets in parallel | High – identical runtime versions everywhere | Instant – deploy previous image tag |
2. Architecture: One Template, Multiple Targets
Packer separates where an image is built (source blocks) from what goes inside it (provisioner blocks). Because both targets run the exact same provisioning script with the exact same input variables, the resulting artifacts match down to the patch version.
Multi-Target Reproducible Image Pipeline with Packer
Packer reads one HCL2 template, runs the same provisioning steps against every target builder in parallel, and outputs version-tagged artifacts for both on-prem and cloud.
3. Standardizing Image Versioning
Never tag production images with latest. If something breaks at 2 AM, latest does not tell you which commit or runtime version is running. Instead, combine three pieces of metadata into every image:
- Release Version: Semantic version like
v1.4.0passed via CI/CD variables. - Target Environment: Clearly mark
onpremvscloudin labels and manifest files. - Build Manifest: Use Packer's
manifestpost-processor to write a JSON audit trail (packer-manifest.json) containing artifact IDs, timestamps, and custom tags.
4. Hands-On Lab: Multi-Target Parameterized Packer Build
In this lab, you will build two artifacts from a single Packer template on your local machine (no paid cloud account required): a local Docker image for on-prem hosts, and a cloud-simulated exportable tarball artifact (representing an AMI/VHD bundle). Both will be tagged with the same release version and verified for identical runtime versions.
Prerequisites
- Packer 1.10+ installed (
packer version) - Docker Desktop or Docker Engine running locally
- Bash shell (Linux, macOS, or WSL2 on Windows)
Project folder structure
packer-hybrid-lab/
├── variables.pkr.hcl # Input parameters (release version, base image)
├── app-image.pkr.hcl # Multi-target sources, build block, post-processors
├── scripts/
│ └── provision.sh # Shared provisioning script for all targets
├── verify-parity.sh # Automated runtime version verification script
└── artifacts/ # Output folder for cloud-simulated artifact & manifest
Step 1: Define parameterized variables
Create variables.pkr.hcl to centralize your version numbers and base image.
File: variables.pkr.hcl
variable "release_version" {
type = string
default = "v1.4.0"
description = "Semantic release tag applied to all built artifacts"
}
variable "base_image" {
type = string
default = "ubuntu:24.04"
description = "Pinned base OS image for reproducible builds"
}
variable "app_name" {
type = string
default = "upgradix-service"
description = "Logical application name"
}
Step 2: Create the shared provisioning script
Create scripts/provision.sh. Every target executes this exact script. Notice how we write a /etc/upgradix-build-info file inside the image so we can audit the exact runtime versions later.
File: scripts/provision.sh
#!/usr/bin/env bash
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
echo "[Provisioner] Installing pinned runtime packages for ${BUILD_TARGET}..."
apt-get update -y
apt-get install -y --no-install-recommends \
python3 \
curl \
ca-certificates
# Clean apt cache to keep images small and consistent
rm -rf /var/lib/apt/lists/*
# Record exact runtime versions inside the image
PYTHON_VER=$(python3 --version)
CURL_VER=$(curl --version | head -n 1)
cat <<EOF > /etc/upgradix-build-info
APP_NAME=${APP_NAME}
RELEASE_VERSION=${RELEASE_VERSION}
BUILD_TARGET=${BUILD_TARGET}
PYTHON_VERSION=${PYTHON_VER}
CURL_VERSION=${CURL_VER}
EOF
echo "[Provisioner] Completed build metadata:"
cat /etc/upgradix-build-info
Step 3: Write the multi-target Packer template
Create app-image.pkr.hcl. We define two source blocks: one commits a local Docker image for on-prem use, and the second exports a standalone filesystem archive (.tar) simulating a cloud VM/AMI artifact bundle. Both share one build block.
File: app-image.pkr.hcl
packer {
required_version = ">= 1.10.0"
required_plugins {
docker = {
version = ">= 1.0.8"
source = "github.com/hashicorp/docker"
}
}
}
# Target 1: On-Prem Local Docker Image
source "docker" "onprem_local" {
image = var.base_image
commit = true
changes = [
"LABEL org.opencontainers.image.version=${var.release_version}",
"LABEL com.upgradix.target=onprem-docker"
]
}
# Target 2: Cloud-Simulated Artifact (Exported Bundle)
source "docker" "cloud_simulated" {
image = var.base_image
export_path = "artifacts/${var.app_name}-cloud-${var.release_version}.tar"
}
build {
name = "hybrid-release"
sources = [
"source.docker.onprem_local",
"source.docker.cloud_simulated"
]
provisioner "shell" {
script = "scripts/provision.sh"
environment_vars = [
"APP_NAME=${var.app_name}",
"RELEASE_VERSION=${var.release_version}",
"BUILD_TARGET=${source.name}"
]
}
# Tag the on-prem Docker image with the release version
post-processor "docker-tag" {
only = ["docker.onprem_local"]
repository = "upgradix/${var.app_name}"
tags = [var.release_version]
}
# Generate a unified manifest for both targets
post-processor "manifest" {
output = "artifacts/packer-manifest.json"
strip_path = true
custom_data = {
release_version = var.release_version
app_name = var.app_name
}
}
}
source "docker" "cloud_simulated" with source "amazon-ebs" "aws_cloud" or source "azure-arm" "azure_cloud". Your provisioner block and variables.pkr.hcl stay 100% unchanged!Step 4: Initialize, validate, and build both targets
Create the artifacts directory, initialize Packer plugins, and run the build with your release version.
Run the multi-target build
mkdir -p artifacts
packer init .
packer validate -var "release_version=v1.4.0" .
packer build -var "release_version=v1.4.0" .
Expected output (abbreviated)
hybrid-release.docker.onprem_local: output will be in this color. hybrid-release.docker.cloud_simulated: output will be in this color. ==> hybrid-release.docker.onprem_local: Tagging image: upgradix/upgradix-service:v1.4.0 ==> hybrid-release.docker.cloud_simulated: Exporting the container to artifacts/upgradix-service-cloud-v1.4.0.tar Build 'hybrid-release.docker.onprem_local' finished after 24 seconds. Build 'hybrid-release.docker.cloud_simulated' finished after 25 seconds. ==> Builds finished. The artifacts of successful builds are: --> hybrid-release.docker.onprem_local: Imported Docker image: upgradix/upgradix-service:v1.4.0 --> hybrid-release.docker.cloud_simulated: Exported Docker file: artifacts/upgradix-service-cloud-v1.4.0.tar
Step 5: Verify identical runtime versions across both builds
Now run verify-parity.sh to inspect the on-prem Docker image and extract the metadata from the cloud-simulated tarball, confirming both have the exact same Python and curl versions.
File: verify-parity.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="${1:-v1.4.0}"
APP="upgradix-service"
echo "=== 1. On-Prem Docker Image Metadata ==="
ONPREM_INFO=$(docker run --rm "upgradix/${APP}:${VERSION}" cat /etc/upgradix-build-info)
echo "$ONPREM_INFO"
echo ""
echo "=== 2. Cloud-Simulated Artifact Metadata ==="
CLOUD_INFO=$(tar -xOf "artifacts/${APP}-cloud-${VERSION}.tar" etc/upgradix-build-info)
echo "$CLOUD_INFO"
ONPREM_PY=$(echo "$ONPREM_INFO" | grep "^PYTHON_VERSION=")
CLOUD_PY=$(echo "$CLOUD_INFO" | grep "^PYTHON_VERSION=")
echo ""
if [ "$ONPREM_PY" = "$CLOUD_PY" ]; then
echo "PASS: Identical runtime verified across On-Prem and Cloud ($ONPREM_PY)"
else
echo "FAIL: Runtime mismatch detected!"
exit 1
fi
Run verification
chmod +x verify-parity.sh
./verify-parity.sh v1.4.0
Expected output
=== 1. On-Prem Docker Image Metadata === APP_NAME=upgradix-service RELEASE_VERSION=v1.4.0 BUILD_TARGET=onprem_local PYTHON_VERSION=Python 3.12.3 CURL_VERSION=curl 8.5.0 (x86_64-pc-linux-gnu) === 2. Cloud-Simulated Artifact Metadata === APP_NAME=upgradix-service RELEASE_VERSION=v1.4.0 BUILD_TARGET=cloud_simulated PYTHON_VERSION=Python 3.12.3 CURL_VERSION=curl 8.5.0 (x86_64-pc-linux-gnu) PASS: Identical runtime verified across On-Prem and Cloud (PYTHON_VERSION=Python 3.12.3)
5. Step-by-Step Execution Breakdown
variables.pkr.hcl and overrides release_version with your CLI or CI/CD flag (v1.4.0).onprem_local and cloud_simulated builders simultaneously using the same pinned ubuntu:24.04 base.scripts/provision.sh, installing identical runtimes and writing /etc/upgradix-build-info.upgradix/upgradix-service:v1.4.0, while the cloud target is exported to artifacts/upgradix-service-cloud-v1.4.0.tar.packer-manifest.json, and your verification script confirms both artifacts match before promoting them to production.ubuntu:latest or unpinned package versions can cause builds run two days apart to differ. Always pin your base image tag (or SHA256 digest) and critical package versions in production.6. Hands-On Practice
Run the Packer build again with release_version=v1.5.0 without editing any .pkr.hcl files, then run ./verify-parity.sh v1.5.0.
Hint: Pass -var "release_version=v1.5.0" to packer build.
Add a new variable git_sha to variables.pkr.hcl, write it into /etc/upgradix-build-info, and include it in the manifest post-processor's custom_data.
Expected result: artifacts/packer-manifest.json records both release_version and git_sha.
Add a second shell provisioner that runs only on the cloud_simulated target to simulate installing a cloud monitoring agent.
Hint: Use the only = ["docker.cloud_simulated"] attribute inside the provisioner block.
7. Interview Questions
Answer: Packer uses a single HCL2 template with multiple source blocks feeding into one shared build block. All targets execute the exact same provisioners and scripts at build time, baking immutable, version-tagged images instead of relying on mutable runtime configuration.
Answer: A Source/Builder creates the temporary machine or container for a specific platform (Docker, AWS AMI, VMware). A Provisioner installs software and configures the OS inside that machine (Shell, Ansible). A Post-Processor runs after the image is built to tag, compress, upload, or log metadata like a build manifest.
Answer: The manifest post-processor outputs a machine-readable JSON file containing every generated artifact ID (such as AMI IDs or Docker image digests) and custom version tags. Downstream deployment tools like Terraform or ArgoCD can read this file to deploy the exact verified build automatically.
Conclusion
Standardizing image builds with Packer removes the guesswork from hybrid infrastructure. By parameterizing your release versions, sharing one provisioning pipeline across targets, and verifying runtime parity automatically, you guarantee that what passes testing locally will behave identically in the cloud.
Start with the two-target workflow in this lab, wire it into your CI/CD pipeline, and swap in your production VMware, AWS, or Azure sources when you are ready to scale.
Official Documentation
- HashiCorp Packer Documentation – HCL2 Templates
- HashiCorp Packer Plugins – Docker Builder
- HashiCorp Packer Reference – Manifest Post-Processor
Upgradix by Shrash Studio – Learn Technology. Build Your Future.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.