Module 3 · Infrastructure-as-Code Security

Manish Garg
Manish Garg Associate of (ISC)² · RingSafe
Apr 22, 2026
5 min read
Read as

Last updated: April 29, 2026

100% Free

No signup. No paywall. No catch. One of our 10 most-requested practitioner modules — published in full so anyone can learn for free. We earn through consulting, not by gating knowledge.

See all 10 free modules →

Checkov, Trivy, kube-score. Terraform issue categories, Kubernetes hardening, Dockerfile patterns, Kyverno/OPA policies.

Infrastructure-as-code (IaC) is the definition of your cloud, Kubernetes, or container environment expressed as files. When those files are insecure — public S3 buckets, privileged containers, missing network policies — the infrastructure that gets deployed is insecure too. IaC security is the discipline of catching these misconfigurations before they become production incidents.

The case for scanning IaC

Industry data consistently shows that most cloud breaches are caused by misconfigurations, not zero-days. Public S3 buckets, security groups open to 0.0.0.0/0, Kubernetes pods running as root, unencrypted RDS instances — these are the volume issues. Each one is a single-line fix in the IaC, if caught before merge.

The tool landscape

  • Checkov (Bridgecrew/Prisma) — multi-framework: Terraform, CloudFormation, Kubernetes, Dockerfile, ARM, Serverless, Helm. Good out-of-box rules, active maintenance
  • tfsec — Terraform-focused, fast, clear output. Acquired by Aqua; maintained alongside Trivy
  • Trivy — now a Swiss-army knife: container images, filesystems, IaC, secrets. One binary
  • kube-score / kubesec — Kubernetes manifest static analysis. Complements admission controllers
  • KICS — open-source IaC scanner from Checkmarx, broad framework support
  • Semgrep — can write custom IaC rules in the same platform you use for code SAST

Recommendation for most teams: Checkov for broad coverage + Trivy for container images + custom Semgrep rules for your specific patterns.

Terraform — what to scan for

Categories of Terraform issues:

  • Public exposure: S3 buckets with public ACL, security groups 0.0.0.0/0 on sensitive ports, RDS publicly_accessible
  • Missing encryption: S3/EBS/RDS unencrypted, secrets in plaintext (Terraform state has them too)
  • Logging/monitoring gaps: no CloudTrail, no VPC flow logs, no RDS logs
  • IAM: wildcard permissions, overly broad trust policies, no MFA on privileged roles
  • Backup/retention: no versioning, missing backup policies, short log retention
  • Network: missing VPC endpoints (forcing traffic over internet), public subnets holding data services

Sample Checkov CI job

# .github/workflows/iac-scan.yml
name: IaC Scan
on:
  pull_request:
    paths: ['terraform/**', 'k8s/**', '**/Dockerfile']

jobs:
  checkov:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: bridgecrewio/checkov-action@master
        with:
          directory: .
          framework: terraform,kubernetes,dockerfile
          output_format: sarif
          output_file_path: checkov.sarif
          soft_fail: false       # fail the build on findings
          skip_check: CKV_AWS_79 # specific known-accepted risks
      - uses: github/codeql-action/upload-sarif@v3
        if: always()
        with:
          sarif_file: checkov.sarif

Kubernetes — the deeper checklist

Kubernetes manifests have a specific set of security-sensitive fields:

  • securityContext.runAsNonRoot — should be true
  • securityContext.readOnlyRootFilesystem — should be true
  • securityContext.allowPrivilegeEscalation — should be false
  • securityContext.capabilities.drop: [“ALL”] — drop then selectively add
  • Resource limits and requests — both CPU and memory, always
  • No hostNetwork: true, hostPID: true, hostIPC: true except where absolutely required
  • ServiceAccount explicitly set (not default); RBAC scoped narrowly
  • NetworkPolicy present (without one, pods can talk to every other pod)
  • Pod Security Standards: at least baseline, ideally restricted, on every namespace
  • Ingress TLS configured; HTTP-only ingresses rejected

Sample Kubernetes manifest — secure defaults

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: prod
spec:
  template:
    spec:
      serviceAccountName: api-sa
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        fsGroup: 10001
        seccompProfile: {type: RuntimeDefault}
      containers:
      - name: api
        image: registry.example.com/api:v1.2.3@sha256:abc...
        securityContext:
          readOnlyRootFilesystem: true
          allowPrivilegeEscalation: false
          capabilities: {drop: [ALL]}
        resources:
          requests: {cpu: 100m, memory: 128Mi}
          limits:   {cpu: 500m, memory: 512Mi}
        ports: [{containerPort: 8080}]

Dockerfile — the scanning layer

Dockerfile-level patterns to catch:

  • USER root (or no USER — defaults to root)
  • Curling to a URL and piping to bash without verification
  • COPY of secret files into the image
  • Base images without explicit version pins (FROM node:latest)
  • Installing packages without cleaning apt cache
  • Exposing ports unnecessarily
  • ADD of remote tarballs without verification

Hadolint is the Dockerfile-specific linter; Checkov catches many of the same plus security-specific rules.

Policy-as-code for runtime enforcement

IaC scanning happens at build. Policy-as-code enforces at deploy. Two are complementary:

  • OPA Gatekeeper — admission controller for Kubernetes. Deny resources that violate policies written in Rego
  • Kyverno — simpler than OPA, YAML-based policy definitions. Kubernetes-native
  • AWS SCPs / Azure Policy / GCP Org Policies — cloud-platform-level guardrails. Deny account-wide

Example Kyverno policy

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-non-root
spec:
  validationFailureAction: Enforce
  rules:
  - name: check-non-root
    match:
      resources:
        kinds: [Pod]
    validate:
      message: "Pods must not run as root"
      pattern:
        spec:
          securityContext:
            runAsNonRoot: true

The CI/CD integration pattern

  1. Pre-commit: quick linters (tflint, hadolint) for fast developer feedback
  2. PR: Checkov/tfsec/Trivy. Block on Critical; warn on High/Medium
  3. Merge: full scan of the whole repo (not just changed files) — catches issues introduced by dependency shifts
  4. Deploy: admission controllers enforce policies in the cluster. If scan missed something, deploy is rejected
  5. Runtime: CNAPP (Wiz/Orca/Prisma) monitors for drift — config changed post-deploy

Managing the baseline

Introducing IaC scanning to a brownfield environment generates hundreds of findings immediately. Tactics:

  • Baseline: mark existing findings as accepted; gate only new or modified resources
  • Severity-weighted burndown: prioritize by severity × exposure (public-facing > internal)
  • Module-level fixes: fix in Terraform modules so one change cascades
  • Lease the gate: teams agree to fix within X weeks; afterwards the gate upgrades to hard-fail

Auditing state files

Terraform state files contain secrets (DB passwords, access keys) in plaintext. Make sure:

  • State is stored in encrypted backend (S3 + KMS, GCS + CMEK, Terraform Cloud)
  • Access to state is narrowly scoped
  • State is never committed to Git (.gitignore includes *.tfstate*)
  • Secrets referenced in Terraform come from a vault (AWS Secrets Manager, HashiCorp Vault) — not hardcoded

Where it lands

With IaC scanning wired in, Kubernetes hardened, and policy-as-code enforcing at deploy, you have caught the bulk of classic cloud misconfigurations. Module 4 covers a deeper vulnerability class — the CI/CD pipeline itself. When attackers target software supply chain, the pipeline is the prize.

🧠
Check your understanding

Module Quiz · 15 questions

Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.

Want this for your team?

Custom team training + practitioner advisory

Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.

Book team training call Replies in 4 working hrs · India-only · Senior consultants