Terraform Field Guide · Chapter 11 of 12
Secrets, policy and cost
Terraform holds the keys to everything it builds, and remembers more than you think. Keep secrets out of code and out of state, give Terraform only the permissions it needs, let policy checks say no before a reviewer has to, and see what a change costs before it is applied.
- 50 min
- Advanced
- Hands-on
- Free
By Joshua Sequeira, founding engineer running Terraform in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
Follow the password
Your database needs a password, and Terraform creates the database. There are several ways to connect the two, and they differ in one thing that matters: where the password ends up. Try each:
Interactive · Follow the password
The database needs a password. Where does it end up?
The progression is the whole lesson. Never commit a secret. sensitive hides it on screen and nowhere else. The best option is for Terraform never to hold the secret at all.
Keeping secrets out of state
For AWS databases, the cleanest answer is to let RDS own the password:
resource "aws_db_instance" "main" {
identifier = "shop-prod"
engine = "postgres"
instance_class = "db.t4g.medium"
username = "shop"
# RDS creates the password, stores it in Secrets Manager and rotates it.
# Terraform never sees it; state only holds the secret's ARN.
manage_master_user_password = true
deletion_protection = true
storage_encrypted = true
}
output "db_secret_arn" {
value = aws_db_instance.main.master_user_secret[0].secret_arn
}- RDS generates the master password and keeps it in Secrets Manager, with rotation. Your app reads it from Secrets Manager at startup.
- The platform-level guard from chapter 8. AWS itself refuses to delete the database until this is turned off.
- Safe to store and pass around: it is a pointer, not the secret.
Where a resource has no managed option, Terraform 1.11 and later support write-only arguments (names ending in _wo) fed by ephemeral values: they are sent to the provider during apply and never written to plan or state. Check the resource's Registry page for a _wo argument before falling back to a value that will sit in state.
Whatever you choose, assume state holds something sensitive and protect it accordingly: an encrypted bucket with versioning, public access blocked, and read access limited to the pipeline roles and a few people.
Terraform's own permissions
The role Terraform applies with can create, change and delete anything it has permission for. Treat it as the most powerful identity in the account:
- Separate plan and apply roles. Plans read resources and state, and write only the lock file. Applies run only after merge, in a protected environment (chapter 10).
- One role per environment, in that environment's account. The dev pipeline cannot assume the prod role at all.
- Scope it down over time. Start broad if you must, then use CloudTrail and IAM Access Analyzer to see which actions the role actually uses, and remove the rest.
- No humans with apply rights day to day. Break-glass access exists, is logged, and is rare.
Policy as code
Some rules should never depend on a reviewer noticing: no SSH from the internet, no public buckets, no unencrypted databases, no resources without an owner tag. Policy as code turns those rules into checks that fail the pipeline.
| Tool | Checks | Good for |
|---|---|---|
| Checkov, Trivy | Your .tf files, against hundreds of built-in rules | A first line of defence, with no setup |
| OPA with conftest | The plan as JSON, against rules you write in Rego | Your own rules: "never delete a database", "prod must be multi-AZ" |
| Sentinel, OPA in HCP Terraform | Plans, inside HCP Terraform runs | Teams already on HCP Terraform |
Plan-based policies see what will actually happen, including values computed from variables. Here is one rule, run against terraform show -json tfplan > plan.json with conftest test plan.json:
package main
import rego.v1
# Never let a pipeline delete a database.
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_db_instance"
"delete" in rc.change.actions
msg := sprintf("%s would be deleted", [rc.address])
}- The plan JSON lists every resource change with its address, type and actions.
- A replacement is a delete plus a create, so this catches -/+ as well as plain destroys.
Cost before apply
A plan tells you what will change, not what it costs. Infracost reads the plan and prices it with public cloud prices, and can comment the difference on a pull request, next to the plan:
infracost breakdown --path .
Project: envs/prod
Name Monthly Qty Unit Monthly Cost
aws_instance.web[0]
├─ Instance usage (Linux/UNIX, on-demand, m5.large) 730 hours $70.08
└─ root_block_device
└─ Storage (general purpose SSD, gp3) 8 GB $0.64
aws_nat_gateway.main[0]
├─ NAT gateway 730 hours $32.85
└─ Data processed Monthly cost depends on usage: $0.045 per GB
...
OVERALL TOTAL $310.71730 hours- A month of on-demand time, at us-east-1 prices: $0.096 an hour for an m5.large, $0.045 for a NAT gateway.
Monthly cost depends on usage- Traffic-based charges need an estimate from you, in an infracost-usage.yml file.
OVERALL TOTAL- Three instances and three NAT gateways. The NAT gateways, one per availability zone, are a third of the bill: exactly the kind of line a cost comment makes people discuss.
Cost visibility also depends on tags. Put environment, service and owner in the provider's default_tags (chapter 2), activate them as cost allocation tags in AWS Billing, and the bill can be split the same way your code is.
Hands-on: scan, and look in state
First, prove that sensitive does not keep a value out of state. No cloud account needed:
terraform {
required_providers {
random = { source = "hashicorp/random", version = "~> 3.6" }
}
}
resource "random_password" "db" {
length = 20
special = false
}
output "db_password" {
value = random_password.db.result
sensitive = true
}terraform init && terraform apply -auto-approve
terraform output
grep '"result":' terraform.tfstate
Outputs:
db_password = <sensitive>
db_password = <sensitive>
"result": "q8Zt3VnK0pLx7WmR2sYd",<sensitive>- Redacted everywhere Terraform prints it.
"result"- In state, in plain text. Anyone who can read the state file can read the password.
Now scan a deliberately bad configuration. Checkov needs only the files:
resource "aws_security_group" "web" {
name = "web"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_s3_bucket" "exports" {
bucket = "acme-exports-demo"
}
resource "aws_s3_bucket_public_access_block" "exports" {
bucket = aws_s3_bucket.exports.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}brew install checkov # or: pip install checkov
checkov -d bad/ --compact
Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
FAILED for resource: aws_security_group.web
File: /main.tf:1-10
Check: CKV_AWS_53: "Ensure S3 bucket has block public ACLS enabled"
FAILED for resource: aws_s3_bucket_public_access_block.exports
File: /main.tf:16-22
...--compact- Hides the code snippets, so the list of failures is easier to scan.
CKV_AWS_24- Each check has an ID you can look up, and skip with a reason when a rule genuinely does not apply.
Mini mission
Make the scan pass, properly
Fix bad/main.tf so the SSH rule and the public access block both pass. Then pick one remaining failure that you would accept for a demo bucket, and skip it with a written reason instead of deleting the check.
Reveal one safe solution
resource "aws_security_group" "web" {
name = "web"
description = "Web servers"
ingress {
description = "SSH from the office VPN only"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["203.0.113.0/24"]
}
}
resource "aws_s3_bucket" "exports" {
#checkov:skip=CKV_AWS_144:Demo bucket, cross-region replication not needed
bucket = "acme-exports-demo"
}
resource "aws_s3_bucket_public_access_block" "exports" {
bucket = aws_s3_bucket.exports.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}The skip comment lives next to the resource, names the check and says why, so a reviewer can disagree with it. Checkov will still flag other things for this bucket, such as access logging and versioning; decide each one the same way: fix it, or skip it with a reason.
Check yourself
Quiz
0 of 5 answered