Infrastructure As Code Security

Production-grade guide to infrastructure as code security covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Infrastructure as Code security is the practice of identifying misconfigurations, hardcoded credentials, and policy violations in infrastructure definitions before they are applied to production environments. It matters whenever infrastructure is provisioned through declarative code—Terraform, CloudFormation, ARM templates, Kubernetes manifests—because a single overlooked permission or exposed secret can grant unintended access to entire cloud accounts or clusters. This page covers the concrete practices and tools that make IaC scanning actionable in a devsecops workflow.

Finding secrets before they're provisioned

The most immediate risk in IaC is a database password, cloud API key, or TLS private key checked into version control. Scanning source text for high-entropy strings is the first line of defense.

git-secrets --scan --regexp='[A-Z]{20,}' searches the working directory for strings matching common secret patterns. On a match, git-secrets exits with status 1 and prints the file path, line number, and the matching line. If the --pre-commit flag is used, the scan runs as a git hook and blocks the commit if any match is found.

A complementary approach uses trufflehog:

trufflehog filesystem --path .

trufflehog decodes base64, hex, and ASCII-85 encoded strings, then evaluates entropy thresholds. Typical output:

trufflehog: secret found: AKIAIOSFODNN7EXAMPLE in main.tf:5

Both tools are filesystem-bound; they do not require a cloud account or API credentials to run. They can be invoked from a Makefile target, a pre-commit configuration, or a CI job step. The sharp edge here is that high-entropy strings that look like secrets may be legitimate long passwords or generated values. Teams typically maintain a allowlist file (--truffle-config) to suppress known false positives, but an allowlist that is too permissive defeats the scan's purpose.

Scanning for infrastructure misconfigurations before apply

Once secrets are ruled out, the next question is whether the declared resources violate security baselines. A cloud bucket marked acl = "public_read" or a security group with from_port = 0 and to_port = 0 and protocol = "-1" creates an open endpoint that may not be intended.

tfsec . scans a Terraform directory and reports rule violations with file, line, and a concise description. Example output:

tfsec main.tf
No.  Rule ID  Message
---  -------  -------
 1   7026     S3 bucket main-bucket has public access enabled
 2   IAM_1    IAM role has more permissions than required

tfsec evaluates rules defined in the Open Source Security Scanning project; the rule set includes checks for CIS Foundation, PCI-DSS, and custom Rego policies. The tool exits non-zero when any rule matches, which is useful for pipeline gating.

For heterogeneous environments, checkov supports multiple IaC frameworks:

checkov -d . --framework terraform --check CKV_AWS_1

The --check flag accepts a specific check ID; CKV_AWS_1 corresponds to “S3 bucket should not allow public reads.” Without a check ID, checkov runs its full rule set and outputs a JSON report suitable for archival or dashboard ingestion.

trivy fs --terraforms . extends scanning beyond AWS. It detects misconfigurations in Terraform, Helm charts, and Kubernetes manifests, and it cross-references detected software versions against the CVE database. A typical finding:

trivy fs --terraforms .
Found: aws_instance with ami that has known vulnerability CVE-2023-XXXXX

The sharp edge with these scanners is rule coverage gap. A scanner may flag an S3 bucket as public but miss that the bucket policy contains a Condition block that effectively restricts access. Conversely, a scanner may report a violation that is mitigated by a VPC endpoint or IAM condition that the rule does not evaluate. Scanners are best treated as a first pass, not a final authority.

Embedding checks in the development workflow

Security checks lose value if they run only in CI. Local feedback loops are essential for developer velocity.

A pre-commit configuration file can bind multiple checks to the pre-commit hook:

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.70.0
    hooks:
      - id: tfsec
      - id: trivy
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.12.1
    hooks:
      - id: gitleaks

When a developer runs pre-commit run --all-files, each hooked check executes on the staged files. If tfsec finds a public S3 bucket, the hook fails and git refuses the commit until the code is corrected.

In CI pipelines, the pattern is similar but orchestrated across stages. A GitHub Actions workflow might look like:

