• HashiCorp Developer

  • HashiCorp Cloud Platform
  • Terraform
  • Packer
  • Consul
  • Vault
  • Boundary
  • Nomad
  • Waypoint
  • Vagrant
Packer
  • Install
  • Tutorials
  • Documentation
  • Guides
  • Plugins
  • Try Cloud(opens in new tab)
  • Sign up
HCP Packer

Skip to main content
5 tutorials
  • Schedule Image Iteration Revocation for Compliance
  • Set Up Terraform Cloud Run Task for HCP Packer
  • Identify Compromised Images with Terraform Cloud
  • Enforce Image Compliance with Terraform Cloud
  • Revoke an Image and its Descendants using Inherited Revocation

  • Resources

  • Tutorial Library
  • Community Forum
    (opens in new tab)
  • Support
    (opens in new tab)
  • GitHub
    (opens in new tab)
  1. Developer
  2. Packer
  3. Tutorials
  4. HCP Packer
  5. Enforce Image Compliance with Terraform Cloud

Enforce Image Compliance with Terraform Cloud

  • 15min

  • HCPHCP
  • PackerPacker
  • TerraformTerraform

Using Terraform data sources in your configuration to retrieve machine images lets your configuration dynamically use more up-to-date images as you create them and stops you from using revoked images. The resource image validation Terraform Cloud run task feature helps you implement this best practice by scanning your Terraform configuration to prevent usage of revoked images, even when they are referenced by hard-coded image IDs.

The resource image validation run task feature parses your Terraform resources for machine image IDs and checks if images are tracked by HCP Packer. If the image is associated with an image iteration, the run task will fail if it is a revoked iteration. Additionally, it will warn you if the image is scheduled for revocation. The run task also detects any hard-coded image IDs, and prompts users to use the HCP Packer data sources to better track and manage machine images. This encourages your organization to track image lifecycles in HCP Packer and dynamically query image IDs from image channels with Terraform data sources.

Note: The resource image validation currently supports this list of resources.

In this tutorial, you will use the Terraform Cloud run task for HCP Packer to enforce Terraform configuration compliance. You will do this by associating the run task with a Terraform Cloud workspace. Then, you will iteratively update the workspace's configuration until the resource image validation reports that the configuration uses compliant images.

Prerequisites

This tutorial assumes that you are familiar with:

  • The standard Packer and HCP Packer workflows. If you are new to Packer, complete the Get Started tutorials first. If you are new to HCP Packer, complete the Get Started HCP Packer tutorials first.
  • The Terraform and Terraform Cloud plan/apply workflows. If you are new to Terraform itself, refer first to the Getting Started tutorials. If you are new to Terraform Cloud, refer to the Get Started - Terraform Cloud tutorials.

To follow along with this tutorial, you will need:

  • Packer 1.7.10 installed locally
  • Terraform 1.1.7 or later installed locally
  • An AWS account with credentials set as local environment variables
  • A HCP account with the HCP Packer Plus tier
  • A Terraform Cloud account with a Team & Governance plan.
  • Terraform Cloud workspace admin permissions to associate run tasks to a workspace.

This tutorial relies on a Terraform Cloud run task integrated with HCP Packer. If you have not yet created one, follow the Set Up Terraform Cloud Run Task for HCP Packer tutorial to do so.

Create HCP service principal and set as environment variables

In HCP Packer, go to Access control (IAM) in the left navigation menu, then select the Service principals tab.

Create a service principal named packer with the Contributor role.

Once you create the service principal, click the service principal name to view its details. From the detail page, click + Generate key to create a client ID and secret.

Copy and save the client ID and secret; you will not be able to retrieve the secret later. You will use these credentials in the next step.

Create service principal key

Once you generate the keys for the service principal, set the client ID and secret as environment variables so that Packer can authenticate with HCP.

In your terminal, set an environment variable for the client ID.

$ export HCP_CLIENT_ID=

Then, set an environment variable for the client secret.

$ export HCP_CLIENT_SECRET=

Login to Terraform Cloud

In this tutorial, you will use the Terraform CLI to create a Terraform Cloud workspace and trigger remote plan and apply runs.

Log into your Terraform Cloud account in your terminal.

$ terraform login
Terraform will request an API token for app.terraform.io using your browser.

If login is successful, Terraform will store the token in plain text in
the following file for use by subsequent commands:
    /Users/<USER>/.terraform.d/credentials.tfrc.json

Do you want to proceed?
  Only 'yes' will be accepted to confirm.

  Enter a value:

