TExcelTAD

Conftest on Terraform Plans

Checking .tf files catches some mistakes, but a module call with variables says little about the result. The plan does: tofu show -json tfplan (or terraform show -json) lists every resource change with its final attribute values. Policies over plan JSON are the IaC gate the Terraform course points to.

The shape of plan JSON

json
{
  "format_version": "1.2",
  "resource_changes": [
    {
      "address": "aws_db_instance.main",
      "type": "aws_db_instance",
      "name": "main",
      "change": {
        "actions": ["create"],
        "before": null,
        "after": { "engine": "postgres", "storage_encrypted": false, "...": "..." },
        "after_unknown": { "id": true, "...": "..." },
        "after_sensitive": { "password": true }
      }
    }
  ],
  "configuration": { "...": "the module and variable structure" },
  "planned_values": { "...": "the resulting state" }
}

Most rules iterate resource_changes, filter by type and change.actions (["create"], ["update"], ["delete"], ["delete","create"] for replacements, ["no-op"]), and inspect change.after. Values only known after apply appear in after_unknown, not in after.

A real plan, a real gate

The sandbox can plan AWS resources offline (dummy credentials, skip_* provider settings), which is enough to produce real plan JSON. The first version of linkly's database breaks three rules:

bash · try it yourself
mkdir -p infra policy && cd infra
cat > providers.tf <<'HCL'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}
provider "aws" {
  region                      = "eu-west-1"
  access_key                  = "offline"          # sandbox only: no AWS account
  secret_key                  = "offline"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}
HCL
cat > main.tf <<'HCL'
resource "aws_security_group" "db" {
  name = "linkly-db"
  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
resource "aws_db_instance" "main" {
  identifier          = "linkly"
  engine              = "postgres"
  engine_version      = "17"
  instance_class      = "db.t4g.micro"
  allocated_storage   = 20
  username            = "linkly"
  password            = "hunter2hunter2"
  storage_encrypted   = false
  skip_final_snapshot = true
}
HCL
cat > ../policy/database.rego <<'REGO'
package terraform

changes(type) := [rc |
	some rc in input.resource_changes
	rc.type == type
	some action in rc.change.actions
	action in {"create", "update"}
]

deny contains msg if {
	some rc in changes("aws_db_instance")
	not rc.change.after.storage_encrypted
	msg := sprintf("%s: storage_encrypted must be true", [rc.address])
}

deny contains msg if {
	some rc in changes("aws_db_instance")
	rc.change.after.password != null
	msg := sprintf("%s: use password_wo (write-only) or manage_master_user_password, never password", [rc.address])
}

deny contains msg if {
	some rc in changes("aws_security_group")
	some rule in rc.change.after.ingress
	"0.0.0.0/0" in rule.cidr_blocks
	rule.from_port <= 5432
	rule.to_port >= 5432
	msg := sprintf("%s: PostgreSQL (5432) open to 0.0.0.0/0", [rc.address])
}

deny contains msg if {
	some rc in input.resource_changes
	rc.type in {"aws_db_instance", "aws_rds_cluster"}
	"delete" in rc.change.actions
	msg := sprintf("%s: deleting a database needs a manual, reviewed apply", [rc.address])
}
REGO
tofu init > /dev/null
tofu plan -out=tfplan > /dev/null
tofu show -json tfplan > plan.json
echo "the plan JSON contains the password: $(grep -c hunter2hunter2 plan.json) line(s)"
conftest test --namespace terraform -p ../policy plan.json; echo "exit $?"
the plan JSON contains the password: 1 line(s)
FAIL - plan.json - terraform - aws_db_instance.main: storage_encrypted must be true
FAIL - plan.json - terraform - aws_db_instance.main: use password_wo (write-only) or manage_master_user_password, never password
FAIL - plan.json - terraform - aws_security_group.db: PostgreSQL (5432) open to 0.0.0.0/0

4 tests, 1 passed, 0 warnings, 3 failures, 0 exceptions
exit 1

The second rule exists because of the first line of output: a password argument puts the secret into the plan file and state, in plain text (How Secrets Leak).

The fixed version: password from Vault, never in the plan

The AWS provider's write-only argument password_wo (with password_wo_version to signal changes) is sent to the API but never stored in the plan or state, and an ephemeral variable can't be persisted either. The pipeline reads the value from Vault into TF_VAR_db_password right before planning:

bash · try it yourself
vault server -dev -dev-root-token-id=root -dev-listen-address=127.0.0.1:8200 > vault.log 2>&1 &
for i in $(seq 50); do vault status > /dev/null 2>&1 && break; sleep 0.2; done
export VAULT_TOKEN=root
vault kv put -mount=secret linkly/db password='Xk29-pQm8-vR4z' > /dev/null

mkdir -p infra policy && cd infra
cat > main.tf <<'HCL'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}
provider "aws" {
  region                      = "eu-west-1"
  access_key                  = "offline"
  secret_key                  = "offline"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}