name: IaC Security Scan
on: [push, pull_request]

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run tfsec
        run: tfsec .
      - name: Run checkov
        run: checkov -d . --framework terraform

If either step exits with a non-zero status, the workflow fails and the pull request cannot be merged. This “scan-before-apply” pattern ensures that no merge reaches production without passing the defined policy set.

The sharp edge in pipeline integration is noise. Scanners frequently produce false positives, especially for organization-specific tagging conventions or non-standard resource names. Teams that toggle scan severity or suppress specific check IDs via comments (# tfsec: skip CKV_AWS_1) reduce friction, but suppression must be reviewed and justified like any other technical debt.

Enforcing standards across teams with policy-as-code

Beyond one-off scans, organizations often want guardrails that apply across all repositories and all deployments. Policy-as-code evaluates resource specifications against declared rules and can enforce outcomes at runtime.

Open Policy Agent (OPA) with the opa eval command evaluates a Rego policy against a data input:

opa eval --input main.tf data.terraform.schema.resources

A sample Rego policy that disallows public S3 buckets:

package terraform.example

deny[reason] {
    input.resource_type == "aws_s3_bucket"
    input.resource.acl == "public_read"
    reason := sprintf("S3 bucket %s has public read ACL", [input.resource.name])
}

The policy is stored in version control alongside the IaC it governs. Changes to the policy require the same review process as infrastructure changes, which keeps guardrails auditable and transparent.

For Kubernetes workloads, Gatekeeper extends OPA into the admission controller. A constraint template might limit the number of hostPort usages in a namespace:

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        deny[msg] {
            input.review.object.spec.containers[_].name == "main"
            not input.review.object.metadata.labels["environment"]
            msg := "Container main must have an environment label"
        }

Gatekeeper enforces the constraint at pod creation time. If a developer kubectl applys a manifest without the required label, the API server rejects the request with a denial message.

The sharp edge with policy-as-code is policy sprawl. As the number of Rego rules grows, it becomes difficult to track which team owns which policy, and which rules are active versus deprecated. Organizations that maintain a dedicated policy repository with clear ownership and versioning avoid the “silent drift” where a team’s infrastructure gradually violates a policy that no one remembers writing.

Protecting state and remote artifacts

IaC tools often store state in remote backends—S3 with DynamoDB locking, Azure Storage with leasing, or Consul. State files contain the full mapping of declared resources to real-world IDs, secrets, and outputs. Unprotected state is a high-value target.

Backend configuration is typically written in the IaC language itself. For Terraform:

terraform {
  backend "s3" {
    bucket         = "my-tf-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "tf-locks"
    tabledynamodb_endpoint = ""
  }
}

The encrypt = true flag ensures the state file is stored server-side encrypted. DynamoDB (or equivalent) provides exclusive lock coordination so that concurrent terraform apply operations do not corrupt state. The sharp edge here is that encrypt only protects at rest; in transit, the TLS configuration of the backend bucket must be validated separately. A misconfigured S3 bucket policy that allows public read on the state bucket exposes every past and future resource mapping.

For cloud-native pipelines, state may be stored in a managed artifact registry. The same principles apply: encryption at rest, IAM least-privilege access to the storage location, and audit logging of download events.

What silently fails and what you learn only after breakage

IaC security scanners are not omniscient. Several failure modes catch teams off guard:

Infrastructure as Code security is not a one-time scan or a single tool. It is a set of layered practices: scanning source text for secrets, evaluating resource configurations against baselines, embedding checks in local and CI workflows, enforcing guardrails with policy-as-code, and protecting the state that ties code to live infrastructure. The concrete commands and patterns above map to real tooling that ships today, but the underlying mechanics—entropy evaluation, policy evaluation, state locking, and admission control—are portable across platforms. Teams that treat IaC security as an ongoing discipline, not a compliance checkbox, find that the cost of a missed misconfiguration far exceeds the operational overhead of a well-tuned scan pipeline.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.