Terraform security: secrets, scanning and policy
Where secrets leak in Terraform and how to stop it, scanning configurations for insecure resources with Trivy and Checkov before apply, and enforcing company rules with policy as code.
By the end of this lesson you'll be able to
0 of 6 completeVerified lab: sensitive values injected with TF_VAR_, the two ephemeral-value errors and Trivy 0.76.2 before and after fixes. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: Checkov, OPA with conftest, Sentinel and write-only arguments: explained, not run.
Cloud lab: write-only arguments and Secrets Manager need an AWS account.
Terraform touches everything: networks, databases, IAM, secrets. So it can leak everything too, through a state file anyone can read, or through a configuration that opens a bucket to the internet. This lesson covers the three places to guard: secrets, insecure resources and company rules.
Secret management
What sensitive hides, and what it doesn't
variable "db_password" { type = string sensitive = true } resource "local_sensitive_file" "db_config" { filename = "${path.module}/out/db.env" # created with 0700 permissions content = "DB_PASSWORD=${var.db_password}\n" } output "db_password" { value = var.db_password sensitive = true }
First, how the secret gets in. Never type it as -var=db_password=...: the value lands in your
shell history and is visible to other users in the process list while Terraform runs. Inject it
through the environment instead. Interactively, read -rs asks for it without echoing it or saving
it to history; in CI, the pipeline's secret store sets the variable. In the lab, the variable was
exported before running Terraform:
$ read -rs TF_VAR_db_password && export TF_VAR_db_password $ terraform apply -auto-approve ... # local_sensitive_file.db_config will be created + resource "local_sensitive_file" "db_config" { + content = (sensitive value) + directory_permission = "0700" + file_permission = "0700" + filename = "./out/db.env" + id = (known after apply) } ... Outputs: db_password = <sensitive> $ terraform output db_password = <sensitive>
read -rs TF_VAR_db_password && export TF_VAR_db_password&&run the next command only if this one worked
terraform apply -auto-approveterraforminfrastructure as codeapplymake the changes-auto-approveskip the yes prompt
The plan and outputs hide it. But the value is still there for anyone who looks:
$ terraform output -raw db_password S3cr3t-demo $ grep -c "S3cr3t-demo" terraform.tfstate 2
terraform output -raw db_passwordterraforminfrastructure as code
grep -c "S3cr3t-demo" terraform.tfstategrepfind lines that match a pattern-ccount matching lines
What this shows:
sensitive = trueis redaction, not encryption. It keeps the value out of plan output and CI logs. That's all.terraform output -rawprints it in clear, by design, so scripts can use it. Anyone who can run Terraform against this state can read it.- The state holds it in plain text, twice (once in the resource, once in the output). A saved
plan file (
-out=tfplan) holds it too. Both need the same protection as the secret itself.
Keeping secrets out of state: three different tools
Terraform 1.10 and 1.11 added ways to use a secret without ever storing it. They're easy to mix up, so here they are separately, with what the lab showed for each.
1. Ephemeral input variables (1.10+). ephemeral = true on a variable means its value is never
written to the plan or state. You can only use it where nothing needs to be stored: in providers, in
ephemeral resources, in write-only arguments, or passed to child modules.
variable "db_password" { type = string sensitive = true ephemeral = true # never written to plan or state }
Try to put it into a normal resource argument and Terraform stops at plan time:
Error: Invalid use of ephemeral value with terraform_data.uses_secret, on main.tf line 15, in resource "terraform_data" "uses_secret": 15: input = module.creds.password Ephemeral values are not valid for "input", because it is not a write-only attribute and must be persisted to state.
When the run used it only in an allowed way, the state didn't contain it at all:
$ grep -c "S3cr3t-demo" terraform.tfstate 0
grep -c "S3cr3t-demo" terraform.tfstategrepfind lines that match a pattern-ccount matching lines
2. Ephemeral outputs, from child modules only. A child module can mark an output ephemeral = true
to hand a secret to its caller without storing it. A root module can't: its outputs are saved in
state for terraform output to read. The lab tried:
$ terraform validate Error: Ephemeral output not allowed on main.tf line 7: 7: output "db_password" { Ephemeral outputs are not allowed in context of a root module
terraform validateterraforminfrastructure as codevalidatecheck the configuration
3. Ephemeral resources and write-only arguments.
- An ephemeral resource (an
ephemeralblock, 1.10+) fetches something for the length of one run only, such as a secret from AWS Secrets Manager (ephemeral "aws_secretsmanager_secret_version") or a short-lived token, and is never saved. - A write-only argument (1.11+) is sent to the cloud API but never stored in plan or state. Providers
name them with a
_wosuffix, for examplepassword_woonaws_db_instance, paired with a version number (password_wo_version) that you bump to rotate the password.
Combined, they're the modern answer to "secrets in state": an ephemeral resource reads the secret, and a write-only argument passes it to the database, with nothing stored anywhere in Terraform. They need a provider version that supports them, so check the resource's docs.
Keeping secrets safe
- Protect state and plan files like password files. Remote backend, encrypted (S3 with
encrypt = true, ideally a KMS key), bucket access limited to the pipeline and a few admins, and saved plans kept private and deleted after apply. - Never put secrets in code, committed tfvars or command-line flags. Pass them as
TF_VAR_db_passwordfrom the CI secret store, or read them inside Terraform from a secret manager. - Let the cloud generate them. Many resources can create and store their own secret, such as
manage_master_user_password = trueon AWS RDS, which keeps the password in Secrets Manager. - Prefer ephemeral values and write-only arguments wherever the provider supports them, so the secret never reaches state at all.
Scanning before apply
Static scanners read your .tf files and flag insecure settings before anything exists. The lab ran
Trivy 0.76.2 (trivy config) on a deliberately bad AWS configuration: an EC2 instance, an S3
bucket with public access allowed, and a security group with SSH open to the world. It needs no AWS
account:
$ trivy config --quiet --severity HIGH,CRITICAL . Report Summary ┌─────────┬───────────┬───────────────────┐ │ Target │ Type │ Misconfigurations │ ├─────────┼───────────┼───────────────────┤ │ . │ terraform │ 0 │ ├─────────┼───────────┼───────────────────┤ │ main.tf │ terraform │ 8 │ └─────────┴───────────┴───────────────────┘ ... main.tf (terraform) =================== Tests: 8 (SUCCESSES: 0, FAILURES: 8) Failures: 8 (HIGH: 8, CRITICAL: 0)
trivy config --quiet --severity HIGH,CRITICAL ..this folder
The eight findings, one per line:
AWS-0028 (HIGH): Instance does not require IMDS access to require a token. AWS-0086 (HIGH): Public access block does not block public ACLs AWS-0087 (HIGH): Public access block does not block public policies AWS-0091 (HIGH): Public access block does not ignore public ACLs AWS-0093 (HIGH): Public access block does not restrict public buckets AWS-0107 (HIGH): Security group rule allows unrestricted ingress from any IP address. AWS-0131 (HIGH): Root block device is not encrypted. AWS-0132 (HIGH): Bucket does not encrypt data with a customer managed key.
Each finding in the full report shows the exact lines and a link explaining the risk and the fix. For example, the bucket's public access block:
AWS-0086 (HIGH): Public access block does not block public ACLs ════════════════════════════════════════ S3 buckets should block public ACLs on buckets and any objects they contain. By blocking, PUTs with fail if the object has any public ACL a. See https://avd.aquasec.com/misconfig/aws-0086 ──────────────────────────────────────── main.tf:25 via main.tf:23-29 (aws_s3_bucket_public_access_block.uploads) ──────────────────────────────────────── 23 resource "aws_s3_bucket_public_access_block" "uploads" { 24 bucket = aws_s3_bucket.uploads.id 25 [ block_public_acls = false 26 block_public_policy = false 27 ignore_public_acls = false 28 restrict_public_buckets = false 29 }
(The truncated sentence is in Trivy's own message.) The fixes are simple: set the four
block_*/restrict_* arguments to true, restrict SSH to your office or VPN range (or use SSM
Session Manager and close port 22 completely), add metadata_options { http_tokens = "required" }
and root_block_device { encrypted = true }.
Checkov, and what happened to tfsec
- Checkov (open source, from Prisma Cloud) does the same job with a very large set of checks:
checkov -d .. Many teams run one of Checkov or Trivy, not both. Checkov wasn't run for this course. - tfsec, once the popular Terraform scanner, has been folded into Trivy by its maintainer, Aqua
Security. Its checks live on in
trivy config; new projects should use Trivy.
When a finding is a deliberate choice (a public website bucket), suppress it in code with a comment the scanner understands and a reason, rather than turning the check off globally.
Policy as code
Scanners know general best practice. Your company has its own rules: only approved instance types, every resource tagged with an owner, no resources outside two regions. Policy as code writes those rules as code that checks every plan automatically.
The input is the plan as JSON:
$ terraform plan -out=tfplan $ terraform show -json tfplan > plan.json
terraform plan -out=tfplanterraforminfrastructure as codeplanpreview changes
terraform show -json tfplan > plan.json>write output to a file, replacing it
Open Policy Agent (OPA) with conftest checks it with rules in the Rego language (shown, not run here):
# policy/tags.rego package main deny contains msg if { some rc in input.resource_changes rc.type == "aws_instance" not rc.change.after.tags.owner msg := sprintf("%s has no owner tag", [rc.address]) }
$ conftest test plan.json
Any deny message fails the command, and so the pipeline. Sentinel is HashiCorp's own policy
language, built into HCP Terraform and Terraform Enterprise, where policies can be set to warn or to
block an apply.
Put all three layers in the pull request pipeline from lesson 13: secrets come from the secret store, Trivy or Checkov scans the code, and policies check the plan, all before a human approves.
Give the pipeline's apply role only the permissions its resources need, not admin. Turn on state bucket versioning, encryption and access logging. Scan and policy-check every pull request, and review suppressions like code. A suppressed finding without a reason is a finding.
Find and fix the insecure settings
Write the flawed AWS configuration from this lesson (EC2 instance, S3 bucket with public access allowed, security group with SSH from 0.0.0.0/0), run trivy config at HIGH and CRITICAL severity, save the report, then fix the findings and re-run until the count drops. Note which findings you fixed and how.
~/security-report.txtReveal one safe solution
$ trivy config --quiet --severity HIGH,CRITICAL . > ~/security-report.txt $ grep -E '^AWS-' ~/security-report.txt $ # fix the public access block, the SSH rule, IMDSv2 and root disk encryption, then: $ trivy config --quiet --severity HIGH,CRITICAL . | grep 'Failures:'
trivy config --quiet --severity HIGH,CRITICAL . > ~/security-report.txt.this folder>write output to a file, replacing it
grep -E '^AWS-' ~/security-report.txtgrepfind lines that match a pattern
trivy config --quiet --severity HIGH,CRITICAL . | grep 'Failures:'|pipe: send output to the next command
The lab started at Failures: 8 (HIGH: 8, CRITICAL: 0). After the four fixes above, the re-run
showed Failures: 1 (HIGH: 1, CRITICAL: 0): only AWS-0132, the customer-managed-key finding, was
left. Fixing it needs a KMS key, which is a judgement call for a bucket of uploads.
Try it yourself
0 of 6 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
A variable is marked sensitive = true. Where is its value still visible?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.