Dev.to AI 🤖 Ai 👁 0 📖 15 min read

What Is Infrastructure Drift? Causes, Risks and How to Fix It

TL;DR Infrastructure drift is the gap between what your last applied IaC configuration declares and what runs in your cloud account. Console edits, incident hotfixes and provider updates cause it, and it can end in a f

What Is Infrastructure Drift? Causes, Risks and How to Fix It

TL;DR

Infrastructure drift is the gap between what your last applied IaC configuration declares and what runs in your cloud account. Console edits, incident hotfixes and provider updates cause it, and it can end in a failed deployment, an exposed port or an apply that destroys a resource nobody meant to touch. Terraform and OpenTofu surface drift during every plan, HCP Terraform and CloudFormation add scheduled checks, and every finding ends in one of three decisions. This guide walks through detection, the three fixes and the controls that keep drift from piling up.

Infrastructure as Code promises that a repository defines the infrastructure a team runs. Engineers review changes in pull requests, a pipeline applies them, and the code stays the record of what exists. That promise holds only while every change goes through the pipeline. Cloud consoles, command-line tools, other automation and the cloud providers themselves can all change a resource without touching the repository.

Suppose we have a payments team at a mid-size fintech that manages an AWS security group with Terraform. During an incident at 2 a.m., an engineer opens port 8080 to the internet in the console. The incident closes, the port stays open, and nobody notices for weeks. By the end of this guide, you will know what causes infrastructure drift, how to detect it with four common tools, and how to choose between the three ways to fix it.

What Infrastructure Drift Looks Like After One Console Edit

Infrastructure drift is any difference between the infrastructure that the last applied code declares and the infrastructure that exists in the cloud account. HashiCorp's Well-Architected guidance attributes drift to manual changes, cloud provider updates and unauthorized modifications. The same page lists deployment failures, security vulnerabilities and operational inconsistencies as the consequences.

Three things are in play whenever drift comes up. The configuration is the code in the repository. The state is the record the IaC tool keeps of what it created. The real infrastructure is what exists in the cloud account right now. A healthy setup keeps all three aligned, and drift breaks that alignment.

The breaks come in two kinds. HCP Terraform's documentation separates them. Configuration drift happens when an external change invalidates what the code declares, such as a console edit that conflicts with a declared rule. State drift happens when an external change to a remote object does not invalidate the configuration. The distinction affects tool choice, because some tools detect only one kind.

Drift is also different from intentional change. A deliberate update that goes through a pull request and a pipeline is a change. A modification that bypasses the pipeline is drift, even when it was the right call.

In the running example, the fintech team manages the security group for its payments API with Terraform. The engineer adds an ingress rule for port 8080 from 0.0.0.0/0 in the console. That one edit is the drift that the rest of this guide detects, assesses and resolves.

Configuration and state list port 443, while real infrastructure also has port 8080 after a console edit

Common Causes of Infrastructure Drift in Cloud Environments

Infrastructure drift comes from a small set of repeating behaviors, and most of them are reasonable decisions made under pressure.

  • Manual console and CLI edits. Someone needs a change faster than a pull request allows, so they make it directly. The port 8080 edit in the running example belongs here.
  • Incident hotfixes. During an outage the console is the fastest route to recovery. The fix works, the incident closes, and the ticket to codify it slips down the backlog.
  • Cloud provider updates. A provider can change a default, add an attribute or modify a managed resource. The next plan then shows a difference nobody caused.
  • Competing automation. An autoscaler, a security scanner with auto-remediation or a second Terraform workspace with overlapping resources can change attributes that the configuration also controls.
  • Partial or failed applies. When an apply stops halfway, some resources match the new configuration and others do not.

These are rarely lapses in discipline, so reminding engineers to use the pipeline does not stop drift on its own. A routine that finds drift and forces a decision works better.

What Unmanaged Infrastructure Drift Puts at Risk in Production

Unmanaged drift costs more the longer it stays hidden, and four risks recur.

Security exposure. In the running example, the console edit opened port 8080 to the entire internet. The change never passed code review or a pipeline policy check, so no reviewer saw it and no scanner tied to the pipeline evaluated it.

Unintended destroy or recreate. HashiCorp's resource drift tutorial warns that when state and configuration do not match the infrastructure, Terraform attempts to reconcile it, which may unintentionally destroy or recreate resources. The risk is highest when a drifted attribute is one that forces replacement, because a routine apply then replaces the resource.

Compliance gaps. Auditors compare what a control says should exist with what exists. A diverged resource shows that the control did not hold.

