Overview

On a Thursday afternoon in the second half of last year, I was doing something deeply boring at my desk: renaming a variable in an old module. It used to be name, which is too vague; name_prefix says what it means. Three lines of HCL. I ran terraform plan locally three times and got No changes. Your infrastructure matches the configuration. every single time.

I opened the PR, merged it, and the CI plan job failed. Not with an error — it was stopped by a gate: that plan wanted to replace 37 resources, 9 of which were database instances and their security groups.

My first suspicion was that the CI environment had crossed state. I dug around; it hadn’t. I pulled the latest code locally and re-ran: still a no-op. Same commit, same state, same cloud account, and the two sides disagreed by 37 resources.

It took until 10 PM to find the root cause. Three problems stacked on top of each other:

  • The CI image cached the .terraform directory, so the provider actually in use was the version cached six months earlier, while my laptop had the new one. Two different provider versions interpret the same state differently.
  • Someone had generated and committed .terraform.lock.hcl on macOS, so it carried only darwin_arm64 checksums. CI runs linux_amd64, and init should have failed on the checksum mismatch — but the cache skipped that step entirely.
  • The database module was pinned at version = "~> 2.0", and combined with -upgrade in init, the module version had drifted from 2.1 all the way to 2.11. Somewhere in those minor releases, one of them changed the default behavior of the subnet field.

Each one alone is survivable. Together they made an incident.

This article is about how to plug those three holes. It is a different problem from cloud drift — Related: Terraform Drift Detection and Remediation is about “someone changed things in the console by hand”; this one is about “the toolchain changed itself”. The second is sneakier, because it leaves no trace in monitoring at all.

1. First, What Does “Version Consistency” Actually Mean in Terraform

A lot of people assume that once the .tf files are committed to Git, the environments are consistent. They are not. Getting a configuration to actually run involves at least four layers, and only the first one lives in your Git repo.

LayerWhat it isWhere it livesWho tends to mess it up
L1 Configuration.tf files, variables, module callsGitHumans (controllable)
L2 Terraform corethe terraform binary versionlocal machine / CI imageCI image tag on latest, local upgrades through brew
L3 Provider pluginse.g. aliyun/alicloud, hashicorp/aws.terraform.lock.hcl + plugin cacheinit -upgrade, image cache, cross-platform checksums
L4 Remote modulessource/version in module blocksnot in the lock filea loose version constraint drifts on its own

Of the four, L3 and L4 are the ones that bite. The reason is plain: they are external dependencies, and they can change without you knowing a thing.

Conclusion first, details after:

  1. Provider constraints must be pinned to patch level. Writing ~> 5.0 is handing over the steering wheel.
  2. .terraform.lock.hcl must be committed, and you must pre-seed multi-platform checksums with terraform providers lock — otherwise CI will definitely blow up.
  3. The lock file pins providers only, never modules. This is one sentence buried in the official docs, and it has burned countless teams. Module versions must be written as exact values.
  4. The Terraform core version needs managing too. Don’t run latest in the CI image.
  5. Locking isn’t enough on its own. You also need “the same commit must produce the same plan in two places” verification, and a change budget that stops the pipeline when destroy/replace counts exceed a threshold.

2. Three Pieces of Evidence from the Scene

During the post-mortem I laid three artifacts side by side, and the chain became obvious.

Evidence 1: the CI init log. A normal terraform init prints provider versions. Ours said:

Initializing provider plugins...
- Using previously-installed aliyun/alicloud v1.214.1
- Using previously-installed hashicorp/null v3.2.1

previously-installed means it didn’t download anything again — it used whatever sat in the cache directory. By then the latest alicloud provider was already 1.23x, and the local copy was 1.230.0.

Evidence 2: the platforms recorded in the lock file. Opening .terraform.lock.hcl:

provider "registry.terraform.io/aliyun/alicloud" {
  version     = "1.230.0"
  constraints = "~> 1.230"
  hashes = [
    "h1:Kq0m9vQY3oGmQ2rC9pVd4t6yQ8bWc1nZ5sFhLxR7uE0=",
    "zh:0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c",
  ]
}

