Module 2: Terraform Fundamentals

Lesson 2.3: The Dependency Lock File

Plain language

Constraints say which versions are allowed. The lock file (.terraform.lock.hcl) records the version that was actually selected. With the lock file, everyone on the team and every CI run gets the same provider build, even after newer versions are released.

HCL
# .terraform.lock.hcl — generated by terraform init. Don't edit by hand.
provider "registry.terraform.io/hashicorp/random" {
  version     = "3.7.2"  # exact version selected
  constraints = "~> 3.7" # the constraint at the time of selection
  hashes = [
    "h1:...", # checksum of the package for this platform
    "zh:...", # checksums from the registry's signed release
  ]
}

Under the hood

Situation What terraform init does
No lock file yet Picks the newest version allowed by the constraints, writes the lock file
Lock file present, locked version still satisfies the constraints Installs the locked version, even if a newer one exists
You add a new provider Selects a version for the new provider and adds it to the lock file
You change a constraint so it excludes the locked version Fails with an error saying the locked version doesn't match and you must use terraform init -upgrade
terraform init -upgrade Ignores the locked versions, picks the newest allowed by the constraints (this can mean a downgrade if the constraint now requires it), and rewrites the lock file. It also upgrades modules to the newest allowed versions.

Two more points:

  • Hashes and platforms. By default the lock file records hashes for the platform that ran init. Run terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 to add hashes for teammates' and CI's platforms.
  • Commit it. Put .terraform.lock.hcl in version control, just as you would with package-lock.json.