Operational inconsistency. Environments built from the same code can diverge, so a bug that reproduces in staging can disappear in production.

Detection that runs routinely keeps all four risks small. Terraform and OpenTofu already provide the first layer.

How to Detect Infrastructure Drift With a Refresh-Only Plan

Terraform detects drift as part of ordinary planning. Before it compares configuration to state, a plan refreshes state from the real infrastructure. When the refresh finds differences, the plan opens by stating that Terraform detected changes made outside of Terraform since the last apply, as the resource drift tutorial shows.

For the running example, the commands below create the drift with the AWS CLI and then check for it with a refresh-only plan.

# Simulate the out-of-band change
aws ec2 authorize-security-group-ingress \
  --group-id "$SG_ID" \
  --protocol tcp --port 8080 --cidr 0.0.0.0/0

# Detect it without proposing any infrastructure change
terraform plan -refresh-only

The -refresh-only mode asks one question: what changed outside Terraform? According to the Terraform plan documentation, it creates a plan whose goal is only to update state and root module output values to match changes made to remote objects. A normal plan can mix drift and intended changes in one output, so a refresh-only plan keeps the two separate.

One option works against detection. Setting -refresh=false disables the synchronization step, and the documentation warns that Terraform then ignores external changes, which could result in an incomplete or incorrect plan. A pipeline that uses it to save API calls trades drift visibility for speed.

OpenTofu behaves the same way. Its plan documentation states that -refresh-only creates a plan whose goal is only to update OpenTofu state and root module output values to match changes made outside OpenTofu. The apply documentation adds that without a saved plan file, tofu apply supports all the planning modes and options of tofu plan.

How Scheduled Drift Detection Works Beyond Manual Plans

A manual plan finds drift only when someone runs it, so teams that want recurring coverage need scheduled detection. HCP Terraform provides it through health assessments, and CloudFormation provides it through an AWS Config rule. Both have documented limits.

HCP Terraform Health Assessments Check for Configuration Drift

HCP Terraform runs drift detection as part of health assessments, which also include continuous validation of the custom conditions in a configuration. The health assessments documentation sets several requirements. Health assessments are available in the Standard and Premium editions. Workspaces must use remote or agent execution mode. Drift detection needs Terraform 0.15.4 or later.

The same page documents the limits. An assessment runs a speculative plan, so it reports differences and does not apply changes. Drift detection finds configuration drift only, and the documentation states that it does not detect state drift. Assessments pause until there is a successfully applied run, which leaves a gap in coverage after a failed apply. Because the plan is speculative, a data source whose value changed since the last run can also fail a check before the infrastructure changed, which produces a false positive. The documentation's cadence example uses a 24-hour schedule.

CloudFormation Drift Detection Works at the Stack Level

AWS CloudFormation checks drift per stack. Its drift detection documentation defines drift as a difference between a stack's actual configuration and its expected template configuration, including when a property or resource has been deleted. Stacks report DRIFTED, IN_SYNC or NOT_CHECKED, and resources report MODIFIED, DELETED, IN_SYNC or NOT_CHECKED.

The limits are explicit. CloudFormation determines drift only for property values that are explicitly set in the template or through template parameters, which excludes default values. It does not run drift detection on the KMSKeyId property of any resource. Nested stacks are not covered when the parent stack is checked, so each nested stack needs its own operation. The page leaves corrective action to the reader.

Periodic checks come from an AWS Config managed rule with the identifier CLOUDFORMATION_STACK_DRIFT_DETECTION_CHECK. According to the AWS Config rule documentation, the rule runs the DetectStackDrift operation on each stack in the account. Its maximum execution time is 15 minutes, so it can time out before it evaluates every stack in a large account.

Detection answers what changed. It does not answer what to do about it, which is the decision the next section structures.

Three Ways to Fix Infrastructure Drift Once Detected

Every drift finding ends in one of three decisions: revert the change, accept it into state, or update the configuration to match it. HashiCorp's resource drift tutorial demonstrates each of these actions on a drifted security group. The Well-Architected guidance frames the same choice as running a new apply to restore the desired state or updating the configuration to match the new state.

Revert the change. Run a normal terraform apply without -refresh-only. Terraform attempts to undo the manual change and return the resource to what the code declares. In the running example, this closes port 8080. Reverting fits when the change was a mistake or an unauthorized modification.

Accept the change into state. Run a refresh-only apply.

terraform apply -refresh-only

At the prompt, Terraform writes the changes to state without modifying real infrastructure. The tutorial warns that there is no undo and that only yes confirms. Accepting only updates state. The configuration still differs from reality, so the next plan proposes reverting the change unless the code is updated too.

