Infrastructure as Code Security

๐Ÿ”ฅ Vibe Prompt

"Scan Terraform code for security issues before apply. Enforce policy as code."

IaC Scanning with Checkov

brew install checkov
checkov -d terraform/
checkov -f cloudformation.yaml
checkov -d k8s/
checkov -d terraform/ --compact --quiet

Checkov Output

Passed checks: 45
Failed checks: 3

CKV_AWS_21: S3 bucket ACL should not be public read (s3.tf:12)
CKV_AWS_23: Ensure S3 bucket has block public access (s3.tf:8)
CKV_AWS_52: Ensure EC2 has detailed monitoring (ec2.tf:15)

Terraform Security Checks

# Good: encrypted, versioned S3
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

# Bad: public RDS
resource "aws_db_instance" "db" {
  publicly_accessible = true  # Never do this!
  skip_final_snapshot = true  # Never do this!
}

Policy as Code with OPA

package terraform

deny[msg] {
  resource := input.resource.aws_s3_bucket[_]
  resource.config.acl == "public-read"
  msg := sprintf("S3 bucket %v has public-read ACL", [resource.config.bucket])
}

deny[msg] {
  resource := input.resource.aws_security_group[_]
  ingress := resource.config.ingress[_]
  ingress.cidr_blocks[_] == "0.0.0.0/0"
  ingress.from_port == 22
  msg := sprintf("SG %v allows SSH from 0.0.0.0/0", [resource.config.name])
}

IaC Security in CI/CD

jobs:
  iac-scan:
    steps:
      - uses: actions/checkout@v4
      - uses: bridgecrewio/checkov-action@v12
        with:
          directory: terraform/
          framework: terraform
          soft_fail: false

Best Practices

  • Scan IaC before every apply
  • Use policy as code (OPA, Checkov)
  • Store Terraform state in encrypted S3
  • Use remote state with locking
  • Never hardcode secrets in IaC
  • Pin provider versions
  • Use modules for consistency

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

  • Official documentation
  • Open source projects on GitHub
  • Community forums and discussions
  • Related courses and tutorials

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!