Apply IaC Security
Scan Infrastructure as Code templates for misconfigurations, enforce least-privilege IAM, and validate security controls in CI — catching S3 public buckets, open security groups, and over-permissive roles before they reach production.
Why This Is Best Practice
Adopted by: OWASP Infrastructure as Code Security Cheat Sheet defines the standard. CIS Benchmarks for AWS (v3.0), GCP (v2.0), and Azure (v2.0) are the authoritative hardening references. Bridgecrew (acquired by Palo Alto Networks), Checkov, and tfsec are used by Netflix, Shopify, and Stripe in their CI pipelines. AWS Security Hub and GCP Security Command Center both consume misconfig signals from IaC scanners.
Impact: Palo Alto Unit 42 (2021) found that 65% of cloud security incidents involved misconfigured IaC — public S3 buckets, overly permissive IAM roles, and unrestricted security groups. The 2019 Capital One breach (106M records) exploited an overly permissive IAM role on an EC2 instance. Checkov scans catch these classes in under 30 seconds before the terraform apply reaches production. CSPM tools report remediating IaC-caught misconfigs is 10× cheaper than post-deployment.
Why best: Runtime cloud security scanning (CSPM) finds misconfigurations after they're deployed — the IaC scanner finds them at PR time, before any resource exists. IaC scanning integrates with existing CI without requiring cloud credentials; CSPM requires a running environment and cloud API access. Combined approach (scan in CI + CSPM in production) provides defense-in-depth.
Sources: OWASP IaC Security Cheat Sheet; CIS AWS Benchmark v3.0; Bridgecrew State of Open Source Terraform Security Report (2022); Palo Alto Unit 42 Cloud Threat Report (2021)
Steps
Scan Terraform with Checkov in CI — fail the pipeline on HIGH/CRITICAL:
# Install
pip install checkov
# Scan a directory
checkov -d ./infrastructure --framework terraform \
--check CKV_AWS_18,CKV_AWS_19,CKV_AWS_20 \
--compact --quiet
# Fail on any HIGH or CRITICAL finding
checkov -d ./infrastructure --soft-fail-on MEDIUM,LOW
# GitHub Actions
- name: Checkov IaC scan
uses: bridgecrewio/checkov-action@master
with:
directory: infrastructure/
framework: terraform
soft_fail: false
output_format: github_failed_only
Fix the most common Terraform misconfigurations:
# S3: block public access + enable versioning + encrypt
resource "aws_s3_bucket" "app_data" {
bucket = "company-app-data"
}
resource "aws_s3_bucket_public_access_block" "app_data" {
bucket = aws_s3_bucket.app_data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_server_side_encryption_configuration" "app_data" {
bucket = aws_s3_bucket.app_data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
}
}
}
resource "aws_s3_bucket_versioning" "app_data" {
bucket = aws_s3_bucket.app_data.id
versioning_configuration { status = "Enabled" }
}
Enforce least-privilege IAM — no wildcard actions or resources:
# BAD — wildcard action on all resources
resource "aws_iam_policy" "bad_policy" {
policy = jsonencode({
Statement = [{
Effect = "Allow"
Action = "*"
Resource = "*"
}]
})
}
# GOOD — specific actions on specific resource ARNs
resource "aws_iam_policy" "app_policy" {
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject"
]
Resource = "${aws_s3_bucket.app_data.arn}/uploads/*"
},
{
Effect = "Allow"
Action = ["secretsmanager:GetSecretValue"]
Resource = aws_secretsmanager_secret.db_password.arn
}
]
})
}
Lock down security groups — no 0.0.0.0/0 ingress except ports 80/443:
resource "aws_security_group" "app" {
name = "app-sg"
vpc_id = aws_vpc.main.id
# Allow HTTPS from anywhere
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
# Allow internal communication only
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
security_groups = [aws_security_group.alb.id]
# NOT: cidr_blocks = ["0.0.0.0/0"]
}
# Restrict egress to known destinations
egress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
Never store secrets in IaC — use secret stores:
# BAD — secret in tfvars or hardcoded
resource "aws_db_instance" "main" {
password = "supersecret123" # visible in state file
}
# GOOD — fetch from Secrets Manager at runtime
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = "/production/db/password"
}
resource "aws_db_instance" "main" {
password = data.aws_secretsmanager_secret_version.db_password.secret_string
}
Terraform state also stores secrets — use remote state with encryption:
terraform {
backend "s3" {
bucket = "terraform-state-company"
key = "production/terraform.tfstate"
encrypt = true
kms_key_id = "arn:aws:kms:..."
}
}
Pin provider versions and module sources:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # no unpinned "latest"
}
}
}
# Pin modules to a specific tag — not a branch
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.2" # not: "main" or "latest"
}
Rules
- Never commit
terraform.tfstate or *.tfvars containing secrets — add both to .gitignore.
- Run
terraform plan before apply and review the diff — automated apply without review risks unintended resource deletion.
- Use separate Terraform workspaces or directories for dev/staging/production — never use the same state file.
- Enable MFA delete on the S3 bucket storing Terraform state to prevent accidental or malicious deletion.
Common Mistakes
0.0.0.0/0 on port 22 or 3389 — SSH/RDP open to the internet is the #1 cloud misconfiguration; use Systems Manager Session Manager instead.
- IAM roles with
sts:AssumeRole for * — allows any AWS principal to assume the role; always specify the trusted principal ARN.
- Ignoring
checkov violations with #checkov:skip — each skip should have a documented justification and tracked exception.
- Not encrypting RDS at rest —
storage_encrypted = true should be the default for any database with sensitive data.
1---2name: apply-iac-security3description: Use when writing Terraform, CloudFormation, Pulumi, or Bicep templates — to detect misconfigurations, enforce least privilege IAM, and prevent insecure defaults before infrastructure reaches production.4source: 'OWASP Infrastructure as Code Security Cheat Sheet (owasp.org/www-project-cheat-sheets); CIS AWS/GCP/Azure Benchmarks; Checkov documentation; tfsec documentation'5tags: [security, owasp, iac, terraform, cloudformation, cloud, devops, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-iac-security8---910# Apply IaC Security1112Scan Infrastructure as Code templates for misconfigurations, enforce least-privilege IAM, and validate security controls in CI — catching S3 public buckets, open security groups, and over-permissive roles before they reach production.1314## Why This Is Best Practice1516**Adopted by:** OWASP Infrastructure as Code Security Cheat Sheet defines the standard. CIS Benchmarks for AWS (v3.0), GCP (v2.0), and Azure (v2.0) are the authoritative hardening references. Bridgecrew (acquired by Palo Alto Networks), Checkov, and tfsec are used by Netflix, Shopify, and Stripe in their CI pipelines. AWS Security Hub and GCP Security Command Center both consume misconfig signals from IaC scanners.17**Impact:** Palo Alto Unit 42 (2021) found that 65% of cloud security incidents involved misconfigured IaC — public S3 buckets, overly permissive IAM roles, and unrestricted security groups. The 2019 Capital One breach (106M records) exploited an overly permissive IAM role on an EC2 instance. Checkov scans catch these classes in under 30 seconds before the `terraform apply` reaches production. CSPM tools report remediating IaC-caught misconfigs is 10× cheaper than post-deployment.18**Why best:** Runtime cloud security scanning (CSPM) finds misconfigurations after they're deployed — the IaC scanner finds them at PR time, before any resource exists. IaC scanning integrates with existing CI without requiring cloud credentials; CSPM requires a running environment and cloud API access. Combined approach (scan in CI + CSPM in production) provides defense-in-depth.1920Sources: OWASP IaC Security Cheat Sheet; CIS AWS Benchmark v3.0; Bridgecrew State of Open Source Terraform Security Report (2022); Palo Alto Unit 42 Cloud Threat Report (2021)2122## Steps23241. **Scan Terraform with Checkov in CI — fail the pipeline on HIGH/CRITICAL**:2526 ```bash27 # Install28 pip install checkov2930 # Scan a directory31 checkov -d ./infrastructure --framework terraform \32 --check CKV_AWS_18,CKV_AWS_19,CKV_AWS_20 \33 --compact --quiet3435 # Fail on any HIGH or CRITICAL finding36 checkov -d ./infrastructure --soft-fail-on MEDIUM,LOW37 ```3839 ```yaml40 # GitHub Actions41 - name: Checkov IaC scan42 uses: bridgecrewio/checkov-action@master43 with:44 directory: infrastructure/45 framework: terraform46 soft_fail: false47 output_format: github_failed_only48 ```49502. **Fix the most common Terraform misconfigurations**:5152 ```hcl53 # S3: block public access + enable versioning + encrypt54 resource "aws_s3_bucket" "app_data" {55 bucket = "company-app-data"56 }5758 resource "aws_s3_bucket_public_access_block" "app_data" {59 bucket = aws_s3_bucket.app_data.id60 block_public_acls = true61 block_public_policy = true62 ignore_public_acls = true63 restrict_public_buckets = true64 }6566 resource "aws_s3_bucket_server_side_encryption_configuration" "app_data" {67 bucket = aws_s3_bucket.app_data.id68 rule {69 apply_server_side_encryption_by_default {70 sse_algorithm = "aws:kms"71 }72 }73 }7475 resource "aws_s3_bucket_versioning" "app_data" {76 bucket = aws_s3_bucket.app_data.id77 versioning_configuration { status = "Enabled" }78 }79 ```80813. **Enforce least-privilege IAM — no wildcard actions or resources**:8283 ```hcl84 # BAD — wildcard action on all resources85 resource "aws_iam_policy" "bad_policy" {86 policy = jsonencode({87 Statement = [{88 Effect = "Allow"89 Action = "*"90 Resource = "*"91 }]92 })93 }9495 # GOOD — specific actions on specific resource ARNs96 resource "aws_iam_policy" "app_policy" {97 policy = jsonencode({98 Version = "2012-10-17"99 Statement = [100 {101 Effect = "Allow"102 Action = [103 "s3:GetObject",104 "s3:PutObject"105 ]106 Resource = "${aws_s3_bucket.app_data.arn}/uploads/*"107 },108 {109 Effect = "Allow"110 Action = ["secretsmanager:GetSecretValue"]111 Resource = aws_secretsmanager_secret.db_password.arn112 }113 ]114 })115 }116 ```1171184. **Lock down security groups — no `0.0.0.0/0` ingress except ports 80/443**:119120 ```hcl121 resource "aws_security_group" "app" {122 name = "app-sg"123 vpc_id = aws_vpc.main.id124125 # Allow HTTPS from anywhere126 ingress {127 from_port = 443128 to_port = 443129 protocol = "tcp"130 cidr_blocks = ["0.0.0.0/0"]131 }132133 # Allow internal communication only134 ingress {135 from_port = 8080136 to_port = 8080137 protocol = "tcp"138 security_groups = [aws_security_group.alb.id]139 # NOT: cidr_blocks = ["0.0.0.0/0"]140 }141142 # Restrict egress to known destinations143 egress {144 from_port = 443145 to_port = 443146 protocol = "tcp"147 cidr_blocks = ["0.0.0.0/0"]148 }149 }150 ```1511525. **Never store secrets in IaC — use secret stores**:153154 ```hcl155 # BAD — secret in tfvars or hardcoded156 resource "aws_db_instance" "main" {157 password = "supersecret123" # visible in state file158 }159160 # GOOD — fetch from Secrets Manager at runtime161 data "aws_secretsmanager_secret_version" "db_password" {162 secret_id = "/production/db/password"163 }164165 resource "aws_db_instance" "main" {166 password = data.aws_secretsmanager_secret_version.db_password.secret_string167 }168 ```169170 Terraform state also stores secrets — use remote state with encryption:171 ```hcl172 terraform {173 backend "s3" {174 bucket = "terraform-state-company"175 key = "production/terraform.tfstate"176 encrypt = true177 kms_key_id = "arn:aws:kms:..."178 }179 }180 ```1811826. **Pin provider versions and module sources**:183184 ```hcl185 terraform {186 required_providers {187 aws = {188 source = "hashicorp/aws"189 version = "~> 5.0" # no unpinned "latest"190 }191 }192 }193194 # Pin modules to a specific tag — not a branch195 module "vpc" {196 source = "terraform-aws-modules/vpc/aws"197 version = "5.1.2" # not: "main" or "latest"198 }199 ```200201## Rules202203- Never commit `terraform.tfstate` or `*.tfvars` containing secrets — add both to `.gitignore`.204- Run `terraform plan` before `apply` and review the diff — automated `apply` without review risks unintended resource deletion.205- Use separate Terraform workspaces or directories for dev/staging/production — never use the same state file.206- Enable MFA delete on the S3 bucket storing Terraform state to prevent accidental or malicious deletion.207208## Common Mistakes209210- **`0.0.0.0/0` on port 22 or 3389** — SSH/RDP open to the internet is the #1 cloud misconfiguration; use Systems Manager Session Manager instead.211- **IAM roles with `sts:AssumeRole` for `*`** — allows any AWS principal to assume the role; always specify the trusted principal ARN.212- **Ignoring `checkov` violations with `#checkov:skip`** — each skip should have a documented justification and tracked exception.213- **Not encrypting RDS at rest** — `storage_encrypted = true` should be the default for any database with sensitive data.