Two hashes, one h1: and one zh:, and both correspond to the darwin_arm64 package only. The official docs are explicit: if you install a provider for the first time through something other than the registry (a filesystem mirror, for instance), Terraform can only record checksums for the current platform, and the configuration won’t work when it moves to another one.

Evidence 3: the module call.

module "rds" {
  source  = "registry.internal.example.com/infra/rds/alicloud"
  version = "~> 2.0"
}

The constraint is ~> 2.0, meaning “any 2.x will do”. Combined with the terraform init -upgrade in CI, the module pulled the newest 2.x every time. So a PR that changed three variable names also carried ten minor versions of a module along for the ride.

Evidence 1 and 2 together produced “local and CI running different providers”; evidence 3 produced “the actual semantics of the configuration keep shifting”. Those 37 replaces in the plan came down to a new provider version understanding some field’s schema differently, plus a new module version changing a default value.

One aside: this class of problem is brutally expensive to diagnose, because every conventional check is green. fmt passed, validate passed, unit tests passed, code review passed. Nothing errors. It just computes a different answer.

3. Gate One: Pin Provider Constraints to the Patch Level

Constraint syntax isn’t complicated, but the semantics differ enormously, which is worth spelling out on its own.

terraform {
  required_version = "~> 1.9.0"

  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = "~> 1.230.0"
    }
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.31.0, < 6.0.0"
    }
  }
}
SyntaxAllowed rangeWhere it belongsMy take
= 1.230.0this one version, nothing elseroot modules that need absolute reproductiontoo rigid; even a security patch needs a code change
~> 1.230.0>= 1.230.0, < 1.231.0root modules (production)recommended — patches move freely, minors need an explicit bump
~> 1.230>= 1.230, < 2.0not recommendedone drift and you’re dozens of minors away
~> 1.0>= 1.0, < 2.0toy projects onlythe same as not pinning at all
>= 5.31, < 6.0anything within the whole majorreusable submodulesa submodule shouldn’t over-constrain its callers

Here’s a point I think a lot of people get backwards: how tight a constraint should be depends on which end of the chain you’re on. There’s no one-size-fits-all rule.

  • Root module (the configuration that actually applies to the cloud): as tight as possible. ~> x.y.z down to the patch, because what you want is “run this again in three months and get the same result”.
  • Reusable module (referenced by dozens of repos): looser, counterintuitively. If you hardcode = 5.31.0 inside a module, any caller who wants 5.40 has to fork you. The right move for a module is to declare the range it’s compatible with and leave the choice to the root module.

One detail that gets overlooked: the constraints field is written into the lock file. It has no influence on installation decisions (Terraform only reads version); it exists purely for humans. But precisely because it’s for humans, it’s the one place in code review where you can quickly judge “did this PR quietly loosen a constraint”. My habit now: always look at the lock file diff on its own, and if constraints changed, ask why.

4. Gate Two: Commit the Lock File and Pre-seed Cross-Platform Checksums

.terraform.lock.hcl does exactly one thing: remember which provider version was chosen last time and reuse that decision on the next init instead of deciding again. It’s trust-on-first-use in file form — whoever you trust the first time, you keep trusting that package’s checksums.

Three fields, that’s the whole structure:

provider "registry.terraform.io/hashicorp/aws" {
  version     = "5.31.0"          # exact version actually selected last time
  constraints = "~> 5.31.0"       # constraint written in the config then, for human eyes only
  hashes = [
    "h1:...",                      # SHA256 over unpacked file contents, the primary scheme today
    "zh:...",                      # SHA256 over the official zip, legacy from the registry protocol
  ]
}

The h1: versus zh: distinction is worth knowing, because it explains why hashes keep accumulating in a lock file for the same version: zh: is the zip hash from the registry protocol and only works when installing from the official registry; h1: is computed over the file contents inside the package, so an official zip, an unpacked directory, and a re-zipped archive all match. Terraform will “helpfully” add an h1: when you install on a different platform — that’s why some people’s lock files grow forever.

To kill this drift properly, use the official command to pre-seed the platforms you care about in one shot:

# download and verify official packages for four platforms in one go, all written into the lock file
terraform providers lock \
  -platform=linux_amd64 \
  -platform=linux_arm64 \
  -platform=darwin_arm64 \
  -platform=windows_amd64