Confirm with a yes and follow the workflow in the browser window that automatically opens. Paste the generated API key into your Terminal when prompted. For more detailed instructions on logging in, review the Authenticate the CLI with Terraform Cloud tutorial.

Clone repository

In your terminal, clone the example repository. This repository contains a Packer template that defines an Ubuntu AMI and two directories with Terraform configuration that you will use to test the run task.

$ git clone https://github.com/hashicorp/learn-hcp-packer-run-tasks

Navigate to the cloned repository.

$ cd learn-hcp-packer-run-tasks

Create image iteration in HCP Packer

Open ubuntu-focal.pkr.hcl to review the template. This template will build an Ubuntu 20.04 AMI in the us-east-2 region and push the metadata to the learn-packer-run-tasks in HCP Packer.

ubuntu-focal.pkr.hcl
build {
  hcp_packer_registry {
    bucket_name = "learn-packer-run-tasks"
    ## ...
  }
  sources = [
    "source.amazon-ebs.basic-example-east"
  ]
}

Initialize your Packer template.

$ packer init .

Now, build your image.

$ packer build ubuntu-focal.pkr.hcl
amazon-ebs.basic-example-east: output will be in this color.

==> amazon-ebs.basic-example-east: Publishing build details for amazon-ebs.basic-example-east to the HCP Packer registry
==> amazon-ebs.basic-example-east: Prevalidating any provided VPC information
==> amazon-ebs.basic-example-east: Prevalidating AMI Name: packer_AWS_1646215104_v1.0.0
    amazon-ebs.basic-example-east: Found Image ID: ami-05be...
## ...
==> Wait completed after 4 minutes 41 seconds
==> Builds finished. The artifacts of successful builds are:
--> amazon-ebs.basic-example-east: AMIs were created:
us-east-2: ami-05be...
--> amazon-ebs.basic-example-east: Published metadata to HCP Packer registry packer/learn-packer-run-tasks/iterations/01FX9WDZPYN3YBFTTVJQFBGQVE

In your HCP dashboard, go to the learn-packer-run-tasks bucket to confirm Packer pushed the build metadata to HCP Packer.

HCP Packer `learn-packer-run-tasks` bucket

Create channel and schedule revocation

On the Channels page, create a channel named production and set it to the first iteration.

Image channel named `production` set to the first iteration

Next, go to the Iterations page. Schedule a revocation date for the first iteration by clicking on ..., then Revoke iteration.

Select Revoke at a future date and enter the time for 1 minute from your current time. The time is in UTC (current time in UTC). For example, if it is currently 10:00, enter 10:01. Then, enter Assign image channel to revoked iteration for the revocation reason, then click Revoke Iteration to revoke the iteration.

You are setting a short revocation window so that your image channel uses a revoked image to test validation workflows. This is for the educational purposes of the tutorial.

Schedule a revocation for the first iteration one minute from current time

Set up Terraform Cloud workspace

Go to the tf-resource-validation directory. This directory contains Terraform configuration that you will use to create your Terraform Cloud workspace to test the HCP Packer resource image validation run task.

$ cd tf-resource-validation

Open main.tf. This configuration defines an EC2 instance that references the community Ubuntu 20.04 AMI ID for us-east-2. This AMI ID is not tracked in your HCP Packer registry.

tf-resource-validation/main.tf
provider "aws" {
  region = var.region
}

resource "aws_instance" "app_server" {
  ami           = "ami-039af..."
  instance_type = "t2.micro"
  tags = {
    Name = "Learn-HCP-Packer"
  }
}

Update configuration

Open terraform.tf. In the cloud block, update the organization to point to your Terraform Cloud organization.

tf-resource-validation/terraform.tf
terraform {
  ## ...

  cloud {
    organization = "hashicorp-training"
    hostname     = "app.terraform.io"

    workspaces {
      name = "learn-hcp-packer-run-tasks-resource-validation"
    }
  }
}

Create Terraform Cloud workspace

Initialize your Terraform configuration. This will create a Terraform Cloud workspace named learn-hcp-packer-run-tasks-resource-validation in your Terraform Cloud organization.

$ terraform init

Initializing Terraform Cloud...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Installing hashicorp/aws v4.2.0...
- Installed hashicorp/aws v4.2.0 (signed by HashiCorp)

Terraform Cloud has been successfully initialized!

You may now begin working with Terraform Cloud. Try running "terraform plan" to
see any changes that are required for your infrastructure.

If you ever set or change modules or Terraform Settings, run "terraform init"
again to reinitialize your working directory.

In Terraform Cloud, open the learn-hcp-packer-run-tasks-resource-validation workspace.

