# 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.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 16. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/16-security

## What you will learn

- Explain what sensitive = true hides and what it doesn't
- Keep secrets out of code and state with secret managers, ephemeral variables and resources, and write-only arguments
- Explain why root-module outputs can't be ephemeral
- Scan a configuration with Trivy and read its findings
- Describe Checkov, and know that tfsec now lives on in Trivy
- Enforce rules with policy as code using OPA or Sentinel against the plan JSON

> **Lab status.** **Verified 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. <br />**Code walkthrough:** Checkov, OPA with conftest, Sentinel and write-only arguments: explained, not run. <br />**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.

> **Figure.** Three risks. One, secrets: the state is plain text; sensitive = true hides output, not the state file; grep for the demo secret in tfstate finds it twice; use an encrypted backend with S3 and KMS, tight IAM on the bucket, and secrets from Vault or Secrets Manager at runtime. Two, insecure resources: scan before apply; trivy config found 8 HIGH findings including S3 public access allowed, SSH open to 0.0.0.0/0, root disk not encrypted and IMDSv2 not required; Checkov does the same with thousands of checks, run in CI on every PR. Three, company rules: policy as code with OPA and conftest or Sentinel in HCP Terraform, for rules like no public S3 buckets, only certain instance types, and every resource has an owner tag, checked against the plan JSON.
>
> Guard the secrets, scan the resources, enforce the rules.

## Secret management

### What sensitive hides, and what it doesn't

```hcl
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:

```text
$ 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>
```

The plan and outputs hide it. But the value is still there for anyone who looks:

```text
$ terraform output -raw db_password
S3cr3t-demo
$ grep -c "S3cr3t-demo" terraform.tfstate
2
```

What this shows:

- **`sensitive = true` is redaction, not encryption.** It keeps the value out of plan output and CI
  logs. That's all.
- **`terraform output -raw` prints 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.

```hcl
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:

```text
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:

```text
$ grep -c "S3cr3t-demo" terraform.tfstate
0
```

**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:

```text
$ 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
```

**3. Ephemeral resources and write-only arguments.**

- An **ephemeral resource** (an `ephemeral` block, 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 `_wo` suffix, for example `password_wo` on `aws_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

1. **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.
2. **Never put secrets in code, committed tfvars or command-line flags.** Pass them as
   `TF_VAR_db_password` from the CI secret store, or read them inside Terraform from a secret manager.
3. **Let the cloud generate them.** Many resources can create and store their own secret, such as
   `manage_master_user_password = true` on AWS RDS, which keeps the password in Secrets Manager.
4. **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:

```text
$ 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)
```

The eight findings, one per line:

```text
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:

```text
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:

```sh
$ terraform plan -out=tfplan
$ terraform show -json tfplan > plan.json
```

**Open Policy Agent (OPA)** with **conftest** checks it with rules in the Rego language (shown, not
run here):

```text
# 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])
}
```

```sh
$ 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.

> **In production.** 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.

## Mission: 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.

- You need: A main.tf with the three flawed AWS resources
- You'll have: ~/security-report.txt

```sh
$ 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:'
```

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

- Mark a variable sensitive, apply, and run `terraform output` and `terraform output -raw`.
- Search terraform.tfstate for the secret's value.
- Install Trivy and run `trivy config .` on a configuration with a public S3 bucket.
- Fix one finding and re-run the scan.
- Export a plan with `terraform show -json tfplan > plan.json` and look for resource_changes.
- Do the mini mission and keep `~/security-report.txt`.

## Quiz

1. A variable is marked sensitive = true. Where is its value still visible?
   - Nowhere
   - **In the state file, in plain text, and through terraform output -raw** (answer)
   - Only in the plan output
   Why: sensitive only redacts CLI output. State stores real values, which is why state must be encrypted and access-controlled.

2. What does trivy config . do?
   - Applies the configuration
   - **Scans Terraform files for insecure settings, such as public buckets or SSH open to the internet, before anything is created** (answer)
   - Encrypts the state
   Why: Static scanners read the code and report misconfigurations with severity and fixes, so problems are caught in the pull request.

3. What is policy as code?
   - Writing comments about security
   - **Rules written as code (OPA/Rego or Sentinel) that check every plan and block ones that break company rules** (answer)
   - A Terraform provider
   Why: Policies such as "no public buckets" or "every resource has an owner tag" run automatically on the plan, so they can't be skipped in review.

4. How should a database password reach Terraform?
   - In a .tfvars file committed to Git
   - **From a secret manager or the CI secret store at run time, ideally through write-only arguments so it never lands in state** (answer)
   - Hard-coded in main.tf
   Why: Secrets in code end up in Git history. Secret managers keep them encrypted and audited, and write-only arguments (Terraform 1.11+) keep them out of state.

5. Can a root module declare an output with ephemeral = true?
   - Yes, to hide it from terraform output
   - **No. Root outputs are saved in state; only child-module outputs can be ephemeral** (answer)
   - Only for sensitive values
   Why: Terraform rejects it with "Ephemeral outputs are not allowed in context of a root module". Ephemeral outputs pass secrets between modules during one run.

## Resources

- [Sensitive data in state](https://developer.hashicorp.com/terraform/language/state/sensitive-data) (HashiCorp)
- [Ephemeral values and write-only arguments](https://developer.hashicorp.com/terraform/language/manage-sensitive-data) (HashiCorp)
- [Trivy misconfiguration scanning for Terraform](https://trivy.dev/latest/docs/coverage/iac/terraform/) (Aqua Security)
- [Checkov](https://www.checkov.io/) (Prisma Cloud (Bridgecrew))
- [Conftest (OPA for config files)](https://www.conftest.dev/) (Open Policy Agent)
- [Sentinel policy as code](https://developer.hashicorp.com/sentinel) (HashiCorp)