Once this finishes, every provider in the lock has zh: and h1: for each of those platforms. Anyone running init on any of them passes verification, and the classic “committed on a Mac, explodes on Linux” script stops happening.

What if you skip it? The error looks like this:

Error: Failed to install provider

Error while installing hashicorp/azurerm v2.1.0: the current package for
registry.terraform.io/hashicorp/azurerm 2.1.0 doesn't match any of the
checksums previously recorded in the dependency lock file.

When you see that, your first instinct should not be to delete the lock and start over. Deleting it throws away the trust anchor, and next time a package changes you’ll have no way of knowing. The right move is to confirm the version is fine, then run terraform providers lock to fill in the missing platforms.

The one thing that actually makes CI hard-nosed: terraform init -lockfile=readonly.

- name: Terraform Init
  run: terraform init -input=false -lockfile=readonly

This flag means “don’t touch the lock file; if something’s missing, fail”. Under the default behavior, when init finds that the lock and the config disagree it updates the lock itself — in CI that’s a disaster, because CI updates it and doesn’t commit it, so the next run makes a fresh decision. With readonly, the moment someone edits required_providers and forgets to commit the lock, CI goes red in tens of seconds, instead of you chasing a bizarre plan result an hour later.

My position is unambiguous: every terraform init in CI should carry -lockfile=readonly; the only exception is a job explicitly named “upgrade providers”.

A Note on CI Caching

That “used the old cached provider” in the incident came down to a wrong cache key. The usual mistake:

# Wrong: the cache key only watches the branch, so a changed lock file never invalidates it
cache:
  key: terraform-${{ github.ref }}
  paths:
    - .terraform

The correct approach ties the cache key to the lock file’s hash:

cache:
  key: terraform-${{ hashFiles('**/.terraform.lock.hcl') }}
  restore-keys: |
    terraform-    
  paths:
    - .terraform
    - .terraform.d

Now when the lock changes the cache dies immediately, packages are re-pulled from the registry, and checksums get verified again. The cost is a few dozen extra seconds the first run after a provider upgrade; the benefit is that the whole “hidden version mismatch caused by caching” path is gone.

There’s a safer option still: don’t cache .terraform in CI at all. A provider download takes roughly 20-40 seconds, which is nothing against a plan job that runs for minutes. In repos where latency isn’t critical I turned this cache off entirely; the debugging time I saved dwarfs those seconds.

5. Gate Three: Module Versions Must Be Exact

This is the point I most want to make in this article, because the official docs give it a single sentence:

Terraform does not remember version selections for remote modules, and so Terraform will always select the newest available module version that meets the specified version constraints.

Translated into plain terms: the lock file governs providers, not modules. Every init re-selects “the newest version that satisfies the constraint” for each module.

What makes that sentence lethal is that it runs against most people’s intuition. The common assumption is “there’s a lock file, so all the dependencies are pinned”, so module version = "~> 2.0" gets written casually — the lock will catch it. It won’t. Nothing catches it.

There is exactly one correct way to write this:

module "rds" {
  source  = "registry.internal.example.com/infra/rds/alicloud"
  version = "2.11.3"   # exact to the patch; no ~>, no >=
}

module "vpc" {
  source  = "git::https://git.internal.example.com/infra/terraform-vpc.git?ref=v3.4.1"
  # git sources can't use version, so they must use a tag, and never ?ref=main
}

A few patterns to avoid:

  • ?ref=main / ?ref=master: this ties production to someone else’s branch HEAD. They push a commit, your plan changes tomorrow.
  • ?ref=feature-xxx: looks fine in review; once the branch is deleted, CI can’t find the source at all.
  • version = "~> 2.0": see above — one of the direct causes of this incident.
  • Floating tags on a private registry (e.g. latest): the registry allows it, but it’s the same species as ?ref=main.

Module upgrades should be explicit: change 2.11.3 to 2.12.0, ship a PR containing only that one line, and keep the plan diff readable on its own. Then when something breaks you can see at a glance that a module bump caused it, instead of digging through a pile of variable renames.

