Terraform Security Best Practices for AWS: 2026 Edition

A guide to securing Terraform-managed AWS infrastructure in 2026, from OIDC authentication and state protection to policy as code and supply-chain hardening.

By VVVHQ Team ·

Infrastructure as code made AWS environments reviewable and repeatable, and it also made a mistake repeatable. One public bucket or open security group in a shared module ends up in every environment that uses it. This guide covers the practices we would put in place for any team running AWS with Terraform, from credentials and state to policy checks and the provider supply chain.

Everything here applies to OpenTofu as well, the open-source fork created after HashiCorp moved Terraform to the Business Source License in 2023. Where the two differ, the text says so.

Remove static credentials with OIDC

Long-lived AWS access keys in CI/CD are the first thing to remove. They do not expire, they leak into logs and forks, and a leaked key keeps working until someone notices. GitHub Actions, GitLab CI and the other major platforms can instead exchange a short-lived OIDC token for temporary AWS credentials:

# GitHub Actions OIDC provider
resource "aws_iam_openid_connect_provider" "github" {
  url             = "https://token.actions.githubusercontent.com"
  client_id_list  = ["sts.amazonaws.com"]
  thumbprint_list = [data.tls_certificate.github.certificates[0].sha1_fingerprint]
}

resource "aws_iam_role" "terraform_deploy" {
  name = "terraform-deploy"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Federated = aws_iam_openid_connect_provider.github.arn }
      Action    = "sts:AssumeRoleWithWebIdentity"
      Condition = {
        StringEquals = {
          "token.actions.githubusercontent.com:aud" = "sts.amazonaws.com"
          "token.actions.githubusercontent.com:sub" = "repo:your-org/your-repo:environment:production"
        }
      }
    }]
  })
}

The sub condition ties the role to one repository and one GitHub environment, so only jobs that passed that environment's protection rules can assume it. The credentials expire after an hour by default. The pipelines we build deploy into AWS with no long-lived access keys.

Protect the state

Terraform state holds a full map of your infrastructure and, unless you take steps, sensitive values in plain text. Treat it like a database dump.

terraform {
  backend "s3" {
    bucket       = "your-org-terraform-state"
    key          = "prod/infrastructure.tfstate"
    region       = "us-east-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:us-east-1:ACCOUNT:key/KEY_ID"
    use_lockfile = true # S3 native locking, Terraform 1.10+ and OpenTofu 1.10+
  }
}

The S3 backend can now lock state with a lock file in the bucket itself, and Terraform deprecated the DynamoDB lock table in 1.11. For the state bucket, use a customer-managed KMS key, versioning, all four Block Public Access settings, access logging to a separate bucket, and replication to a second region for production. Restrict who can read it: anyone who can read production state can read whatever secrets it holds.

Keep secrets out of state where you can. Terraform 1.10 added ephemeral values that are never written to state, and 1.11 added write-only arguments for passwords and similar inputs. OpenTofu can encrypt the whole state file on the client side, a feature it has had since 1.7.

Policy as code in three layers

Static analysis on every pull request

Scan the Terraform code before plan runs. Checkov and trivy config (which now carries the former tfsec checks) find public buckets, unencrypted databases, wide-open security groups and missing logging:

- name: Trivy config scan
  uses: aquasecurity/trivy-action@<commit-sha>  # pin to a full commit SHA
  with:
    scan-type: config
    scan-ref: ./terraform
    severity: HIGH,CRITICAL
    exit-code: '1'

- name: Checkov scan
  uses: bridgecrewio/checkov-action@<commit-sha>
  with:
    directory: ./terraform
    framework: terraform

Checks on the plan

Static analysis cannot see values computed at plan time. Export the plan with terraform show -json plan.out > plan.json and test it with Open Policy Agent and Conftest. In OPA 1.0 syntax:

package terraform.s3

deny contains msg if {
    some rc in input.resource_changes
    rc.type == "aws_s3_bucket_public_access_block"
    rc.change.after.block_public_acls != true
    msg := sprintf("%s must block public ACLs", [rc.address])
}

HCP Terraform and Terraform Enterprise run Sentinel or OPA policy sets natively.

Checks on what is deployed

