12 Infrastructure as Code Mistakes That Cause Drift, Outages and Security Gaps

    Avoid the infrastructure as code mistakes that cause drift, outages and leaked secrets. 12 common IaC errors, with practical Terraform fixes for each.

    Omer Hassan

    Founder & CEO

    7 min read
    Share
    On this page

    Infrastructure as code promises something every ops team wants: environments you can rebuild from a Git repo, changes you can review like any pull request, and no more "it works on staging" mysteries. Then reality shows up. A plan wants to destroy the production database. Someone changed a security group in the console last Tuesday. A state file with plain-text passwords sits in a shared drive.

    Most IaC problems aren't caused by the tool. They come from a handful of habits that seem harmless early on and get expensive later. A large study of open-source IaC scripts, "Gang of Eight" (presented at ICSE 2020), found that the most frequent defect category was simply wrong configuration data, like the wrong value in the wrong place. In other words, ordinary mistakes, repeated at scale.

    Below are the 12 infrastructure as code mistakes we see most often, why each one hurts, and how to fix it. Examples use Terraform, but the lessons apply to OpenTofu, Pulumi, CloudFormation and Bicep too.

    1. Mixing IaC With Manual Console Changes

    Why it hurts: The moment someone "just quickly" edits a resource in the cloud console, your code stops describing reality. This gap, called configuration drift, means the next apply may silently undo the fix, or fail in confusing ways.

    How to fix it: Make code the only path to change. Limit console write access to a small break-glass role, and if an emergency change happens, back-port it into code the same day. Run a scheduled terraform plan to flag drift automatically (see mistake 9).

    2. Keeping State Files on Laptops

    Why it hurts: Terraform's state file is its memory of what exists. Store it locally and two people can apply at once, overwrite each other's changes or lose state entirely when a laptop dies.

    How to fix it: Use a remote backend with locking and encryption, such as S3, Azure Blob Storage, Google Cloud Storage or Terraform Cloud.

    hcl
    terraform {
      backend "s3" {
        bucket         = "acme-terraform-state"
        key            = "prod/network/terraform.tfstate"
        region         = "us-east-1"
        encrypt        = true
        dynamodb_table = "terraform-locks"
      }
    }

    Newer Terraform versions can also lock directly in S3 using use_lockfile = true, so check which option your version supports. Turn on bucket versioning so you can recover an older state if something goes wrong.

    3. Putting Secrets in Code or State

    Why it hurts: Hard-coded passwords and API keys end up in Git history forever. Even when you avoid that, many resources write sensitive values into the state file in plain text.

    How to fix it:

    • Pull secrets at runtime from a secrets manager such as AWS Secrets Manager, Azure Key Vault, Google Secret Manager or HashiCorp Vault.
    • Mark variables and outputs as sensitive = true so they don't print in logs.
    • Treat the state file itself as a secret: encrypt it, restrict who can read it, and never commit it.
    • Add a secret scanner to your pipeline and rotate anything that was ever exposed.

    4. One Giant State File for Everything

    Why it hurts: When networking, databases, Kubernetes and DNS share one state, every plan is slow, every change is risky and one typo can touch everything. This is a large blast radius.

    How to fix it: Split state by environment and by layer, for example prod/network, prod/data and prod/app. Layers that change rarely (like VPCs) live apart from layers that change daily (like app services). Share values between them with outputs and data sources, not copy-paste.

    5. Not Pinning Provider and Module Versions

    Why it hurts: Without version constraints, a routine init can pull a new provider release with breaking changes. The same code then behaves differently on Monday than it did on Friday.

    How to fix it: Pin the Terraform version, providers and modules, and commit the .terraform.lock.hcl file.

    hcl
    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }

    Upgrade on purpose: bump a version in a branch, review the plan, then merge.

    6. Copy-Pasting Code for Each Environment

    Why it hurts: Separate, hand-copied folders for dev, staging and prod slowly drift apart. A fix lands in one and is forgotten in the others, so staging stops being a reliable preview of production.

    How to fix it: Put shared infrastructure in reusable modules and pass environment differences in as variables (instance sizes, counts, domain names). Each environment folder should be short and mostly made of module calls.

    7. Applying Changes From Local Machines

    Why it hurts: When engineers run apply from their own laptops, there's no consistent review, no record of who changed what and no guarantee they used the latest code.

    How to fix it: Run IaC through a CI/CD pipeline. On every pull request, generate a plan and post it for review. Apply only after approval, from the main branch, using pipeline credentials rather than personal ones. Our DevOps and cloud team sets up this kind of plan-review-apply workflow for clients regularly.

    8. Skipping Tests and Policy Checks

    Why it hurts: Code that provisions infrastructure can break things just as easily as application code, often more expensively. Without checks, open storage buckets and unencrypted databases slip through review.

    How to fix it: Add layers of automated checks, starting with the cheapest:

    1. terraform fmt and terraform validate on every commit.
    2. A linter such as TFLint to catch provider-specific errors.
    3. A security scanner such as Checkov or Trivy to flag risky settings.
    4. Policy as code, using tools like Open Policy Agent or Sentinel, to enforce rules such as "all storage must be encrypted" and "no public databases."
    5. For shared modules, integration tests (for example with Terratest or Terraform's built-in test command) that spin up and tear down real resources.

    9. Ignoring Drift Until Something Breaks

    Why it hurts: Drift builds quietly. You only discover it during an urgent change, when the plan suddenly shows dozens of unexpected differences.

    How to fix it: Schedule a nightly or weekly plan for each environment and alert the team when it isn't clean. Decide each time: bring the change into code, or let the next apply reverse it. Either way, the gap gets closed while it's small.

    10. Hard-Coding Values Everywhere

    Why it hurts: Account IDs, AMI IDs, regions and CIDR ranges typed directly into resources make code fragile and hard to reuse. Changing a region becomes a search-and-replace exercise.

    How to fix it: Use variables with clear descriptions and sensible defaults, locals for derived values, and data sources to look up things like the latest approved image or existing VPC IDs. Add validation rules so bad inputs fail early.

    11. No Guardrails on Critical Resources

    Why it hurts: A renamed resource or misread plan can mean Terraform destroys and recreates your production database. Without protection, nothing stops it.

    How to fix it: Combine Terraform's lifecycle rules with the cloud provider's own protection settings.

    hcl
    resource "aws_db_instance" "main" {
      # ...other settings
      deletion_protection = true
    
      lifecycle {
        prevent_destroy = true
      }
    }

    Use moved blocks when renaming resources so Terraform updates state instead of replacing infrastructure. And always read the plan summary: any "destroy" in production deserves a second pair of eyes.

    12. Over-Engineering Before You Need To

    Why it hurts: Some teams build a deep tree of nested modules, custom wrappers and clever abstractions on day one. The result is code only its author understands, which defeats the point of IaC.

    How to fix it: Start simple and readable. Extract a module when you've written the same thing two or three times, not before. Keep modules small, document their inputs and outputs, and favor clarity over cleverness. Good IaC reads like a plain description of your infrastructure.

    Quick Checklist: Is Your IaC in Good Shape?

    • State is remote, locked, encrypted and versioned
    • No secrets in code, logs or unprotected state
    • State is split by environment and layer
    • Terraform, providers and modules are pinned
    • Environments share modules instead of copied code
    • All changes go through pull requests and a pipeline
    • Lint, security and policy checks run automatically
    • Drift is detected on a schedule
    • Critical resources have deletion protection
    • Modules are small, documented and easy to read

    Frequently Asked Questions

    What is the most common infrastructure as code mistake?

    In day-to-day work, it's mixing manual console changes with code, which causes drift. In research on open-source IaC scripts, the most frequent defect type was incorrect configuration values.

    Is Terraform state safe to store in Git?

    No. State can contain secrets and changes on every apply, which leads to conflicts. Use an encrypted remote backend with locking instead.

    How do we fix drift that already exists?

    Run a plan to list the differences, then decide resource by resource whether to update the code to match reality or apply the code to reset the resource. For resources created by hand, use terraform import or import blocks to bring them under management.

    Should small teams bother with policy as code?

    Start with free scanners like Checkov or Trivy in your pipeline. Add custom policies once you have rules you find yourself repeating in every review.

    Need a Second Pair of Eyes on Your Infrastructure?

    Fixing these mistakes is far cheaper than recovering from them. If you'd like experienced engineers to review your current setup, untangle drift or design a clean module structure, our DevOps & cloud engineering services team can help. We also offer hosting and ongoing support so your infrastructure stays healthy after launch. See our case studies, check software pricing, or book a free consultation.

    Found this useful? Share it with your team.

    Written by

    Omer Hassan

    Founder & CEO, TechKnoc

    Omer Hassan is the Founder & CEO of TechKnoc, started in 2022 to make production-grade AI and custom software accessible to growing businesses. Omer writes practical guides on topics like app development cost, CI/CD for manual deploys, AWS vs Azure vs Google Cloud and infrastructure as code, drawing on 40+ delivered projects and the work behind TechKnoc's custom software and DevOps and cloud services.

    Keep reading

    All articles