variable "db_password" {
  type      = string
  sensitive = true
  ephemeral = true          # may only flow into write-only arguments and other ephemeral contexts
}
resource "aws_security_group" "db" {
  name = "linkly-db"
  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["10.20.0.0/16"]
  }
}
resource "aws_db_instance" "main" {
  identifier          = "linkly"
  engine              = "postgres"
  engine_version      = "17"
  instance_class      = "db.t4g.micro"
  allocated_storage   = 20
  username            = "linkly"
  password_wo         = var.db_password
  password_wo_version = 1                 # bump to push a rotated password
  storage_encrypted   = true
  skip_final_snapshot = true
}
HCL
cat > ../policy/database.rego <<'REGO'
package terraform

deny contains msg if {
	some rc in input.resource_changes
	rc.type == "aws_db_instance"
	not rc.change.after.storage_encrypted
	msg := sprintf("%s: storage_encrypted must be true", [rc.address])
}

deny contains msg if {
	some rc in input.resource_changes
	rc.type == "aws_db_instance"
	rc.change.after.password != null
	msg := sprintf("%s: use password_wo, never password", [rc.address])
}
REGO

export TF_VAR_db_password="$(vault kv get -mount=secret -field=password linkly/db)"
tofu init > /dev/null
tofu plan -out=tfplan | grep -E 'password_wo|Plan:'
tofu show -json tfplan > plan.json
echo "password in plan.json: $(grep -c "$TF_VAR_db_password" plan.json), in tfplan: $(grep -ac "$TF_VAR_db_password" tfplan)"
conftest test --namespace terraform -p ../policy plan.json
      + password_wo                           = (write-only attribute)
      + password_wo_version                   = 1
Plan: 2 to add, 0 to change, 0 to destroy.
password in plan.json: 0, in tfplan: 0

2 tests, 2 passed, 0 warnings, 0 failures, 0 exceptions

Write-only arguments need OpenTofu 1.11+ or Terraform 1.11+ and a provider that offers them (password_wo on aws_db_instance, secret_string_wo on aws_secretsmanager_secret_version, and more each release). Where none exists, manage_master_user_password = true lets RDS keep the password in AWS Secrets Manager itself.

Plans vs .tf files

Conftest can also parse .tf files directly (conftest test main.tf, HCL2 parser): fast and needs no init, but it sees variables and module calls unresolved. Use both: HCL checks for style rules ("every module is pinned to a version"), plan checks for everything about the outcome.

bash · try it yourself
mkdir -p policy
cat > policy/modules.rego <<'REGO'
package main

deny contains msg if {
	some name, calls in input.module
	some m in calls
	startswith(m.source, "git::")
	not contains(m.source, "?ref=")
	msg := sprintf("module %q: pin git sources with ?ref=<tag>", [name])
}
REGO
cat > main.tf <<'HCL'
module "network" {
  source = "git::https://git.acme.internal/infra/modules.git//network?ref=v3.2.0"
}
module "database" {
  source = "git::https://git.acme.internal/infra/modules.git//database"
}
HCL
conftest parse main.tf | jq -c '.module | keys'
conftest test main.tf
["database","network"]
FAIL - main.tf - main - module "database": pin git sources with ?ref=<tag>

1 test, 0 passed, 0 warnings, 1 failure, 0 exceptions

Test yourself

Why do policies usually read resource_changes[].change.after?

  1. It contains the old state
  2. It holds each resource's planned attribute values after the change
  3. It lists providers
  4. It is the only field in plan JSON

What makes password_wo better than password on aws_db_instance?

  1. It is encrypted with AES
  2. It is write-only: sent to the provider but never stored in the plan or state
  3. It rotates automatically
  4. It works without Vault

What is a limitation of running Conftest on .tf files instead of plans?

  1. It can't parse HCL
  2. Variables, expressions and module internals are unresolved, so final values are unknown
  3. It requires AWS credentials
  4. It only works with OpenTofu