One practical tip for a private module repo: add tag protection to the release flow — once a tag is published, it can’t be re-pointed at a different commit. It sounds like fussiness, but it pays off during a post-mortem: you can point at the tag and say “we were on this commit”, rather than “probably some commit that week”.

6. Gate Four: The Terraform Core Version Drifts Too

The impact of the core version is easy to underestimate. The same .tf file can plan differently on 1.5 and 1.9, and terraform test syntax is version-dependent (the native test framework only arrived in 1.6; provider mocking in 1.7). Bump the core and a pile of your test cases may simply stop running.

Two things keep it in check:

terraform {
  required_version = "~> 1.9.0"
}

First, put required_version in the configuration so a wrong version fails loudly instead of “producing something that happens to work”. The error is ugly, but it beats silently computing a different result by a factor of ten thousand.

Second, don’t use latest or a floating tag like hashicorp/terraform:light for the CI image:

# Not recommended: upstream pushes a new tag one day and your plan output changes
image: hashicorp/terraform:latest

# Recommended: pin the image tag to an exact version, and the digest if you can
image: hashicorp/terraform:1.9.8

One step further: make version collection a pre-flight check in the pipeline:

#!/usr/bin/env bash
set -euo pipefail

expected="1.9.8"
actual="$(terraform version -json | jq -r '.terraform_version')"

if [[ "${actual}" != "${expected}" ]]; then
  echo "terraform version mismatch: expected ${expected}, got ${actual}" >&2
  exit 1
fi
echo "terraform version check passed: ${actual}"

The script is under twenty lines, but it keeps “some runner has the brew build of terraform installed” out of the door. I put it in two projects and it caught a runner running 1.5.7 on the first day.

7. Gate Five: The Same Commit Must Produce a Reproducible Plan

The first four gates are all about pinning versions. But pinned doesn’t mean identical results — a configuration can still contain timestamp(), uuid(), or data sources that return rows in a different order. So you need one more gate that verifies reproducibility.

The method is crude but effective: for the same commit, generate a plan JSON locally and in CI, then compare the two resource change summaries.

# run on both sides to produce a structured plan
terraform plan -input=false -out=tfplan.bin
terraform show -json tfplan.bin > plan.json

Then compare. This script drops straight into CI:

#!/usr/bin/env python3
"""Compare the change summaries of two terraform show -json outputs to detect a non-reproducible plan."""
import json
import sys
from collections import Counter


def summarize(path):
    with open(path, encoding="utf-8") as f:
        plan = json.load(f)

    counts = Counter()
    addresses = {}
    for rc in plan.get("resource_changes", []):
        actions = rc["change"]["actions"]
        if actions == ["no-op"]:
            counts["noop"] += 1
            continue
        # both ["delete", "create"] and ["create", "delete"] mean replace
        if sorted(actions) == ["create", "delete"]:
            counts["replace"] += 1
            addresses.setdefault("replace", []).append(rc["address"])
        else:
            counts[actions[0]] += 1
            addresses.setdefault(actions[0], []).append(rc["address"])
    return counts, addresses


def main(baseline_path, current_path, budget):
    baseline, _ = summarize(baseline_path)
    current, addr = summarize(current_path)

    print("baseline plan:", dict(baseline))
    print("current plan:", dict(current))

    keys = {"create", "update", "delete", "replace", "noop"}
    drift = {k: (baseline.get(k, 0), current.get(k, 0)) for k in keys
             if baseline.get(k, 0) != current.get(k, 0)}

    if drift:
        print("plan is not reproducible; these change counts differ:")
        for k, (b, c) in drift.items():
            print(f"  {k}: baseline {b} -> current {c}")
        return 2

    # change budget: destroy and replace must be 0, otherwise an explicit approval label is required
    risky = current.get("delete", 0) + current.get("replace", 0)
    if risky > budget:
        print(f"change budget exceeded: {risky} destroy+replace against a threshold of {budget}")
        for a in addr.get("replace", []):
            print("  will replace:", a)
        return 3

    print("reproducibility check passed, within change budget")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1], sys.argv[2], int(sys.argv[3])))

