Terraform usually runs with more power than any person on the team: it can create, change and delete almost anything in your accounts. Its state can hold every secret your infrastructure uses. That makes a Terraform setup one of the most valuable targets in a company. This lesson collects the habits that keep it safe, from secrets to supply chain.
The threat model in one table
| Asset | What can go wrong | Main defence |
|---|---|---|
| Secrets in code, plans and state | Leaked through Git, logs, artifacts or a readable bucket | Ephemeral values, write-only arguments, encrypted state |
| Cloud credentials | Long-lived keys stolen from a laptop or CI | SSO and OIDC, short-lived roles, least privilege |
| Providers and modules | A compromised or typo-squatted dependency runs with admin rights | Pinning, lock file checksums, trusted sources |
| The configuration itself | Insecure settings (public buckets, open ports) merged by mistake | Scanners, policies, code review |
| The pipeline | A pull request changes the workflow to exfiltrate credentials | Separate plan and apply roles, protected environments |
Secrets: from sensitive to ephemeral to write-only
Orbit’s API needs a PostgreSQL database with an admin password. Three generations of doing this:
1. Plain variable (do not do this): the password is in a tfvars file, in the plan, in the state and maybe in Git.
2. Sensitive: sensitive = true hides the value in CLI output, but it is still stored in plan files and state.
3. Ephemeral and write-only (Terraform 1.10 and 1.11+): the password is generated or fetched during the run, sent to the API, and stored nowhere by Terraform.
ephemeral "random_password" "db" {
length = 32
special = true
}
resource "aws_secretsmanager_secret" "db" {
name = "orbit/${var.environment}/db-admin"
}
resource "aws_secretsmanager_secret_version" "db" {
secret_id = aws_secretsmanager_secret.db.id
secret_string_wo = ephemeral.random_password.db.result
secret_string_wo_version = 1
}
resource "aws_db_instance" "orbit" {
identifier = "orbit-${var.environment}"
engine = "postgres"
instance_class = "db.t4g.micro"
allocated_storage = 20
username = "orbit_admin"
password_wo = ephemeral.random_password.db.result
password_wo_version = 1
storage_encrypted = true
skip_final_snapshot = var.environment != "prod"
}
How the pieces fit:
- An ephemeral resource (
ephemeral "random_password") produces a value that exists only during this run. - A write-only argument (ending in
_wo) accepts ephemeral values and sends them to the API, but Terraform never saves them in plan or state. - Because Terraform cannot compare a value it never stored, the matching
_wo_versiontells it when to send a new one. To rotate the password, increase both versions to2and apply.
The application reads the password from Secrets Manager at runtime. Nobody, including Terraform’s state, needs to hold it.
Protect the state anyway
Ephemeral values reduce what is in state, but state still describes your whole infrastructure and many providers still return secrets (private keys, generated tokens). Treat it as sensitive:
- Encrypted at rest: S3 with SSE-KMS (
encrypt = trueplus akms_key_id), Azure Storage or GCS encryption, or HCP Terraform. - Least access: only the apply role and a few administrators can read the state bucket. The plan role can read it, but nobody else in the organisation.
- Versioned and logged: bucket versioning to recover from mistakes, access logs or CloudTrail data events to see who read it.
- Never in Git, never in artifacts without encryption and short retention.
Credentials: short-lived and least privilege
- People log in with SSO or
aws login; pipelines use OIDC (lesson 14). Nobody needs long-lived access keys. - Split roles by what they do: a read-only plan role, an apply role usable only from the protected branch and environment.
- Scope apply roles per configuration where you can. The network pipeline does not need permission to delete databases.
- Add
allowed_account_idsto every AWS provider block so credentials for the wrong account fail fast. - Use
lifecycle { prevent_destroy = true }on resources whose loss would be a disaster (state buckets, production databases, KMS keys). Terraform refuses any plan that destroys them.
Supply chain: pin what you run
Providers are executables that run with your cloud credentials. Modules are code you did not write. Pin both:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "6.0.0"
}
- Commit the lock file (
.terraform.lock.hcl). It records the provider version and its checksums;initrefuses a binary whose checksum does not match. Generate checksums for every platform your team uses so a Mac user and a Linux runner agree:
$ terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
- Pin modules to exact versions or Git commits, and upgrade them through pull requests where someone reads the changelog.
- Watch the source names.
hashicorp/awsis official; a lookalike namespace is not. Prefer official and partner providers, and a private registry for modules in larger organisations. - Pin CI actions by commit SHA (
uses: hashicorp/setup-terraform@<full-sha>) so a hijacked tag cannot change what runs with your cloud role. - Since Terraform 1.17,
required_providerscan reference variables and locals, which helps platform teams keep provider versions in one shared place. Keep those values in reviewed code, not in runtime inputs anyone can change.
Scan the code before it is planned
Static scanners read HCL and flag known-bad patterns in seconds:
$ trivy config infra/
infra/envs/prod/storage.tf (terraform)
HIGH: Bucket does not have logging enabled
...
$ checkov -d infra/ --compact
Trivy now includes what used to be tfsec. Checkov covers similar ground with a different rule set. Run one of them on every pull request and treat findings like failing tests: fix, or suppress with a written reason.
Enforce your own rules with Terraform Policy
Scanners know generic best practice; they do not know that Orbit only allows t4g instance types or that every resource needs a cost_center tag. Terraform Policy, generally available since Terraform 1.17, evaluates policies written in HCL (.policy.hcl files) against a plan. The plan, apply and query commands accept a -policies flag, so the same rules run on a laptop, in CI and in HCP Terraform. Teams already on HCP Terraform can also use Sentinel or OPA policy sets.
Start small: three or four rules that encode real incidents (“no public buckets”, “no security group open to the world on port 22”, “production databases must be encrypted and deletion-protected”), set them to advisory first, then make them blocking once the noise is gone.
A checklist for every Terraform repository
- No secrets in code, tfvars or plan output; ephemeral values and write-only arguments for passwords.
- Remote state, encrypted, versioned and readable only by the roles that need it.
- SSO for people, OIDC for pipelines, no long-lived keys.
- Separate plan and apply roles; apply only from the protected branch with approval.
.terraform.lock.hclcommitted with checksums for every platform.- Providers, modules and CI actions pinned.
- A scanner and policies on every pull request.
prevent_destroyon resources you can never lose.- A nightly drift check, so console changes are noticed.
Exercise
A database password is passed through a write-only argument from an ephemeral resource. You need to rotate it. What do you change?
Show answer
Answer: C. Terraform never stores write-only values, so it cannot tell they changed. The _wo_version argument is stored; changing it is the signal to send the new value to the API.
Exercise
Why commit .terraform.lock.hcl and run terraform providers lock for several platforms?
Show answer
Answer: C. The lock file pins exact provider versions and their checksums. Locking for all platforms your team uses avoids checksum mismatches between, for example, a Mac and a Linux CI runner.
Key takeaways
sensitiveonly hides output; ephemeral values and write-only arguments keep secrets out of plan and state.- Rotate write-only secrets by increasing their
_wo_version. - Encrypt, version and restrict state; it still describes everything you run.
- Short-lived credentials, separate plan and apply roles,
allowed_account_idsandprevent_destroy. - Pin providers, modules and CI actions; commit the lock file with multi-platform checksums.
- Scanners catch common mistakes; Terraform Policy (GA in 1.17) enforces your own rules.
FAQ
Is state encryption built into Terraform?
Terraform relies on the backend: S3, Azure Storage, GCS and HCP Terraform all encrypt at rest. OpenTofu added client-side state encryption as a built-in feature; Terraform has not. Either way, combine encryption with strict access control.
Which providers support write-only arguments?
Support is added resource by resource. In the AWS provider, database passwords, Secrets Manager secret values and SSM parameters were among the first. Check the resource documentation for arguments ending in _wo; if none exists yet, keep using a secret manager and sensitive.
Should I use Vault with Terraform?
If your company runs Vault, yes: the Vault provider has ephemeral resources for dynamic credentials, so Terraform can get a short-lived database or cloud credential for one run. Without Vault, your cloud’s secret manager plus ephemeral resources covers most needs.
What is the fastest security win for an existing Terraform repository?
Replace stored CI keys with OIDC and move state to an encrypted, access-controlled backend. Those two changes remove the most common ways Terraform setups are compromised.