MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Packer Tutorials: Amazon Secrets Manager Data Source – amazon-secretsmanager

The amazon-secretsmanager data source lets a Packer HCL2 template read a secret from AWS Secrets Manager during a build, so passwords and tokens stay out of your template files and variable files. This page explains every argument and output, gives a complete working template, covers the IAM permissions you need, and lists common errors and how to fix them.

The Amazon plugin is able to fetch data from AWS. To achieve this, the plugin comes with data sources to retrieve AMI and secrets information. Packer supports the following data sources at the moment:

  • amazon-ami – Filter and fetch an Amazon AMI to output all the AMI information.
  • amazon-secretsmanager – Retrieve information about a Secrets Manager secret version, including its secret value.
  • amazon-parameterstore – Retrieve information about a parameter in SSM.

The Secrets Manager data source provides information about a Secrets Manager secret version, including its secret value. Data sources is a feature exclusively available to HCL2 templates.


data "amazon-secretsmanager" "basic-example" {
  name = "packer_test_secret"
  key  = "packer_test_key"
  version_stage = "example"
}

# usage example of the data source output
locals {
  value         = data.amazon-secretsmanager.basic-example.value
  secret_string = data.amazon-secretsmanager.basic-example.secret_string
  version_id    = data.amazon-secretsmanager.basic-example.version_id
  secret_value  = jsondecode(data.amazon-secretsmanager.basic-example.secret_string)["packer_test_key"]
}
Code language: PHP (php)

data "amazon-secretsmanager" "basic-example" {
  name = "packer_test_secret"
  key  = "packer_test_key"

  assume_role {
      role_arn     = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME"
      session_name = "SESSION_NAME"
      external_id  = "EXTERNAL_ID"
  }
}
Code language: JavaScript (javascript)

How the data source works

Packer evaluates data sources before any builder starts. When it reaches an amazon-secretsmanager block, the Amazon plugin calls the Secrets Manager GetSecretValue API with the credentials Packer has, then makes the result available as data.amazon-secretsmanager.<NAME>.<ATTRIBUTE>. You can reference those attributes in locals, source blocks and provisioners just like variables.

Because the lookup happens on every packer build, rotating the secret in AWS changes what the next build uses without any template edits. Data sources are HCL2-only, so this does not work in legacy JSON templates. Run packer hcl2_upgrade to convert those first.

Arguments and outputs

ArgumentRequiredDescription
nameYesFriendly name or full ARN of the secret.
keyNoFor JSON secrets, the key whose value goes into the value output.
version_stageNoStaging label of the version to fetch. Defaults to AWSCURRENT. AWSPREVIOUS is the other common label.
version_idNoExact version ID to fetch. Use this or version_stage, not both.
region, profile, access_key, secret_key, assume_roleNoStandard Amazon plugin authentication settings. If you leave them out, the usual AWS credential chain is used.
OutputDescription
valueThe value for key if you set one. If you did not, the first value found in the secret.
secret_stringThe full decrypted secret string, which is often a JSON document.
secret_binaryThe binary secret, base64-encoded, if the secret was stored as binary.
version_idThe ID of the version that was retrieved.

Note: If you leave out key on a JSON secret that holds several values, you cannot rely on which one ends up in value. Set key explicitly, or decode secret_string with jsondecode() as the first example above does.

Correcting the first example

The first example above sets version_stage = "example". That only works if a version of the secret carries a custom staging label called example. Most secrets don't have one, so the build fails because Secrets Manager can't find a version with that label. In most cases, remove the line so the default AWSCURRENT version is used:

data "amazon-secretsmanager" "basic-example" {
  name   = "packer_test_secret"
  key    = "packer_test_key"
  region = "us-east-1"
  # version_stage defaults to AWSCURRENT; set it only for custom labels
}Code language: PHP (php)

Neither example above declares the Amazon plugin or a region. Without a required_plugins block, packer init won't install the plugin. Without a region set in the template, the environment or an AWS profile, the API call fails. The full template below includes both.

Prerequisites: the secret and IAM permissions

  1. Install Packer and the AWS CLI, and configure credentials with aws configure or environment variables.
  2. Create a JSON secret for testing (the command is below).
  3. Grant the identity that runs Packer secretsmanager:GetSecretValue on the secret. If the secret is encrypted with a customer-managed KMS key, also grant kms:Decrypt on that key.
  4. If you use assume_role, the calling identity needs sts:AssumeRole on the target role. The target role's trust policy must allow that caller, and must require the external_id if you set one.
aws secretsmanager create-secret \
  --name packer_test_secret \
  --secret-string '{"packer_test_key":"S3cr3tValue","db_user":"admin"}' \
  --region us-east-1Code language: JavaScript (javascript)
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "arn:aws:secretsmanager:us-east-1:ACCOUNT_ID:secret:packer_test_secret-*"
    }
  ]
}Code language: JSON / JSON with Comments (json)

Note: Secrets Manager adds a random six-character suffix to every secret ARN. The -* at the end of the resource lets the policy match it.

A complete working template

This template reads the secret, marks it as sensitive so Packer masks it in logs, and passes it to a shell provisioner as an environment variable. Save it as aws-secret.pkr.hcl.