This script has three engineering virtues worth spelling out:

  1. It turns “reading plan output” into a machine decision. Humans get tired reading plans; 37 replaces buried in hundreds of lines of output will genuinely be missed by eye. A program doesn’t get tired.
  2. It separates “not reproducible” from “over budget”. The first says the toolchain is broken (versions, non-deterministic expressions); the second says this change is genuinely dangerous. The two need completely different handling, and folding them into one error just makes people numb.
  3. The change budget can be a hard gate. Our rule now is: delete + replace above 0 requires an approval label, added by an SRE by hand, and CI doesn’t try to guess. The side effect is that people started explaining “why this needs replacing” in the PR description, instead of explaining after being blocked.

That sorted(actions) == ["create", "delete"] check came from a scar. Terraform doesn’t guarantee ["delete","create"] order for replaces — a create_before_destroy lifecycle block flips it to ["create","delete"]. In an early version I only matched the first form, so every create_before_destroy replacement was counted as a create, and the budget gate was decorative.

8. Upgrade Rehearsal: Treat a Provider Major Bump as Its Own Change Window

Pinning versions isn’t the goal; being able to upgrade safely is. A provider major bump (aws from 5.x to 6.x, say) is one of the riskiest operations in IaC, because it can rename fields, change defaults, and deprecate APIs. We treat it as a standalone change window with a fixed runbook:

1. Dedicated branch + dedicated PR, with no business changes riding along
2. Copy the state into a rehearsal workspace (not the production workspace)
3. Plan everything on the rehearsal workspace and walk the replace list by hand, item by item
4. For high-risk resources, apply in steps with -target, then watch for 30 minutes
5. Once it passes, merge; the production workspace goes out in the normal release window
6. Keep a state backup through the whole process

A few key details:

Always back up the state first. terraform state pull > backup.tfstate, one line. A provider upgrade can trigger a state schema upgrade, and a state upgrade is irreversible — an upgraded state can’t be read by an older Terraform. That backup is your only way back.

Don’t sneak resource changes into the upgrade PR. This is counterintuitive and extremely important. update actions showing up in an upgrade PR’s plan are normal (the provider version changed, so some computed fields get recomputed), but if your own configuration changes appear there too, you’ll never be able to tell whether a problem came from the upgrade or from your edit.

-target stepwise apply has a price. It leaves the state in a partially updated condition, and later plans without -target can produce strange diffs. We only use it in rehearsal workspaces; production always runs full. This contradicts a lot of tutorials out there, but in my experience the hangover -target leaves in production is more trouble than the risk it avoids.

Use terraform test to catch behavior changes. The native framework is genuinely useful here: write a few command = plan run blocks that assert property values on critical resources, run them before and after the upgrade, and a changed field semantic shows up immediately:

# tests/rds_plan.tftest.hcl
variables {
  env         = "test"
  name_prefix = "demo"
}

run "rds_keeps_storage_type" {
  command = plan

  assert {
    condition     = module.rds.storage_type == "cloud_essd"
    error_message = "storage type changed to ${module.rds.storage_type}; the default may have changed after the upgrade"
  }
}

run "rds_instance_class_not_empty" {
  command = plan

  assert {
    condition     = length(module.rds.instance_class) > 0
    error_message = "instance class is empty; check whether the provider renamed the field"
  }
}

These two assertions look basic, but they saved me during one provider upgrade — the new version changed a field from required to having a default, and that default was an entry-level spec. Nothing errored during plan; only the assertion could tell me “the spec is no longer what it was”.

If the upgrade touches a lot of resources and you don’t want to spend real money in a rehearsal environment, use provider mocking (supported from 1.7) for pure unit verification:

# tests/mock.tftest.hcl
mock_provider "alicloud" {
  mock_resource "alicloud_db_instance" {
    defaults = {
      instance_type = "rds.mysql.c1.large"
      storage       = 100
    }
  }
}

run "plan_with_mock" {
  command = plan

  assert {
    condition     = alicloud_db_instance.main.instance_type == "rds.mysql.c1.large"
    error_message = "instance class does not match expectation"
  }
}

Mocking’s boundary needs stating too: it verifies your configuration logic and your assertions, not the cloud API’s real behavior. It cannot answer “is this instance type actually available in the target zone” — only a real apply can. So its role is “quick regression before an upgrade”, not “a replacement for integration tests”.

