Infrastructure-as-code (IaC) security in CI/CD means giving every Terraform, CloudFormation and Kubernetes change the same treatment as application code. You scan it for misconfigurations and secrets on the pull request, check the resolved plan against policy-as-code rules, have a person review risky changes, and look for drift once it's live. Fast checks run first. Blocking gates fail only on high-severity findings.
What can go wrong when infrastructure code skips security checks?#
A single unchecked line can open a storage bucket to the public, hand out admin rights or leak a credential in every environment the pipeline deploys to.
IaC multiplies mistakes. A module gets reused across accounts and regions, so one bad default spreads everywhere it's used. The pipeline that applies the change also holds credentials that can modify production, which makes the pipeline a target in its own right. The OWASP Top 10 CI/CD Security Risks includes insufficient credential hygiene and insecure system configuration. It also cites the Codecov breach, in which secrets stored in environment variables were stolen from thousands of build pipelines.
Infrastructure mistakes are also harder to undo than application bugs. You can redeploy a broken service. You can't redeploy a deleted database or a public bucket that has already been crawled.
Which IaC risks matter most: misconfigurations, secrets, permissions or drift?#
Permissions and secrets do the most damage, misconfigurations are the most common, and drift is what stops you from seeing the other three.
The numbers explain why identity comes first. In Datadog's 2025 State of Cloud Security research, 59% of AWS IAM users, 55% of Google Cloud service accounts and 40% of Microsoft Entra ID applications had an access key older than one year. Datadog also found that 12.2% of third-party integration roles had enough privilege to read all data in an AWS account or take it over.
Secrets are the second problem. GitGuardian counted 23.8 million new secrets leaked on public GitHub in 2024, up 25% on the year before. It also found that 70% of secrets leaked in 2022 were still valid. Variable files, state files and Helm values are common places for them to end up.
| Risk | Typical example | Where to catch it | Gate type |
|---|---|---|---|
| Permissions | "Action": "*" on a role, cluster-admin binding |
Plan + policy check, human review | Block |
| Secrets | Key in terraform.tfvars or a manifest |
Pre-commit and PR secret scan | Block |
| Misconfiguration | Public bucket, 0.0.0.0/0 ingress, privileged pod |
Static scan + policy on plan | Block high, warn rest |
| Drift | Console edit to a security group | Scheduled drift check | Alert + ticket |
Where in the CI/CD pipeline should IaC scanning run?#
Scanning should run in four places, because each one catches something the earlier ones can't.
- Editor and pre-commit. Secret scanning and formatting, so credentials never reach the remote repository.
- Pull request, on source. Static misconfiguration scanning of
.tf, CloudFormation templates and YAML manifests. It's fast and gives feedback line by line. - Pull request, on the plan. Run
terraform plan(or a CloudFormation change set) with read-only credentials, then check the JSON output against policy. This step matters because module inputs, variables and computed values only resolve at plan time. - After apply, on a schedule. Drift detection against the live environment.
Keep apply credentials out of pull request jobs. Only the protected main branch should be able to change production. This addresses the flow-control and access risks in the OWASP list above.
Our DevOps engineering practice builds pipelines around this split, so each stage has one job and only the final stage can touch production.
How does policy-as-code turn security rules into enforceable gates?#
Policy-as-code writes your rules as versioned code that runs against every plan. "No public buckets" stops being a line on a wiki page and becomes a check that fails.
A common setup uses Open Policy Agent rules in Rego. A tool like conftest evaluates them against the Terraform plan JSON. For Kubernetes, the same rules can run a second time at the cluster's admission layer, which catches anything applied outside the pipeline.
Treat each rule like production code:
- An ID and a severity, so findings can be tracked and reports grouped.
- Unit tests with a passing and a failing fixture, so a policy change can't quietly allow what it used to deny.
- An owner who answers questions and approves exceptions.
- An exception path with a reason, an approver and an expiry date, written down in the repository.
Good first rules: storage encrypted and not public, no wildcard IAM actions, no ingress from 0.0.0.0/0 on admin ports, no privileged containers, required tags for owner and cost centre, and deletion protection on stateful resources.
How do you review AI-written Terraform and Kubernetes manifests safely?#
Put AI-written infrastructure through the same gates as human-written code, then review the plan diff rather than just the source. Look hardest at IAM, networking and anything that deletes.
AI assistants draft IaC quickly, but they learn from public examples, and many of those were written for a demo rather than for production. Reviewers should check for:
- Wildcard actions or resources in IAM policies, and roles broader than the task needs
- Open security groups, public endpoints and disabled encryption
- Privileged pods,
hostPathmounts, missing resource limits and containers running as root - Unpinned provider and module versions, and module sources nobody on the team recognises
- Arguments or attributes that don't exist or are deprecated (a plan or validate step catches these quickly)
prevent_destroyor deletion protection removed, and any "destroy and recreate" line in the plan
Every change we ship passes three gates, whether a person or an AI wrote it: tests prove it works, security checks prove it's safe, and a senior engineer's review proves it's right. Our guide to verifying AI-generated code before production covers those gates in detail. For IaC, the reviewer signs off on the plan, because the plan shows what will actually change.
How do you catch drift between your IaC and what's actually running?#
Run a scheduled refresh-only plan against each environment, alert on any difference, and then decide whether to write the change into code or revert it.
Drift is any difference between your configuration and the resources actually running. It usually comes from manual console changes or other tools. With Terraform, a scheduled terraform plan -refresh-only with -detailed-exitcode lets the job tell "no drift" apart from "drift found" and send an alert. Run it per workspace, daily or more often for production, and record each run, including clean ones.
The lasting fix is to make drift rare: restrict console write access in production, keep a documented break-glass role, and require every emergency change to come back as a pull request.
How do you roll out IaC gates without blocking every team's releases?#
Start every rule in warn mode, clear the existing backlog, and then block only high-severity findings on new changes.
- Baseline. Scan every repository and environment once. Expect a long list.
- Block new problems, not old ones. Make gates diff-aware, so a pull request fails only on findings it introduces. Track the existing backlog as tickets with owners.
- Tier by severity. Critical and high findings (secrets, public data, admin rights) block. Medium and low findings comment on the pull request.
- Keep it fast. Run static scans in parallel with the plan. Slow gates get bypassed.
- Promote rules gradually. Move a rule to blocking only once its false positive rate is low and the backlog it covers is fixed.
Ownership matters as much as tooling. The platform team owns the policies and the pipeline. Product teams own fixing their own findings. Our Security & DevSecOps consulting follows the same order: find the gaps, rank them by risk, then build the checks into your pipeline.
What release evidence should each infrastructure change leave behind?#
Each change should leave a record that links one change ID to the commit, the plan, the scan and policy results, the approver and the apply output.
At minimum, keep:
- Commit SHA, pull request link and author (including whether an AI assistant drafted it)
- The saved plan file and a readable diff
- Scanner and policy results, including any exceptions with approver and expiry
- Reviewer approval and timestamp
- Apply logs and the identity that ran the apply
- The next drift check result showing the environment matches the code
This record answers an auditor's questions and speeds up incident reviews. It also fits the direction of NIST SP 800-204D, NIST's guidance on building software supply chain security into DevSecOps CI/CD pipelines. On cloud migrations, the same evidence supports our rule of a rollback plan for every phased step.
Conclusion#
Infrastructure code now moves through the same pipeline as application code, and a growing share of it is drafted by AI. The way to keep it safe without slowing releases is layered:
- secret and static scans on every pull request
- policy-as-code checks on the resolved plan
- human review of the plan diff for permissions, networking and deletions
- scheduled drift detection
- a release record for every apply
Roll gates out in warn mode first, and block only what matters.
If you'd like help setting this up, we can start with a paid pilot: one pod, one outcome, with success criteria agreed up front. Talk to an engineering lead →
Frequently asked questions
Which IaC scanner should we start with?
Start with whichever scanner covers your main formats (Terraform, CloudFormation, Kubernetes YAML) and runs well in your CI system. Pair it with a dedicated secret scanner. Which tool you pick matters less than running it on every pull request and blocking only high-severity findings at first.
Should policy checks run on Terraform source or on the plan?
Both. Source scans are fast and point to exact lines. Plan checks see resolved variables, module outputs and the real list of resources that will be created, changed or destroyed. Security-critical rules, such as IAM and public exposure, belong on the plan.
How often should drift detection run?
Daily is a sensible starting point for most environments. Run it more often for production accounts that hold sensitive data. Record every run, including clean ones, so you can show the environment matched the code at a given time.
Do AI-written infrastructure changes need different gates?
They need the same gates, applied consistently. Reviewers should pay extra attention to wildcard permissions, open network rules, unpinned versions and removed deletion protection, because those patterns are common in public examples. Recording whether a change was AI-drafted also helps you see where review effort is going.
How do we handle exceptions without weakening the gates?
Store each exception in the repository with a rule ID, a reason, an approver and an expiry date. When it expires, the gate blocks again unless someone renews it. This keeps exceptions visible and time-limited.
- Infrastructure as Code
- DevSecOps
- CI/CD
- Terraform
- Kubernetes
- Policy as Code
Newsletter
Get new articles by email
A short monthly round-up of what we've written on engineering pods, quality and AI. No spam.