Update the configuration to match. Add the change to the code so that configuration, state and reality agree. If Terraform does not manage the resource yet, import it first. The import documentation explains that an import block specifies the unique infrastructure resource ID to import and declares an address for the imported resource in state. A team can write only the import block and run terraform plan with the -generate-config-out flag to generate the resource blocks. The plan command page labels that flag experimental.

import {
  to = aws_vpc_security_group_ingress_rule.payments_api_8080
  id = "sgr-0abc1234567890def"
}

The import ID for this rule resource is the security group rule ID, which starts with sgr-, according to the AWS provider documentation.

The right path depends on the change. Unauthorized or accidental changes get reverted, because the code is the source of truth. A harmless provider default can be accepted into state to avoid a noisy diff. A hotfix that should stay belongs in the configuration, where it becomes reviewable and repeatable.

Decision flow for a drift finding: revert, update the configuration or accept into state

For the fintech team, port 8080 open to the whole internet is a revert. The incident is over, the exposure is the risk, and nothing in the change deserves a place in code. If the team had needed 8080 reachable from one internal CIDR, it would have updated the configuration with that narrower rule instead.

How to Prevent Infrastructure Drift Before It Starts

Prevention works in layers, because no single control stops every cause listed earlier.

  • Restrict console write access in production accounts. If engineers cannot modify resources by hand, a common cause of drift becomes a permission error that sends them back to the pipeline. Keep a documented break-glass role for incidents and require that anything done through it is codified afterward.
  • Enforce policy as code. Guardrails that evaluate every plan catch dangerous changes whether or not the author remembers the rule.
  • Route changes through a GitOps workflow. When every change is a reviewed pull request and the pipeline is the only path to production, the repository stays authoritative by design. HashiCorp's guidance adds a related practice: implement drift detection as part of the CI/CD pipeline to catch configuration issues before they reach production.
  • Schedule detection and alert on it. Detection that nobody sees is as weak as no detection. Tier alerts by severity, so a security finding pages someone while a cosmetic difference waits for review.
  • Codify what already exists. Resources created before IaC adoption can never be in sync with code that does not exist. The brownfield infrastructure guide explains how to bring them under management.

A platform can tie these controls into one loop, and StackGuardian approaches it as follows.

How StackGuardian Closes the Drift Loop for Terraform Teams

StackGuardian addresses four parts of the drift loop: recurring detection, alerting, destructive plans and resources that never had code.

Automated Drift Check on Deployed Terraform Workflows

StackGuardian's Terraform Configuration settings include an Automated Drift Check option. According to the Terraform Configuration documentation, enabling it allows StackGuardian to run drift checks regularly on deployed infrastructure. When drift is detected, users can rerun the workflow to reconcile it or modify the Terraform configuration to import the changes. Those two options correspond to the revert and update-configuration paths above. The setting closes the gap that a manual plan leaves open.

Background checks also stay out of the way of deployments. Since v1.31.8, drift runs have lower priority than user-initiated workflow runs.

Stackguardian

Automated Drift Check in the Terraform Configuration panel of the workflow wizard.

Alerting Through the On Drift Detection Webhook Event

StackGuardian workflows can send a webhook when drift is found. The Terraform and OpenTofu configuration documentation lists On Drift Detection as a trigger type that fires when drift is found between the current and desired state, and it suggests sending drift updates to monitoring dashboards. Webhooks are set up under Resources and Events in the workflow's runtime environment settings. Each webhook takes a name, a URL and an optional secret.

The documentation does not state what payload a drift event carries, so check what one sends before building routing rules on it. Email is the other documented alert path. The notifications documentation lists a Send Email on Drift Detection setting for Terraform and OpenTofu workflows.

Blocking Destructive Plans With Tirith Policy Sets

A Tirith policy can fail a plan that would delete a resource, which guards against the destructive reconciliation that HashiCorp's tutorial warns about. StackGuardian Policy Sets support two policy engines. Tirith is a JSON-based policy framework, and OPA policies are written in Rego. The Tirith policy below fails any plan that would delete the payments team's aws_security_group, following the format of the NoCode Policy Builder documentation.

{
  "meta": {
    "required_provider": "stackguardian/terraform_plan",
    "version": "v1"
  },
  "evaluators": [
    {
      "id": "eval-id-1",
      "description": "Safeguard the payments security group against deletion",
      "provider_args": {
        "operation_type": "action",
        "terraform_resource_type": "aws_security_group",
        "terraform_resource_attribute": ""
      },
      "condition": {
        "type": "NotEquals",
        "value": "delete",
        "error_tolerance": 1
      }
    }
  ],
  "eval_expression": "eval-id-1"
}