9. The Numbers: Before and After Governance

These gates went in in batches. I compared three months of Q1 2025 (before) against Q2 2025 (after), on the same configuration repo: roughly 90 root modules and 460 module calls.

MetricBeforeAfterNotes
CI plan vs local mismatches141the one was a config using timestamp(), which is expected
Unintended provider upgrades90-lockfile=readonly doing its job
Rollbacks caused by version issues40—
Module version revert PRs61after: every module bump is an explicit PR
Average plan duration92s88sread-only and version checks added cost, offset by better cache hits
Average provider major upgrade11 days3 daysstandardizing the process made it faster

The last row is the most counterintuitive: with gates added, upgrades got faster. The reason is that upgrades used to depend on manual verification, so nobody dared touch them; now with a rehearsal workspace, assertions, and a change budget, the risk is broken into observable pieces, and people dare.

10. Five Judgement Calls and Why I Made Them

That covers the mechanics. The rest are judgements I’ve formed in practice — offered for reference, not as dogma.

Judgement 1: pin to patch level, but only in root modules. Inside a module, declare the compatible range (>= 5.31, < 6.0) and leave the final choice to the caller. The reasoning: a module maintainer can’t know the caller’s cloud environment, and over-constraining only forces forks.

Judgement 2: -lockfile=readonly should be the CI default, not an option. I’ve seen too many teams put terraform init -upgrade in CI believing “always newest is safer”. It’s the opposite: it turns CI into an unpredictable environment. Upgrading should be a human decision, not a pipeline side effect.

Judgement 3: exact module versions, no floating. There is no room for compromise here. The fact that the lock file doesn’t cover modules is the most widely misunderstood mechanism in IaC, and the price of misunderstanding is production being replaced at midnight.

Judgement 4: -target never goes to production. The “partially updated state” problem it creates is harder to debug than the risk it avoids. Better to split a change into several PRs run in sequence than to partially apply against the same state.

Judgement 5: use “destroy + replace count” as the only change-budget metric; don’t build a scoring system. We tried weighting by resource type (database weight 10, ECS weight 3) and it was dead within two weeks — weights need maintenance, and people don’t maintain them. Now it’s just counts: simple, explainable, and nobody argues about them.

11. Turning the Dependency Inventory into an Auditable Matrix

With 90 root modules and 400+ module calls, remembering who runs which version is not realistic. We did something plain: a script that scans the whole repo into a provider version matrix.

#!/usr/bin/env bash
# scan every lock file in the repo and print a provider version matrix
set -euo pipefail
printf "%-42s %-26s %-12s\n" "MODULE" "PROVIDER" "VERSION"