The `learn-hcp-packer-run-tasks-resource-validation` workspace

Add AWS and HCP credentials to workspace variables

Go to the Variables page.

Under Workspace variables, add your AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, HCP_CLIENT_ID, and HCP_CLIENT_SECRET as environment variables. You generated the HCP client ID and secret in the prerequisites. Alternatively, you can create variable sets with these environment variables and reuse them across multiple workspaces.

Note: Be sure to mark the AWS_SECRET_ACCESS_KEY and HCP_CLIENT_SECRET as sensitive.

Set Terraform Cloud variables for AWS and HCP credentials

Note: The AWS_SESSION_TOKEN is optional unless your organization requires it.

Enable run tasks in workspace

Click on Settings then Run Tasks.

Go to run task page from variables page

Under Available Run Tasks, click on HCP-Packer.

Run task page shows HCP-Packer under "Available Run Tasks"

Terraform Cloud run tasks have two enforcement levels:

  1. Advisory: If this run task fails, the run will proceed with a warning in the UI.
  2. Mandatory: If this run task fails, the run will return an error and stop.

Select the Mandatory enforcement level, then click Create.

Associate HCP-Packer run task with workspace and set to mandatory enforcement level

The Run Task page will now display the run task for HCP Packer. This run task will parse resources for hard-coded machine image IDs and check if they are tracked and unrevoked in HCP Packer. If the run task detects an machine image ID that is associated with a revoked iteration, both the run task and the Terraform Cloud run will fail.

Terraform Cloud workspace now shows HCP-Packer run task

Trigger Terraform Cloud run

In your terminal, apply your configuration. When prompted to confirm the apply, press Enter to discard the run.

$ terraform apply
Running apply in Terraform Cloud. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.

Preparing the remote apply...

To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-training/learn-hcp-packer-run-tasks-resource-validation/runs/run-REDACTED

Waiting for the plan to start...

Terraform v1.1.6
on linux_amd64
Configuring remote state backend...
Initializing Terraform configuration...

## ...

Plan: 1 to add, 0 to change, 0 to destroy.

## ...

Do you want to perform these actions in workspace "learn-hcp-packer-run-tasks-resource-validation"?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:

â•·
│ Error: Apply discarded.
│
│

Verify untracked image validation

In Terraform Cloud, open the latest run and expand the Tasks passed box.

View passing run track. This run track notifies the user that the hard-coded image is not tracked by HCP Packer.

The run task passed with the following message:

Data source and resource image validation: 1 resource scanned. 1 image not tracked by HCP Packer. Use Packer to build compliant images and send information to HCP Packer.

Since you have the HCP Packer Plus tier, the run task will perform both data source and resource image validation. This will check and validate whether the HCP Packer data sources and hard-coded image IDs reference revoked image iterations in HCP Packer.

The run task parsed the aws_instance resource but did not find the AMI it uses in your HCP Packer registry. Since the task cannot verify the compliance of untracked images, it passes. The run task prompts you to use HCP Packer to track and manage your images for more accurate validation.

In addition, the run task has a Details link that will take you to the HCP Packer dashboard.

Hard-code AMI to test validation

In HCP Packer, go to the learn-packer-run-tasks bucket's revoked iteration. Under Builds, click on us-east-2 to view more information about the image.

Copy the Image ID, you will update your Terraform configuration to use this AMI ID.

Get revoked iteration's AMI ID from the HCP Packer dashboard

In tf-resource-validation/main.tf, update the aws_instance's ami attribute to the revoked iteration's image ID.

tf-resource-validation/main.tf
resource "aws_instance" "app_server" {
  ami           = "ami-039af..."
  instance_type = "t2.micro"
  tags = {
    Name = "Learn-HCP-Packer"
  }
}

Apply your configuration. After Terraform creates the plan, it will return an error because the run task failed.

$ terraform apply
Running apply in Terraform Cloud. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.

Preparing the remote apply...

To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-training/learn-hcp-packer-run-tasks-resource-validation/runs/run-REDACTED

## ...

â•·
│ Error: Unknown or unexpected cost estimate state: unreachable
│
│
╵

Verify hard-coded AMI image validation

In Terraform Cloud, open the latest run and expand the Tasks failed box.

View failed run task. This run task fails because the hard-coded image ID references a revoked iteration.

The run task failed with the following message:

Data source and resource image validation results: 1 resource scanned. 1 new resource using revoked images. 1 using hardcoded images in the configuration. No newer version was found for the revoked images. Use Packer to build compliant images and send information to HCP Packer. Use hcp_packer_image and hcp_packer_iteration data sources to query images from HCP Packer.