AWS Config rules or Prowler verify the running estate, and drift detection catches changes made outside the pipeline. For a healthtech AI startup we built a 7-account, 3-region AWS organization in Terraform with an organization-wide rule requiring HTTPS for S3, which reported compliant on 13 of 13 buckets.

Least-privilege IAM

Overly broad roles turn a small compromise into a large one. Attach a permissions boundary to every role Terraform creates, so even a mistaken policy cannot grant more than the boundary allows:

resource "aws_iam_role" "app" {
  name                 = "app-service-role"
  permissions_boundary = aws_iam_policy.workload_boundary.arn

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy_attachment" "app" {
  role       = aws_iam_role.app.name
  policy_arn = aws_iam_policy.app.arn
}

IAM Access Analyzer can generate a least-privilege policy from a role's CloudTrail activity, which is a better starting point than a guess. Replace any remaining access keys with roles or OIDC, and rotate the ones you cannot remove yet. Tag IAM resources with an owner, and use the tags for attribute-based access control where it fits. In bucket policies, aws:SourceVpce limits access to requests that arrive through your VPC endpoints.

Encryption with KMS

resource "aws_kms_key" "main" {
  description             = "Main encryption key"
  deletion_window_in_days = 30
  enable_key_rotation     = true
  rotation_period_in_days = 90

  policy = data.aws_iam_policy_document.kms_policy.json
}

resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
  bucket = aws_s3_bucket.data.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.main.arn
    }
    bucket_key_enabled = true
  }
}

S3 has encrypted every new object by default since January 2023, so the old bucket policy that rejects uploads without encryption headers adds little. Set a default SSE-KMS configuration where you need your own key and its audit trail, and add a bucket policy that denies requests where aws:SecureTransport is false. S3 Bucket Keys reduce the number of KMS requests, and AWS says they cut KMS request costs by up to 99%.

Network controls

Terraform makes it easy to open port 22 to 0.0.0.0/0 and forget about it. Allow ingress from anywhere only on public load balancers, on 80 and 443. For internal traffic, reference security groups instead of CIDR blocks, give each service its own group, and enable VPC Flow Logs on every production VPC.

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0" # pin the major version you have tested

  name = "production"
  cidr = "10.0.0.0/16"
  azs  = ["us-east-1a", "us-east-1b", "us-east-1c"]

  private_subnets  = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets   = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
  database_subnets = ["10.0.201.0/24", "10.0.202.0/24", "10.0.203.0/24"]

  enable_dns_hostnames = true
  enable_dns_support   = true

  enable_nat_gateway = true
  single_nat_gateway = false # one NAT gateway per AZ in production

  enable_flow_log                      = true
  create_flow_log_cloudwatch_log_group = true
  create_flow_log_iam_role             = true
}

Use VPC endpoints for AWS services to keep that traffic off the internet. For blocking known malicious addresses, AWS WAF IP sets or AWS Network Firewall scale better than network ACLs, which have a small rule limit.

Provider and module supply chain

Providers run with your cloud credentials, so a compromised one can read or change anything the pipeline can.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

Commit .terraform.lock.hcl, which pins the exact provider version and its checksums, and run terraform providers lock for every platform your team and CI use. terraform init verifies provider signatures from the registry. Let Renovate or Dependabot propose provider updates as pull requests, so each upgrade gets a plan and a review. Pin modules to exact version tags, never to a branch, read a module's code before adopting it, and consider a private registry or proxy for approved providers and modules.

The checklist

  1. Credentials: OIDC for every pipeline, no static keys.
  2. State: encrypted, locked, versioned, access-logged, and as free of secrets as possible.
  3. Policy: Checkov and trivy config on pull requests, OPA or Sentinel on plans, AWS Config or Prowler on the running estate.
  4. IAM: permissions boundaries on every role, policies generated from real activity.
  5. Encryption: KMS with rotation for data stores, TLS required on buckets.
  6. Network: narrow security groups, VPC endpoints, flow logs.
  7. Supply chain: committed lock files, pinned modules, reviewed upgrades.

The same controls work on an existing estate. On one engagement we split a Terraform monolith into 10 roots and moved 457 resources without destroying one. Ask for a review of your own Terraform against this list.

Tags: terraform, aws security, infrastructure as code, cloud security, iac security