The action operation type checks whether a resource is being created, deleted or left unchanged. Terraform records a replacement as a delete plus a create, so plans that replace the group can fail this check as well. An error_tolerance value of 1 skips the policy when the plan contains no aws_security_group, so unrelated plans are not failed.

Scope is set on the Scope tab, which lets the fintech team attach the policy to its own Workflow Group. In the Enforcement section of a rule, Action when Policy errors defaults to FAIL, and it can also be set to WARN or APPROVAL REQUIRED. Attached policies apply to the resulting runs the same way they apply to any other change.

Finding Resources That Never Had Code in Cloud Inventory

Drift detection works on resources that code already declares. Resources created by hand have nothing to drift from. SGCode addresses that side through Cloud Inventory. Per the Cloud Inventory documentation, it displays resources discovered across connected cloud accounts and assigns each a status. Unmanaged marks a resource that no IaC state file includes, and SG Drifted marks a StackGuardian-managed resource that has drifted from its expected state. Externally Managed marks resources that IaC manages outside StackGuardian. One table therefore shows both halves of the problem: what has no code, and what has code it no longer matches.

Cloud Inventory resource status values including Unmanaged, Externally Managed and SG Drifted

Resource status values in Cloud Inventory.

A Practical Drift Management Workflow for Platform Teams

A workable routine has five steps, and the fintech team runs through all of them.

  1. Detect. Automated Drift Check runs against the payments workflow and finds that the security group no longer matches its configuration.
  2. Alert. The On Drift Detection webhook posts the finding to the team's channel.
  3. Triage. An engineer reads the plan output and traces the console edit to the incident. Port 8080 is open to 0.0.0.0/0.
  4. Decide and fix. The incident is over and the rule is no longer needed, so the team picks the revert path and reruns the workflow.
  5. Prevent. The team adds a console write restriction to the production account, keeps a break-glass role for incidents and attaches a policy that fails any plan that would delete the security group. Codifying any hotfix that should stay joins the incident checklist.

Where Should You Start With Infrastructure Drift Management

Infrastructure drift is the predictable result of people and providers changing infrastructure faster than code can follow. It cannot be eliminated, so the goal is to shorten the time between a change and a decision about it. Terraform, OpenTofu, HCP Terraform and CloudFormation each detect drift within documented limits, and none of them decides what to do. Every finding ends in revert, accept or update.

To start, run terraform plan -refresh-only against the most important workspace and read what it reports. Then move detection from manual to scheduled and attach an alert to it. Teams that manage Terraform through StackGuardian can enable Automated Drift Check on a workflow and pair it with the On Drift Detection webhook. For the guardrails that stop drift from turning into an outage, continue with the policy as code guide.

Frequently Asked Questions

Is Infrastructure Drift the Same as Configuration Drift?

No. Configuration drift is one kind of infrastructure drift, where an external change invalidates what the configuration declares. State drift is the other kind, where an external change does not invalidate the configuration. HCP Terraform drift detection finds only configuration drift, so the distinction affects which tool a team relies on.

How Often Should You Run Infrastructure Drift Detection?

No universal interval exists. Detection should run often enough that the gap between a change and its discovery stays shorter than the audit cycle. HCP Terraform's documentation uses a 24-hour schedule as an example, and StackGuardian's documentation states that Automated Drift Check runs regularly. Teams with sensitive resources such as network rules may choose a shorter cycle and alert on findings.

Does Drift Detection Change My Infrastructure?

No. Terraform plans, refresh-only plans, HCP Terraform health assessments and CloudFormation drift detection report differences without changing real infrastructure. A refresh-only apply writes the changes to state, not to the cloud resource. Only a normal apply modifies infrastructure, and it does so after approval.

Can Infrastructure Drift Be Fixed Automatically?

Detection can run automatically, but the fix still needs a decision. HCP Terraform assessments and CloudFormation drift detection report drift and leave the correction to the team. In StackGuardian, users can rerun the workflow to reconcile detected drift or modify the configuration to import the changes. Automatic reverts deserve caution, since a drifted change is sometimes what keeps production up.

Does OpenTofu Support Drift Detection Like Terraform?

Yes. OpenTofu supports -refresh-only on both tofu plan and tofu apply, so a team can review and record changes made outside OpenTofu the same way it would in Terraform. Recurring checks need a platform or pipeline job that runs the plans on a schedule.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.