find . -name ".terraform.lock.hcl" -not -path "*/.terraform/*" | sort | while IFS= read -r lock; do
  dir="${lock%/.terraform.lock.hcl}"
  awk '
    /^provider / {
      s = $2; gsub(/"/, "", s)      # registry.terraform.io/aliyun/alicloud
      n = split(s, a, "/")          # a[n-1]=namespace, a[n]=name
      prov = a[n-1] "/" a[n]
    }
    /version *=/ {
      v = $3; gsub(/"/, "", v)
      printf "%s %s\n", prov, v
    }
  ' "$lock" | while read -r prov ver; do
    printf "%-42s %-26s %-12s\n" "$dir" "$prov" "$ver"
  done
done

The output looks roughly like this (real data, scrubbed):

MODULE                                     PROVIDER                   VERSION
./envs/prod/network                        aliyun/alicloud            1.230.0
./envs/prod/compute                        aliyun/alicloud            1.230.0
./envs/prod/data                           aliyun/alicloud            1.214.1   <-- behind
./envs/staging/compute                     aliyun/alicloud            1.230.0
./envs/staging/data                        aliyun/alicloud            1.223.0   <-- behind
./envs/shared/dns                          hashicorp/null             3.2.1

The value of this table isn’t in reading it; it’s in sorting it and spotting anomalies at a glance:

  • The same provider showing up in three or more versions → converge them, or explicitly record “why the data environment must stay on the old one”.
  • An environment more than a minor behind → check whether the lock file wasn’t committed alongside the upgrade PR.
  • A provider you didn’t expect (someone quietly used hashicorp/local to write files in some module) → a signal that code review missed something.

We hung it on a weekly scheduled job and posted the output to the ops channel. Nobody looks when there’s nothing to look at, but the moment someone asks “why does this environment behave differently from the others”, the first move is to pull up this table. Its value peaks during a post-mortem: it answers “where exactly do the two sides disagree” in under two minutes.

12. Should a Bot Open the Upgrade PRs?

The more dependencies you have, the less anyone wants to upgrade them, until it all piles into a single jump spanning dozens of versions — the riskiest kind of upgrade there is. So “let a bot open upgrade PRs” deserves serious consideration.

My conclusion is to tier it. No blanket rule:

Update typeAuto PRAuto mergeRationale
provider patch (e.g. 5.31.0 → 5.31.3)yesyes (local + CI assertions pass)under semver, patch releases shouldn’t contain breaking changes
provider minor (e.g. 5.31 → 5.40)yesno, a human reads the planchanged field defaults and schema shifts often hide in minors
provider major (e.g. 5.x → 6.x)yes, with a dedicated labelnomust go through a rehearsal window
any module version changeyesnomodules aren’t pinned, so auto-upgrade drags non-reproducibility back into the pipeline

Renovate’s Terraform support is ready-made; the key is setting rangeStrategy to pin, or it will happily “optimize” your exact versions into ~>:

{
  "packageRules": [
    {
      "matchManagers": ["terraform"],
      "rangeStrategy": "pin",
      "matchUpdateTypes": ["patch"],
      "automerge": true
    },
    {
      "matchManagers": ["terraform"],
      "matchUpdateTypes": ["major"],
      "automerge": false,
      "labels": ["iac-major-upgrade"]
    }
  ]
}

That "rangeStrategy": "pin" line is the whole point. Under the default strategy Renovate leans toward loosening constraints (it considers ranges more semantically correct), and our goal is the exact opposite — nail every version down. Without this config the bot will keep turning 2.11.3 back into ~> 2.11, and your careful pinning gets dismantled piece by piece.

One more thing: PRs from the bot must reuse the same gates. Otherwise it opens 20 PRs a week, every one of them showing green, and people start clicking merge in bulk — that turns automation into a new risk source. Our rule: patch-level PRs may auto-merge, but a plan reproducibility check runs before the merge, and if any replace or delete appears in the plan, auto-merge is cancelled immediately.

13. Three Extra Steps for Offline and Mirrored Environments

Financial and government environments are often network-restricted, with providers available only from an internal mirror. The first four gates still apply there, but you need three more things.

One: seed the checksums in a networked environment first. I mentioned this earlier, but offline it’s a hard prerequisite. When installing for the first time from a filesystem mirror, Terraform cannot obtain signature checksums for other platforms; it only records the current one. So you must run this once on a machine with internet access:

terraform providers lock \
  -platform=linux_amd64 \
  -platform=linux_arm64 \
  -platform=darwin_arm64

Then carry that lock file into the offline environment. Get the order wrong and the first init offline plants a mine: “this only works on the one machine”.

Two: pin the install source with CLI config. Disable direct connections in ~/.terraformrc, so nobody who forgot to configure the mirror silently reaches the public internet:

# ~/.terraformrc
provider_installation {
  filesystem_mirror {
    path    = "/opt/terraform-providers"
    include = ["registry.terraform.io/*/*"]
  }
  direct {
    exclude = ["registry.terraform.io/*/*"]
  }
}

Swapping include and exclude is a high-frequency mistake. Inside the mirror block, include means “these providers come from the mirror”; inside the direct block, exclude means “these don’t go direct”. The two must be paired, or you get the silent fallback of “mirror miss → go direct” — which in an offline environment manifests as inexplicable timeouts.

Three: the mirror itself needs a version. Package /opt/terraform-providers as a versioned artifact (a tarball or an OCI image) and release it alongside the lock file. Otherwise you run into “the mirror changed and nobody knows what changed”, which is harder to debug than provider drift — at least provider drift is visible in the lock file.

The provider versions in the mirror should be the union of every lock file in the repo. That step can be automated: dedupe provider+version from the matrix above and use it as your pull list.

14. Landing Checklist

Starting from zero, here’s the minimum set that fits in a day:

repo/
├── .terraform.lock.hcl          # committed, with multi-platform checksums
├── versions.tf                  # required_version + exact constraints
├── modules/                     # every module call uses an exact version
├── scripts/
│   ├── check-terraform-version.sh
│   └── compare-plan.py          # reproducibility + change budget
└── .ci/
    └── terraform.yaml

Three key CI steps:

stages:
  - validate
  - plan
  - gate

version-check:
  stage: validate
  script:
    - ./scripts/check-terraform-version.sh
    - terraform fmt -check -recursive
    - terraform init -input=false -lockfile=readonly
    - terraform validate

plan:
  stage: plan
  script:
    - terraform plan -input=false -out=tfplan.bin
    - terraform show -json tfplan.bin > plan.json
  artifacts:
    paths:
      - plan.json

change-budget:
  stage: gate
  script:
    - python3 scripts/compare-plan.py baseline-plan.json plan.json 0
  # baseline-plan.json comes from the same commit planned in the baseline environment

One architectural question is worth settling early: should providers go through an internal mirror? At small scale (a few dozen root modules), hitting the official registry directly plus a lock file is enough. At hundreds of modules with dozens of concurrent CI jobs, registry downloads become a bottleneck and rate limits get easy to trip. That’s when you add a provider mirror — but watch the side effect: on first install from a mirror, Terraform cannot get signature checksums for other platforms, so it must be paired with terraform providers lock seeding, or you’re back to the old “only usable on the platform where it was installed”. This is the same class of problem as the state architecture decision; Related: Terraform State Management covered a similar trade-off.

Summary

Back to that Thursday. If I compress the whole thing into one sentence: “code as environment” in IaC only holds up when the dependencies are reproducible too.

A few things you can take away as-is:

  • When something breaks, compare terraform version and provider versions on both sides first. Don’t start with the code. In this incident the code was perfectly fine.
  • .terraform.lock.hcl pins providers only. Leaving module versions unpinned is running naked, and ~> 2.0 in a production configuration should be stopped in review.
  • terraform providers lock pre-seeds multi-platform checksums once and kills a whole category of “fine locally, explodes in CI”.
  • Add -lockfile=readonly to CI’s init so drift surfaces within tens of seconds instead of disguising itself as a business change in the plan output.
  • Plan results have to be machine-comparable. “This diff looks normal” is the least reliable judgement there is.
  • Provider major upgrades go through their own change window: back up the state, then verify step by step in a rehearsal workspace. -target stays in the rehearsal environment.

A closing observation. What these problems have in common is that nothing alerts. Cloud drift at least shows up in a plan; dependency drift is the toolchain changing itself, and your monitoring, logs, and alerting can’t see it at all. So this layer’s defense can only be process and gates — you can’t watch it by hand.

By the way, if you’re still running terraform plan by hand and eyeballing the diff, you may as well have no gate at all. That came up in Related: A Four-Layer IaC Validation System — though that piece is about what to test, and this one fills in what to test with. If the thing under test keeps changing, even the right test design means nothing.

References & Acknowledgments

This article drew on the following sources while it was being written. Thanks to the original authors for their work:

  1. Dependency Lock File (.terraform.lock.hcl) — HashiCorp official docs: lock file structure, the difference between the h1:/zh: checksum schemes, the mechanism behind “module versions are not recorded”, and how to pre-seed multi-platform checksums with terraform providers lock
  2. Tests — Terraform Configuration Language — HashiCorp official docs: run blocks, assert assertions, command = plan/apply, and expect-fail syntax, used here for post-upgrade behavior verification
  3. Testing HashiCorp Terraform — Rosemary Wang (HashiCorp): the testing pyramid and the cost/coverage trade-off in module testing; the assertion design in this article was inspired by its unit test examples
  4. Version Constraints — HashiCorp official docs: the exact semantics of ~> and range constraints
  5. terraform providers lock — HashiCorp official CLI docs: parameters for pre-seeding multi-platform checksums
  6. terraform init — HashiCorp official CLI docs: how -lockfile=readonly and -upgrade differ in behavior