packer {
  required_plugins {
    amazon = {
      version = ">= 1.0.0"
      source  = "github.com/hashicorp/amazon"
    }
  }
}

variable "region" {
  type    = string
  default = "us-east-1"
}

data "amazon-secretsmanager" "app" {
  name   = "packer_test_secret"
  key    = "packer_test_key"
  region = var.region
}

# A local block (not locals) is needed to mark a value as sensitive
local "app_token" {
  expression = data.amazon-secretsmanager.app.value
  sensitive  = true
}

locals {
  timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}

source "amazon-ebs" "ubuntu" {
  region        = var.region
  instance_type = "t3.micro"
  ssh_username  = "ubuntu"
  ami_name      = "secret-demo-${local.timestamp}"

  source_ami_filter {
    filters = {
      name                = "ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*"
      root-device-type    = "ebs"
      virtualization-type = "hvm"
    }
    owners      = ["099720109477"]
    most_recent = true
  }
}

build {
  sources = ["source.amazon-ebs.ubuntu"]

  provisioner "shell" {
    environment_vars = ["APP_TOKEN=${local.app_token}"]
    inline = [
      "test -n \"$APP_TOKEN\" && echo 'Secret received'"
    ]
  }
}Code language: PHP (php)
packer init .
packer fmt .
packer validate .
packer build .

During the build, the provisioner prints Secret received. Wherever the secret value would appear in Packer's output, you see <sensitive> instead.

Common errors and fixes

ErrorCauseFix
ResourceNotFoundExceptionWrong secret name, or the secret lives in a different region.Check with aws secretsmanager describe-secret --secret-id NAME --region REGION and set region to match.
AccessDeniedExceptionMissing secretsmanager:GetSecretValue or kms:Decrypt.Add the permissions to the IAM identity or assumed role.
Can't find a version for the staging labelversion_stage points to a label that doesn't exist, like example in the example above.Remove version_stage or use AWSCURRENT / AWSPREVIOUS.
Unknown data source type amazon-secretsmanagerAmazon plugin not installed.Add required_plugins and run packer init ..
No valid credential sources foundPacker can't find AWS credentials.Set AWS_PROFILE or the access key environment variables, or use an instance or OIDC role in CI.
Error about the key or JSONkey set on a plain-text (non-JSON) secret.Remove key and use secret_string directly.

Security best practices

  • Don't bake long-lived secrets into images. Anything written to disk in the AMI is readable by everyone who launches it or can access its snapshots. Use secrets mainly for build-time tasks such as pulling from a private repository, and remove any temporary files before the build ends.
  • Mark values as sensitive with a local block and sensitive = true, so they don't show up in PACKER_LOG=1 debug output.
  • Scope IAM policies to specific secret ARNs instead of *.
  • In CI, use short-lived credentials (OIDC federation or assume_role) instead of static access keys.
  • Pick amazon-parameterstore for plain configuration values and Secrets Manager for credentials that need rotation.

For more on where Packer fits alongside Terraform and CloudFormation, see Infrastructure as Code: A Practical Guide for DevOps Professionals.

Frequently asked questions

Can I use the amazon-secretsmanager data source in a Packer JSON template?

No. Data sources only work in HCL2 templates. Convert the JSON template with packer hcl2_upgrade first.

Which version of the secret does Packer fetch by default?

The version labelled AWSCURRENT. Set version_stage to use another label such as AWSPREVIOUS, or version_id to fetch an exact version.

How do I read several keys from one JSON secret?

Leave key out and decode the whole string, for example jsondecode(data.amazon-secretsmanager.x.secret_string)["db_user"]. Alternatively, declare one data source block per key.

Will the secret appear in Packer logs?

It can. To avoid that, assign it to a local block with sensitive = true, and Packer will show <sensitive> in its output instead of the value.

What IAM permissions does the data source need?

secretsmanager:GetSecretValue on the secret, plus kms:Decrypt if the secret uses a customer-managed KMS key. With assume_role, the caller also needs sts:AssumeRole on the target role.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Packer Tutorials: Packer Install and configurations

HashiCorp Packer is a single binary that builds machine images (AMIs, Azure images, Docker images, VMware templates and more) from one HCL template. The commands above install…

Read More

DevOps in Banking: What Engineers Should Know Before Joining a Compliance Team

DevOps in banking follows a rule most tech companies can bend: every change to a production system needs an approval and a record someone can check later. …

Read More

Gitlab FAQ

GitLab cannot restrict who reads or edits a single file in a repository. Access is granted per project. You can still stop secrets from reaching the repository…

Read More

How to Add an AI Model API to a DevOps Pipeline Safely

Adding an AI/ML service to a DevOps pipeline involves more than placing an API key in an environment variable. The team must decide which pipeline stages can…

Read More

Building an AI Video Pipeline: A DevOps Guide for Ad Teams

An AI video pipeline for advertising treats video generation like any other cloud workload: requests are submitted asynchronously, jobs are tracked and polled, outputs are validated automatically,…

Read More

Dark Web Explained for DevOps: What It Is, What It Isnโ€™t, and How to Reduce Risk

The dark web is a small, intentionally hidden part of the internet, often confused with the deep web. This guide explains the differences and gives DevOps teams practical steps to detect leaks, rotate secrets, and harden delivery pipelines.

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x