The run task parsed the aws_instance resource and found the machine image ID in a revoked iteration. This configuration uses a revoked (compromised or outdated) image. As a result, because the resource was being created, the run task failed and blocked the deployment of revoked images.

Note: The run task will only fail if the configuration uses a revoked image for creating new resources. If an existing resource uses a revoked image, the run task will succeed but still report that the resource is not compliant.

If the run task identifies a newer iteration version, it will suggest that you use it. If you are the image maintainer, you can then assign the channel to the newer iteration.

The run task also detected a hard-coded image ID in your configuration. The error message recommends updating the configuration to use HCP Packer data sources, so you do not have to manually update hard-coded image IDs.

Restore image iteration

In the HCP Packer dashboard, go to the learn-packer-run-tasks bucket and select the revoked iteration. Click Manage, then Restore iteration to restore the revoked iteration.

Restore revoked iteration in learn-packer-run-tasks bucket

Confirm the action by clicking on Restore iteration.

Use HCP Packer data source

In tf-resource-validation/main.tf, add the following data sources to the top of the file so Terraform can dynamically query the image ID from HCP Packer.

tf-resource-validation/main.tf
provider "hcp" {}

data "hcp_packer_iteration" "ubuntu" {
  bucket_name = "learn-packer-run-tasks"
  channel     = "production"
}

data "hcp_packer_image" "ubuntu_us_east_2" {
  bucket_name    = "learn-packer-run-tasks"
  cloud_provider = "aws"
  iteration_id   = data.hcp_packer_iteration.ubuntu.ulid
  region         = "us-east-2"
}

Then, update the aws_instance's ami attribute to reference the hcp_packer_image data source.

tf-resource-validation/main.tf
resource "aws_instance" "app_server" {
  ami           = data.hcp_packer_image.ubuntu_us_east_2.cloud_image_id
  instance_type = "t2.micro"
  tags = {
    Name = "Learn-HCP-Packer"
  }
}

In your terminal, apply your configuration. When prompted to confirm the apply, press Enter to discard the run.

$ terraform apply
Running apply in Terraform Cloud. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.

Preparing the remote apply...

To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-training/learn-hcp-packer-run-tasks-resource-validation/runs/run-REDACTED

Waiting for the plan to start...

Terraform v1.1.6
on linux_amd64
Configuring remote state backend...
Initializing Terraform configuration...

## ...

Plan: 1 to add, 0 to change, 0 to destroy.

## ...

Do you want to perform these actions in workspace "learn-hcp-packer-run-tasks-resource-validation"?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:

â•·
│ Error: Apply discarded.
│
│

Verify image validation

In Terraform Cloud, open the latest run and expand the Tasks passed box.

View passing run task

The run task passed with the following message:

Data source and resource image validation: 1 resource scanned. All resources are compliant.

The run task parsed both the data sources and the aws_instance resource. Since the data sources and the resource reference a d.

Next steps

In this tutorial, you associated the Terraform Cloud run task for HCP Packer with a Terraform Cloud workspace, then used the run task to ensure your Terraform configuration uses compliant images and follows HCP Packer best practices.

For more information on topics covered in this tutorial, check out the following resources:

  • Read more about the Terraform Cloud run task integration in the HCP Packer documentation.
  • Complete the data source image validation run task tutorial to learn how to identify compromised and outdated images referenced by the HCP Packer data sources (`hcp_packer_iteration and hcp_packer_image).
 Previous
 Next

This tutorial also appears in:

  •  
    6 tutorials
    Provision Infrastructure
    Install software, edit files, and provision machines created with Terraform. Use Packer or Cloud-Init to automatically provision SSH keys and a web server onto a Linux VM created by Terraform in AWS.
    • Terraform
  •  
    24 tutorials
    Collaborate using Terraform Cloud
    Collaborate on infrastructure with Terraform Cloud. Follow these tutorials to migrate state from local storage and take a deeper look at Terraform Cloud operations, including VCS integration, workspace configuration, and remote runs.
    • Terraform

On this page

  1. Enforce Image Compliance with Terraform Cloud
  2. Prerequisites
  3. Clone repository
  4. Create image iteration in HCP Packer
  5. Set up Terraform Cloud workspace
  6. Trigger Terraform Cloud run
  7. Hard-code AMI to test validation
  8. Restore image iteration
  9. Use HCP Packer data source
  10. Next steps
Give Feedback(opens in new tab)
  • Certifications
  • System Status
  • Terms of Use
  • Security
  • Privacy
  • Trademark Policy
  • Trade Controls
  • Give Feedback(opens in new tab)