3 December 2026 · 14 min read · Download as PDF
GitHub Actions, Packer and Terraform: build a golden AMI on every merge, deploy it with Terraform, with or without HCP Packer
GitHub Actions runs Packer to build the image, Terraform deploys it. The one design decision is how Terraform learns which image to use: HCP Packer channels, or plain AWS with a Parameter Store entry you move on release. Both pipelines, no stored secrets, and which one I'd pick for your team.
Three tools, one pipeline. GitHub Actions runs Packer when the image template changes, Packer builds a golden Amazon Machine Image (AMI), and Terraform launches servers from it. Building and deploying are the easy parts. The decision that shapes everything else is the handoff: how does Terraform know which AMI to use, and how do you move production to a new one on purpose? You can answer it with HCP Packer, the image registry in HashiCorp Cloud Platform (HCP), or with plain AWS: a Systems Manager Parameter Store entry your workflow updates. This guide builds both, with no long-lived secret stored in GitHub, and ends with which one I'd pick for your team.
TL;DR
- The pipeline: a pull request runs
packer validate; a merge tomainbuilds the AMI and makes it thedevimage; a release tag promotes the AMI that commit built toproductionwithout rebuilding; Terraform deploys whateverproductionpoints at. - No secrets in GitHub: AWS and HCP both trust GitHub's short-lived OpenID Connect (OIDC) token, through
aws-actions/configure-aws-credentialsandhashicorp/hcp-auth-action. - With HCP Packer: the template's
hcp_packer_registryblock records every build, channels name what each environment gets, and Terraform reads a channel with thehcp_packer_versionandhcp_packer_artifactdata sources. You also get ancestry and revocation across images and clouds. - Without HCP: tag each AMI with its commit, write the AMI ID to an AWS Systems Manager (SSM) parameter per environment, and let Terraform read the parameter, or let the launch template resolve it with
resolve:ssm:. Promotion is overwriting a parameter, and Parameter Store keeps its history. - What I'd do: one AWS account and a small team: plain AWS. Several clouds, many image consumers, or an auditor asking which servers run a revoked image: HCP Packer.
- Model Context Protocol (MCP) is an aside: HashiCorp's Terraform MCP server lets an AI assistant look up current provider and module docs, but nothing here needs it.
The pipeline
Event | GitHub Actions runs | Result |
|---|---|---|
Pull request |
| A template with a syntax or configuration error never merges. Nothing is built or recorded. (Validation doesn't run the build, so a bad provisioner still shows up on |
Merge to |
| A new AMI, tagged with its commit. It becomes the |
Tag | A promote step, no build |
|
| (your deploy pipeline) | Servers launch from the |
Promoting by tag rather than rebuilding means production gets the exact image built from that commit, the one you've been able to try on dev, not a second build of it. Booting it and running a smoke test before you tag is up to you; this pipeline doesn't. Tag only after that commit's main build has finished: a tag on a commit that is still building, failed or never built has nothing to promote, and the promote step fails, which is what you want.
With HCP Packer or without: the handoff
HCP Packer | Plain AWS (tags and Parameter Store) | |
|---|---|---|
Where "which image" lives | A channel in a bucket | An SSM parameter per environment, holding an AMI ID |
Record of each build | Automatic: commit, workflow run, builder, region, labels | Whatever you put in AMI tags (commit, date, source AMI) |
Promote to production | Move the channel (UI, API or Terraform) | Overwrite the parameter ( |
History and rollback | Channel assignment history; move it back | Parameter versions; put the previous value back |
Terraform reads it with |
|
|
Several clouds and regions | One bucket tracks AWS, Azure, Google Cloud and more | One parameter per region and cloud, and you keep them in step |
Images built on images | Tracks parents; can revoke a base and flag its children | You trace it yourself, through tags |
Bad image | Revoke it; channels roll back; Terraform sees | Put the old ID back, deprecate or deregister the AMI |
What you sign up for | An HCP account and its billing, a service principal | Nothing new: AWS Identity and Access Management (IAM) and Parameter Store you already have |
What I'd do
- A small team, one AWS account, a handful of images: plain AWS. Tags plus one parameter per environment cover it, and there's nothing new to pay for or learn.
- Several AWS accounts or regions, still AWS only: plain AWS still works (share the AMI, keep a parameter per account and region), but the bookkeeping grows with every account. This is where HCP Packer starts to earn its place.
- More than one cloud, or images built on images: HCP Packer. One channel for the AMI, the Azure image and the Google Cloud image, plus parent tracking, is hard to rebuild yourself.
- Governance: if an auditor will ask "which running servers use the image with that vulnerability?", HCP Packer's revocation and ancestry answer it. With plain AWS, you'd query AMI tags and instances yourself.
- Cost: plain AWS adds nothing beyond the AMIs' snapshots, which both paths pay for. HCP Packer is a separately billed HCP service; check HashiCorp's current pricing for your volume before choosing it on features alone.
Start plain if you're unsure. The template, the workflow and the Terraform change little if you move to HCP Packer later: you add one block to the template and swap one data source.
The Packer template
The template builds an Ubuntu AMI and tags it with the commit that built it, so either handoff can find it again. The hcp_packer_registry block is the only HCP-specific part: leave it out (and the channels variable) for the plain AWS path. It sits at the top level of the file, where Packer 1.13.0 and later expect it; inside build still works but is deprecated.
packer { required_version = ">= 1.15.0" required_plugins { amazon = { source = "github.com/hashicorp/amazon" version = "1.8.4" } }}variable "region" { type = string default = "us-east-1"}variable "git_sha" { type = string # set by the workflow: PKR_VAR_git_sha}# HCP Packer only: channels to move to this version once the build completes.variable "channels" { type = list(string) default = []}# HCP Packer only. Delete this block for the plain AWS path.hcp_packer_registry { bucket_name = "web-base" description = "Ubuntu 24.04 base image for the web tier, built from main." bucket_labels = { team = "platform" os = "ubuntu-24.04" } channels = var.channels}source "amazon-ebs" "ubuntu" { region = var.region instance_type = "t3.small" ssh_username = "ubuntu" ami_name = "web-base-{{timestamp}}" source_ami_filter { filters = { name = "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*" virtualization-type = "hvm" } owners = ["099720109477"] # Canonical most_recent = true } tags = { Image = "web-base" GitSha = var.git_sha }}build { sources = ["source.amazon-ebs.ubuntu"] provisioner "shell" { inline = [ "sudo apt-get update", "sudo apt-get install -y nginx", ] }}With HCP Packer, the bucket name must be 3 to 36 letters, numbers and hyphens, and the description at most 255 characters; Packer checks both before it builds.
Authentication: no secrets in GitHub
Both paths need AWS, to launch the temporary build instance and save the AMI. The HCP path also needs HCP, to record the build and move channels. Both can trust GitHub's OIDC token, which GitHub issues per job when the job has id-token: write permission, so nothing long-lived is stored, leaked or rotated.
AWS: an IAM role for GitHub
Add GitHub's OIDC provider to IAM and create a role whose trust policy accepts only the jobs that need it: audience sts.amazonaws.com, and subject repo:acme/golden-images:ref:refs/heads/main for the build. The plain AWS path's promote job also needs AWS, so add its subject too. A job that uses a GitHub environment gets an environment subject instead, here repo:acme/golden-images:environment:production. Give the role the Amazon Elastic Compute Cloud (EC2) permissions the Amazon plugin's documentation lists as its minimum for building an AMI, plus ssm:PutParameter on your image parameters for the plain path. Store the role's Amazon Resource Name (ARN) as a repository variable: it isn't a secret.
HCP: workload identity federation
Create a service principal in your HCP project with the Contributor role (it pushes metadata and moves channels), and a workload identity provider that trusts only the refs you publish from:
hcp iam service-principals create "packer-ci" --project "$HCP_PROJECT_ID"# SP_ID: the service principal's ID, printed by the create command abovehcp projects add-binding \ --project="$HCP_PROJECT_ID" \ --member="$SP_ID" \ --role=roles/contributorhcp iam workload-identity-providers create-oidc "github-packer" \ --service-principal="iam/project/$HCP_PROJECT_ID/service-principal/packer-ci" \ --issuer="https://token.actions.githubusercontent.com" \ --conditional-access='jwt_claims.repository == "acme/golden-images" and (jwt_claims.ref == "refs/heads/main" or jwt_claims.ref matches "^refs/tags/v")'The conditional access statement reads any claim in GitHub's token with the jwt_claims. prefix, and combines them with and, or, parentheses and matches. Trusting the whole repository would be weaker than it looks: branch protection controls who can merge, not which branches can run a workflow that asks for a token. Protect the v* tags with a repository ruleset as well. In the workflow, hashicorp/hcp-auth-action trades the token for a short-lived credential file and sets HCP_CRED_FILE, which Packer reads from version 1.14.2 (September 2025). Can't use federation? Store a service principal key as HCP_CLIENT_ID and HCP_CLIENT_SECRET and rotate it like a password.
The workflow with HCP Packer
# .github/workflows/web-base-image.ymlname: web-base imageon: pull_request: paths: ["packer/**"] push: branches: [main] tags: ["v*"] paths: ["packer/**"] # GitHub ignores path filters for tag pushes, so tags always runpermissions: contents: readenv: PACKER_VERSION: "1.16.3" TEMPLATE: packer/web-base.pkr.hcljobs: validate: runs-on: ubuntu-latest env: HCP_PACKER_REGISTRY: "OFF" # check the template without talking to HCP Packer PKR_VAR_git_sha: ${{ github.sha }} steps: - uses: actions/checkout@v7 - uses: hashicorp/setup-packer@v3 with: version: ${{ env.PACKER_VERSION }} - run: packer init "$TEMPLATE" - run: packer fmt -check "$TEMPLATE" - run: packer validate "$TEMPLATE" build: if: github.event_name == 'push' && github.ref == 'refs/heads/main' needs: validate runs-on: ubuntu-latest concurrency: # one build at a time, so an older build can't move dev back group: web-base-image-main cancel-in-progress: false permissions: contents: read id-token: write # lets the job ask GitHub for an OIDC token steps: - uses: actions/checkout@v7 - uses: hashicorp/setup-packer@v3 with: version: ${{ env.PACKER_VERSION }} - id: hcp uses: hashicorp/hcp-auth-action@v0 with: workload_identity_provider: ${{ vars.HCP_WORKLOAD_IDENTITY_PROVIDER }} - uses: aws-actions/configure-aws-credentials@v6 with: role-to-assume: ${{ vars.PACKER_AWS_ROLE_ARN }} aws-region: us-east-1 - run: packer init "$TEMPLATE" - run: packer build -color=false -on-error=abort "$TEMPLATE" env: HCP_PROJECT_ID: ${{ steps.hcp.outputs.project_id }} HCP_PACKER_BUILD_FINGERPRINT: ${{ github.sha }} PKR_VAR_git_sha: ${{ github.sha }} PKR_VAR_channels: '["dev"]' promote: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') needs: validate runs-on: ubuntu-latest environment: production # add required reviewers here for a human gate permissions: contents: read id-token: write steps: - id: hcp uses: hashicorp/hcp-auth-action@v0 with: workload_identity_provider: ${{ vars.HCP_WORKLOAD_IDENTITY_PROVIDER }} set_access_token: true - name: Point production at the version this commit built env: TOKEN: ${{ steps.hcp.outputs.access_token }} ORG: ${{ steps.hcp.outputs.organization_id }} PROJECT: ${{ steps.hcp.outputs.project_id }} run: | curl --fail-with-body -X PATCH \ "https://api.cloud.hashicorp.com/packer/2023-01-01/organizations/$ORG/projects/$PROJECT/buckets/web-base/channels/production" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{\"version_fingerprint\": \"$GITHUB_SHA\", \"update_mask\": \"versionFingerprint\"}"- The fingerprint is the commit. HCP Packer keys each version by its fingerprint. If a build fails half-way, re-running the job continues the same incomplete version; once it's complete, building the same commit again fails on purpose. (The
setup-packerREADME uses the run ID and attempt instead, which gives every attempt a fresh version.) - Channels move after the build completes. Packer 1.15.0 added
channelsto the registry block. The channels must already exist (create them once in the HCP Packer UI or with Terraform'shcp_packer_channel, withrestricted = trueonproductionso only people who can manage channels see it). A failed assignment is logged, not fatal: look forAssigning version … to channel `dev`in the job log. - Pull requests never touch HCP Packer:
HCP_PACKER_REGISTRY=OFF, and the job has noid-tokenpermission. Pull requests from forks get no repository secrets and only a read-onlyGITHUB_TOKEN. - Pinned versions: Packer 1.16.3 (released 25 Nov 2026) and Amazon plugin 1.8.4, so a new release can't change your images unannounced. The actions use major-version tags; pin them to commit SHAs if your policy asks for it.
- Metadata comes free: Packer notices it's running in GitHub Actions and records the repository, commit, ref, actor and a link to the run.
The workflow without HCP
Same triggers and validate job. Delete the hcp_packer_registry block from the template, drop the HCP steps, and let the jobs write the AMI ID to Parameter Store. Parameters with the data type aws:ec2:image are checked by AWS to hold a real AMI ID.
build: if: github.event_name == 'push' && github.ref == 'refs/heads/main' needs: validate runs-on: ubuntu-latest concurrency: group: web-base-image-main cancel-in-progress: false permissions: contents: read id-token: write steps: - uses: actions/checkout@v7 - uses: hashicorp/setup-packer@v3 with: version: ${{ env.PACKER_VERSION }} - uses: aws-actions/configure-aws-credentials@v6 with: role-to-assume: ${{ vars.PACKER_AWS_ROLE_ARN }} aws-region: us-east-1 - run: packer init "$TEMPLATE" - run: packer build -color=false -on-error=abort "$TEMPLATE" env: PKR_VAR_git_sha: ${{ github.sha }} - name: Make it the dev image run: | AMI=$(aws ec2 describe-images --owners self \ --filters "Name=tag:Image,Values=web-base" "Name=tag:GitSha,Values=$GITHUB_SHA" \ --query 'sort_by(Images, &CreationDate)[-1].ImageId' --output text) aws ssm put-parameter --name /images/web-base/dev --type String \ --data-type aws:ec2:image --value "$AMI" --overwrite promote: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') needs: validate runs-on: ubuntu-latest environment: production permissions: contents: read id-token: write steps: - uses: aws-actions/configure-aws-credentials@v6 with: role-to-assume: ${{ vars.PACKER_AWS_ROLE_ARN }} aws-region: us-east-1 - name: Point production at the AMI this commit built run: | AMI=$(aws ec2 describe-images --owners self \ --filters "Name=tag:Image,Values=web-base" "Name=tag:GitSha,Values=$GITHUB_SHA" \ --query 'sort_by(Images, &CreationDate)[-1].ImageId' --output text) if [ "$AMI" = "None" ]; then echo "No AMI was built from $GITHUB_SHA"; exit 1; fi aws ssm put-parameter --name /images/web-base/production --type String \ --data-type aws:ec2:image --value "$AMI" --overwriteThe commit tag does the job of HCP Packer's fingerprint: the promote step finds the AMI that exact commit built and refuses when there is none. Each put-parameter --overwrite creates a new parameter version, so the recent history of what production pointed at, and when, stays in Parameter Store. It keeps the last 100 versions of a parameter; for a longer audit trail, rely on AWS CloudTrail, which records every PutParameter call.
Terraform deploys the image
With HCP Packer, Terraform asks for the channel:
data "hcp_packer_version" "web_base" { bucket_name = "web-base" channel_name = "production"}data "hcp_packer_artifact" "web_base" { bucket_name = "web-base" version_fingerprint = data.hcp_packer_version.web_base.fingerprint platform = "aws" region = "us-east-1"}resource "aws_launch_template" "web" { name_prefix = "web-" image_id = data.hcp_packer_artifact.web_base.external_identifier instance_type = "t3.small"}Without HCP, it reads the parameter. The provider marks value as sensitive for every parameter type, so use insecure_value for an AMI ID and the plan shows which image changes:
data "aws_ssm_parameter" "web_base" { name = "/images/web-base/production"}resource "aws_launch_template" "web" { name_prefix = "web-" image_id = data.aws_ssm_parameter.web_base.insecure_value instance_type = "t3.small"}Or let EC2 resolve it: image_id = "resolve:ssm:/images/web-base/production" in the launch template means each new instance launches from whatever the parameter holds at that moment, with no Terraform run. That's convenient but quieter: the plan never shows an image change, so replace running instances deliberately (an Auto Scaling instance refresh, for example). Avoid the third common option, an aws_ami data source with most_recent = true, for production: it deploys the newest AMI whether or not anyone promoted it.
With the data sources, the change reaches every deployment that reads them at its next plan and apply; with resolve:ssm:, only at the next instance launch. The older hcp_packer_image and hcp_packer_iteration data sources were replaced by the two above and have since been removed from the HCP provider, so old examples no longer work.
An aside: MCP and an AI assistant
HashiCorp publishes MCP servers for Terraform, Vault and Consul; there's none for Packer. The Terraform MCP server (version 1.4.1, October 2026) connects an AI assistant to the public Terraform Registry and, with a token, to HCP Terraform or Terraform Enterprise. With it, an assistant can look up the current arguments of hcp_packer_artifact or aws_launch_template instead of guessing from old examples, or list your workspaces and runs. Tools that change things are off unless you enable them, and HashiCorp warns against using it with untrusted clients or models. It's a convenience for whoever writes the Terraform, not part of the pipeline: nothing in this guide needs it.
What changed in 2025 and 2026
- Packer 1.13.0 (2 Jun 2025):
hcp_packer_registrybecame a top-level block. - Packer 1.14.2 (9 Sep 2025):
HCP_CRED_FILE, so builds can use workload identity federation instead of a client ID and secret. - Packer 1.14.3 (18 Nov 2025): continuous integration (CI) metadata for Bitbucket Pipelines and Jenkins, alongside GitHub Actions and GitLab.
- Packer 1.15.0 (4 Feb 2026): the
channelsargument, so the build itself moves channels. - Packer 1.15.1 (26 Mar 2026): native software bill of materials (SBOM) generation for HCP Packer, with no separate Syft download.
Common questions
Do I need HCP Packer to run Packer in GitHub Actions?
No. The plain AWS path above builds, records (in AMI tags) and promotes (in Parameter Store) without it. HCP Packer adds a registry across clouds, ancestry and revocation.
Why did my HCP Packer build fail with a fingerprint error?
A version with that fingerprint is already complete: with the commit SHA as the fingerprint, that commit was already built. Push a new commit, or use a different fingerprint, such as the run ID, for deliberate rebuilds like a nightly security patch.
Packer says HCP authentication isn't configured. What's missing?
Set HCP_CLIENT_ID and HCP_CLIENT_SECRET, or point HCP_CRED_FILE at a credential file (the auth action sets it) with Packer 1.14.2 or later. With a project-level service principal, also set HCP_PROJECT_ID.
How do I take a bad image out of circulation?
With HCP Packer, revoke the version and choose to roll back channels: each channel pointing at it moves to the last valid version. Terraform then reads the rolled-back version, so a plan simply moves to the good image. While a version is revoked it can't be assigned to a channel. If a channel still points at a revoked version (no rollback, or a revocation scheduled for later), hcp_packer_artifact returns it with revoke_at set: add a lifecycle precondition on revoke_at if a plan should stop then. Restoring it later doesn't put it back on any channel. Without HCP, put the previous AMI ID back in the parameter, then deprecate or deregister the bad AMI.
Can a pull request build an image for testing?
It can, but keep it away from your real image line: with HCP Packer, turn the registry off or send it to another bucket with HCP_PACKER_BUCKET_NAME; without it, tag it differently and never write a parameter from a pull request.
Keep going
The free Terraform and Packer course explains the pieces: golden images, a registry for image metadata, channels, revocation and Packer meets Terraform. Deciding between Packer and AWS's own image service? Read Packer vs EC2 Image Builder.