Mini Project: A Policy Gate for linkly
The course's milestone project: a pipeline gate that rejects a Terraform plan and a Kubernetes manifest that break policy, while linkly's database password is served by Vault and never appears in the repository, the plan or the manifests. It joins most of the course into one script that runs the same way on a laptop and in CI.
The plan
linkly/
├── infra/main.tf # RDS PostgreSQL + security group; password via password_wo from an ephemeral variable
├── deploy/linkly.yaml # Deployment (+ ExternalSecret once fixed)
├── policy/
│ ├── terraform/rds.rego # deny: unencrypted DB, plain password, 5432 open to the world, DB deletion; warn: owner tag
│ ├── terraform/rds_test.rego
│ ├── k8s/workloads.rego # deny: :latest, literal secrets in env, plain Secrets in Git
│ └── k8s/workloads_test.rego
└── gate.sh # secret scan → policy tests → plan with Vault → conftest on plan → conftest on manifestsRequirements:
- Vault holds linkly's database password (KV v2,
secret/linkly/db), generated by a machine, never typed or committed (KV v2). - The pipeline has its own identity: an AppRole with a read-only policy on exactly that path, batch tokens, and single-use secret ids (Auth Methods). In GitHub Actions or GitLab CI you would use JWT/OIDC instead (below).
- Terraform receives the password without storing it: an ephemeral variable feeding
password_wo(Conftest on Terraform Plans); the gate proves the plan doesn't contain it. - Policies with tests: every rule has a test that proves it fires (Testing Policies).
- The gate reports every failure in one run and exits non-zero if any check failed.
- The app gets the password from Vault at runtime through an ExternalSecret, not from the manifest (External Secrets & Sealed Secrets).
Try building it yourself first; the session below is one complete solution. It plays two pull requests: the first breaks four rules, the second fixes them.
The session
# ---------- Vault: linkly's DB password and a CI identity ----------
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 username=linkly password="$(head -c 18 /dev/urandom | base64)" > /dev/null
vault policy write linkly-ci - > /dev/null <<'HCL'
path "secret/data/linkly/db" {
capabilities = ["read"]
}
HCL
vault auth enable approle > /dev/null
vault write auth/approle/role/linkly-ci token_policies=linkly-ci token_ttl=10m token_type=batch \
secret_id_ttl=10m secret_id_num_uses=1 > /dev/null
export CI_ROLE_ID=$(vault read -field=role_id auth/approle/role/linkly-ci/role-id)
unset VAULT_TOKEN # from here on, only the pipeline's own identity
# ---------- the repository ----------
mkdir -p linkly/{infra,deploy,policy/terraform,policy/k8s} && cd linkly
cat > infra/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
}
resource "aws_security_group" "db" {
name = "linkly-db"
ingress {
from_port = 5432
to_port = 5432
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags = { owner = "team-links" }
}
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
storage_encrypted = false
skip_final_snapshot = true
tags = { owner = "team-links" }
}
HCL
cat > deploy/linkly.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly, namespace: linkly}
spec:
selector: {matchLabels: {app: linkly}}
template:
metadata: {labels: {app: linkly}}
spec:
containers:
- name: app
image: ghcr.io/acme/linkly:latest
env:
- name: DATABASE_PASSWORD
value: "changeme-later"
YAML
cat > policy/terraform/rds.rego <<'REGO'
package terraform
writes(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 writes("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 writes("aws_db_instance")
rc.change.after.password != null
msg := sprintf("%s: use password_wo, never password", [rc.address])
}
deny contains msg if {
some rc in writes("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 open to 0.0.0.0/0", [rc.address])
}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_db_instance"
"delete" in rc.change.actions
msg := sprintf("%s: database deletion needs a manual apply", [rc.address])
}
warn contains msg if {
some rc in input.resource_changes
"create" in rc.change.actions
not rc.change.after.tags.owner
msg := sprintf("%s: add an owner tag", [rc.address])
}
REGO
cat > policy/terraform/rds_test.rego <<'REGO'
package terraform_test
import data.terraform
db(after) := {"resource_changes": [{"address": "aws_db_instance.main", "type": "aws_db_instance",
"change": {"actions": ["create"], "after": after}}]}
test_unencrypted_denied if {
"aws_db_instance.main: storage_encrypted must be true" in terraform.deny with input as db({"password": null})
}
test_plain_password_denied if {
"aws_db_instance.main: use password_wo, never password" in terraform.deny with input as db({"storage_encrypted": true, "password": "x"})
}
test_compliant_db_allowed if {
count(terraform.deny) == 0 with input as db({"storage_encrypted": true, "password": null})
}
test_db_delete_denied if {
count(terraform.deny) == 1 with input as {"resource_changes": [{"address": "aws_db_instance.main",
"type": "aws_db_instance", "change": {"actions": ["delete"], "after": null}}]}
}
test_open_postgres_denied if {
count(terraform.deny) == 1 with input as {"resource_changes": [{"address": "aws_security_group.db",
"type": "aws_security_group", "change": {"actions": ["create"], "after": {"ingress": [
{"from_port": 0, "to_port": 65535, "cidr_blocks": ["0.0.0.0/0"]}]}}}]}
}
REGO
cat > policy/k8s/workloads.rego <<'REGO'
package k8s
containers contains c if {
input.kind == "Deployment"
some c in input.spec.template.spec.containers
}
deny contains msg if {
some c in containers
not contains(c.image, "@sha256:")
endswith(c.image, ":latest")
msg := sprintf("%s: container %q must not use :latest", [input.metadata.name, c.name])
}
deny contains msg if {
some c in containers
some e in c.env
regex.match(`(?i)(password|secret|token|api_key)`, e.name)
e.value
msg := sprintf("%s: %s is a literal value; use secretKeyRef to a Secret synced from Vault", [input.metadata.name, e.name])
}
deny contains msg if {
input.kind == "Secret"
not input.sops.mac
msg := sprintf("Secret %s has plain values in Git; use an ExternalSecret", [input.metadata.name])
}
REGO
cat > policy/k8s/workloads_test.rego <<'REGO'
package k8s_test
import data.k8s
deploy(c) := {"kind": "Deployment", "metadata": {"name": "linkly"}, "spec": {"template": {"spec": {"containers": [c]}}}}
test_latest_denied if {
count(k8s.deny) == 1 with input as deploy({"name": "app", "image": "x:latest"})
}
test_literal_password_denied if {
count(k8s.deny) == 1 with input as deploy({"name": "app", "image": "x:1", "env": [{"name": "DB_PASSWORD", "value": "x"}]})
}
test_secret_ref_allowed if {
count(k8s.deny) == 0 with input as deploy({"name": "app", "image": "x:1",
"env": [{"name": "DB_PASSWORD", "valueFrom": {"secretKeyRef": {"name": "linkly-db", "key": "password"}}}]})
}
test_plain_secret_denied if {
count(k8s.deny) == 1 with input as {"kind": "Secret", "metadata": {"name": "s"}, "stringData": {"a": "b"}}
}
REGO
cat > gate.sh <<'SH'
#!/bin/bash
# Pipeline gate: run every check, report all failures, exit non-zero if any failed.
set -uo pipefail
status=0
step() { printf '\n== %s\n' "$1"; }
step "secret scan"
gitleaks dir . --no-banner --redact > /dev/null 2>&1 && echo "no secrets found" || { echo "secrets found"; status=1; }
step "policy unit tests"
opa test policy/ > /dev/null && echo "all policy tests pass" || { opa test policy/; status=1; }
step "terraform plan (password from Vault)"
export VAULT_TOKEN=$(vault write -field=token auth/approle/login role_id="$CI_ROLE_ID" secret_id="$CI_SECRET_ID")
export TF_VAR_db_password=$(vault kv get -mount=secret -field=password linkly/db)
( cd infra && tofu init > /dev/null && tofu plan -out=tfplan > /dev/null && tofu show -json tfplan > plan.json ) || status=1
leaks=$(grep -cF -- "$TF_VAR_db_password" infra/plan.json)
echo "plan written; occurrences of the DB password in plan.json: $leaks"
[ "$leaks" -eq 0 ] || status=1
unset TF_VAR_db_password VAULT_TOKEN
step "policy: terraform plan"
conftest test --no-color --namespace terraform -p policy/terraform infra/plan.json || status=1
step "policy: kubernetes manifests"
conftest test --no-color --namespace k8s -p policy/k8s deploy/ || status=1
printf '\n== result: %s\n' "$([ $status -eq 0 ] && echo PASSED || echo FAILED)"
exit $status
SH
chmod +x gate.sh
# ---------- pull request #1 ----------
export CI_SECRET_ID=$(VAULT_TOKEN=root vault write -f -field=secret_id auth/approle/role/linkly-ci/secret-id)
echo "### pull request #1"
./gate.sh; echo "exit $?"
# ---------- pull request #2: the fixes ----------
sed -i 's|cidr_blocks = \["0.0.0.0/0"\]|cidr_blocks = ["10.20.0.0/16"] # the private app subnets only|' infra/main.tf
sed -i 's|storage_encrypted = false|storage_encrypted = true|' infra/main.tf
cat > deploy/linkly.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly, namespace: linkly}
spec:
selector: {matchLabels: {app: linkly}}
template:
metadata: {labels: {app: linkly}}
spec:
containers:
- name: app
image: ghcr.io/acme/linkly:1.4.2
env:
- name: DATABASE_PASSWORD
valueFrom: {secretKeyRef: {name: linkly-db, key: password}}
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: {name: linkly-db, namespace: linkly}
spec:
refreshInterval: 15m
secretStoreRef: {kind: ClusterSecretStore, name: vault}
target: {name: linkly-db}
data:
- secretKey: password
remoteRef: {key: linkly/db, property: password}
YAML
echo; echo "### re-using the first run's secret_id"
vault write auth/approle/login role_id="$CI_ROLE_ID" secret_id="$CI_SECRET_ID" 2>&1 | grep -E '^\*'
export CI_SECRET_ID=$(VAULT_TOKEN=root vault write -f -field=secret_id auth/approle/role/linkly-ci/secret-id)
echo "### pull request #2"
./gate.sh; echo "exit $?"### pull request #1
== secret scan
no secrets found
== policy unit tests
all policy tests pass
== terraform plan (password from Vault)
plan written; occurrences of the DB password in plan.json: 0
== policy: terraform plan
FAIL - infra/plan.json - terraform - aws_db_instance.main: storage_encrypted must be true
FAIL - infra/plan.json - terraform - aws_security_group.db: PostgreSQL open to 0.0.0.0/0
5 tests, 3 passed, 0 warnings, 2 failures, 0 exceptions
== policy: kubernetes manifests
FAIL - deploy/linkly.yaml - k8s - linkly: DATABASE_PASSWORD is a literal value; use secretKeyRef to a Secret synced from Vault
FAIL - deploy/linkly.yaml - k8s - linkly: container "app" must not use :latest
3 tests, 1 passed, 0 warnings, 2 failures, 0 exceptions
== result: FAILED
exit 1
### re-using the first run's secret_id
* invalid role or secret ID
### pull request #2
== secret scan
no secrets found
== policy unit tests
all policy tests pass
== terraform plan (password from Vault)
plan written; occurrences of the DB password in plan.json: 0
== policy: terraform plan
5 tests, 5 passed, 0 warnings, 0 failures, 0 exceptions
== policy: kubernetes manifests
6 tests, 6 passed, 0 warnings, 0 failures, 0 exceptions
== result: PASSED
exit 0
Walking through it
Pull request #1 passed the secret scan and the policy tests, and the password from Vault didn't leak into the plan, but the gate still failed with four precise messages:
- the plan creates an unencrypted database and opens 5432 to 0.0.0.0/0: two Terraform rules, evaluated on the real plan JSON, so they would also catch the same values coming from a module or a variable;
- the manifest uses
:latestand puts a literal password into an environment variable: two Kubernetes rules.
Between the runs, the old secret_id was rejected: it had been used once by the first pipeline run. Each run gets a fresh one, valid for 10 minutes, so a secret id copied from a CI log is worthless.
Pull request #2 restricts the security group to the app subnets, enables storage encryption, pins the image, and replaces the literal value with a secretKeyRef to a Secret that the ExternalSecret syncs from secret/linkly/db in Vault. The same password now reaches both consumers, RDS (through Terraform's write-only argument) and the pods (through ESO), without ever being written to Git, the plan or the state.
Running it in GitHub Actions
In CI, replace the AppRole with the job's OIDC token (JWT/OIDC Auth for CI): no secret id to deliver at all.
# .github/workflows/gate.yml (non-run)
name: policy-gate
on: pull_request
permissions:
contents: read
id-token: write
jobs:
gate:
runs-on: ubuntu-24.04
environment: plan # bound in the Vault JWT role
steps:
- uses: actions/checkout@v7
- name: Install pinned tools
run: ./ci/install-tools.sh # tofu, opa 1.21.4, conftest 0.71.1, gitleaks 8.30.1, vault 2.2.1; checksums verified
- name: Vault login
run: |
ID_TOKEN=$(curl -sH "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://github.com/acme" | jq -r .value)
echo "VAULT_TOKEN=$(vault write -field=token auth/jwt/login role=linkly-plan jwt=$ID_TOKEN)" >> "$GITHUB_ENV"
env:
VAULT_ADDR: https://vault.acme.internal:8200
- run: ./gate.sh
env:
VAULT_ADDR: https://vault.acme.internal:8200(gate.sh then skips its own AppRole login when VAULT_TOKEN is already set; a two-line change.)
Extensions
- Admission parity: write the two Kubernetes rules as a Kyverno
ValidatingPolicywith akyverno-test.yaml, and addkyverno testto the gate (In the Cluster). - Exceptions with expiry: allow one team a temporary exception through a data file, as in Field Notes.
- Dynamic credentials: switch linkly from the static KV password to a
database/creds/linkly-approle and aVaultDynamicSecret(Dynamic Database Credentials). - Rotation drill: write a script that rotates the password in Vault, bumps
password_wo_version, and checks that the ExternalSecret picks it up (Rotation Without Downtime). - SARIF reports: produce
conftest test -o sarifandgitleaks --report-format sarifso findings appear in the pull request's code-scanning view.
Test yourself
How does the gate prove that linkly's password did not end up in the Terraform plan?
- It trusts
sensitive = true - It searches plan.json for the value it read from Vault and fails on any occurrence
- It deletes the plan
- Conftest hides it
Why did the second login with the first run's secret_id fail?
- Vault was restarted
- The AppRole was configured with
secret_id_num_uses=1, so each secret id works exactly once - The policy changed
- The token expired
Why does the gate keep going after a failed step instead of stopping at the first error?
- Bash can't stop early
- So one pipeline run shows every problem to fix, while still exiting non-zero
- To save time
- Conftest requires it