#Why this matters
Cloud misconfigurations in IAM roles, security groups, and storage buckets rarely begin in a web console today. Engineering teams define entire cloud accounts in HashiCorp Configuration Language (HCL) using Terraform and reuse those templates across development, staging, and production.
That automation cuts both ways. A single insecure default inside a shared module replicates across dozens of accounts in minutes. Conversely, auditing HCL before terraform apply runs lets defenders eliminate whole classes of exposure while the infrastructure is still plain text in a pull request.
#How IaC shifts the cloud threat surface
Terraform reads .tf files, builds a dependency graph, compares desired resources against recorded state, and calls cloud provider APIs. Because the configuration lives in Git, security teams can inspect infrastructure changes with the same automated gates used for application code.
- Author HCLWrite Terraform modules
- Static ScanRun Checkov and tfsec
- Plan ReviewInspect terraform plan diff
- Remote StateLock and encrypt state file
- ApplyProvision cloud resources
Three IaC-specific failure modes deserve special attention:
- Default-open resource definitions: Copy-pasted examples often omit encryption, access logging, or public-access blocks.
- Unpinned external modules: Pulling a module from a Git branch or unpinned registry version allows upstream changes to alter your cloud permissions silently.
- Exposed state files: Terraform records resource metadata in
terraform.tfstate, which can include initial database passwords, private keys, or token outputs in plaintext JSON.
#Common Terraform misconfigurations
Most high-severity findings in cloud posture audits map directly back to a few recurring HCL patterns.
| Resource area | Insecure HCL pattern | Cloud impact | Hardened pattern |
|---|---|---|---|
| Object storage | Bucket without public-access block or encryption | Public data leak or unencrypted objects at rest | Enforce aws_s3_bucket_public_access_block and KMS/AES encryption |
| Network ingress | Security group with 0.0.0.0/0 on port 22 or 3389 |
Internet-wide brute force against management ports | Restrict CIDR blocks to bastion or VPN ranges |
| IAM policies | Wildcard "Action": "*" on "Resource": "*" |
Full account compromise if workload is breached | Scope actions and resource ARNs to least privilege |
| Compute metadata | EC2 instance allowing IMDSv1 (http_tokens = "optional") |
SSRF vulnerabilities can steal instance role tokens | Set http_tokens = "required" to enforce IMDSv2 |
Consider this vulnerable security group and storage configuration in a lab module:
resource "aws_security_group" "admin_sg" {
name = "lab-admin-sg"
description = "Admin access"
ingress {
description = "SSH from anywhere"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_s3_bucket" "artifacts" {
bucket = "lab-local-build-artifacts"
}Here, admin_sg opens SSH to the entire internet, and artifacts relies on defaults without explicit public-access blocks, encryption configuration, or versioning. Fixing the security group narrows the CIDR block to the lab management subnet 10.10.10.0/24 and adds a clear description. Fixing the bucket pairs aws_s3_bucket with aws_s3_bucket_public_access_block (all four flags set to true) and aws_s3_bucket_server_side_encryption_configuration.
resource "aws_security_group" "admin_sg" {
name = "lab-admin-sg"
description = "Admin access from management subnet"
vpc_id = aws_vpc.lab.id
ingress {
description = "SSH from lab management subnet"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.10.10.0/24"]
}
}
resource "aws_s3_bucket_public_access_block" "artifacts_block" {
bucket = aws_s3_bucket.artifacts.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}#Static scanning with Checkov and tfsec
Static IaC scanners parse HCL (and optionally rendered terraform plan JSON) into an abstract graph and evaluate built-in security rules without touching a live cloud account. Checkov and tfsec (now also integrated into Trivy) are widely used in pull-request pipelines because they run in seconds and return a non-zero exit code when checks fail.
$ checkov -d ./infra --framework terraform --compact
terraform scan results:
Passed checks: 14, Failed checks: 2, Skipped checks: 0
Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
FAILED for resource: aws_security_group.admin_sg
File: /network.tf:1-12
Check: CKV_AWS_145: "Ensure that S3 buckets are encrypted with KMS by default"
FAILED for resource: aws_s3_bucket.artifacts
File: /storage.tf:1-3
$ tfsec ./infra --no-color
Result #1 HIGH Security group rule allows ingress from public internet.
/network.tf:9Scanning raw .tf files catches static mistakes, but dynamic expressions using var.*, for_each, or locals may only resolve at plan time. Exporting a binary plan and converting it to JSON lets Checkov inspect resolved values before any resource is created:
$ terraform plan -out=tfplan.binary
$ terraform show -json tfplan.binary > tfplan.json
$ checkov -f tfplan.jsonWhen a rule genuinely does not apply (for example, a dedicated public CDN origin bucket), never disable the scanner globally. Use an inline suppression with an explicit reason so reviewers can audit the exception:
#checkov:skip=CKV_AWS_145:Lab artifact bucket uses SSE-S3 AES256 per baseline policy#Protecting state files, variables, and modules
Even flawless resource definitions fail if the surrounding Terraform workflow leaks secrets or drifts from reviewed code.
- Keep state out of Git: Add
*.tfstate,*.tfstate.*, and.terraform/to.gitignore. Store state in a remote backend (such as an encrypted S3 bucket with access logging and DynamoDB or native lockfile locking, or Terraform Cloud) restricted to the deployment role. - Never hardcode secrets in
.tfor.tfvars: Pass credentials via short-lived OIDC roles or a secrets manager data source rather than plaintext variables. Remember that marking a variablesensitive = truehides it from CLI stdout, not fromterraform.tfstate. - Pin providers and modules: Commit
.terraform.lock.hclto version control so every runner verifies the same provider checksums. Pin third-party module versions (version = "5.1.2") or immutable Git commit hashes instead of floating branches.
#Defending and common mistakes
- Skipping
terraform planinspection: Attackers or accidental edits can trigger destructive recreations or IAM changes. Always review the plan diff in pull requests before approval. - Adding blank suppressions: Writing
#checkov:skip=CKV_AWS_...without a reason bypasses policy enforcement. Require peer review on any suppression comment. - Scanning only
.tfand ignoringtfplan.json: Variable defaults may look harmless in a module while production.tfvarspass0.0.0.0/0. Scan the rendered plan in CI. - Running
terraform applyfrom laptops: Developer workstations accumulate cached admin keys and stale state. Execute applies only from hardened CI runners with least-privilege roles.
#Summary
Terraform turns cloud architecture into reviewable code, which means security controls can be verified before any API call runs. Static scanners like Checkov and tfsec detect open security groups, unencrypted storage, and wildcard IAM policies directly in HCL and rendered JSON plans. Combining automated policy gates with encrypted remote state, locked provider checksums, and pinned modules prevents misconfigurations from scaling across environments.