patternbashterraformMajor
Terraform provider version constraints prevent unexpected breaking changes
Viewed 0 times
Terraform >= 0.14 required for lock file support
provider versionrequired_providerslock fileterraform.lock.hclpessimistic constraintversion pinning
Error Messages
Problem
Using a provider without a version constraint (or with an overly permissive
~> 1.0) allows Terraform to download a major provider update that contains breaking changes, causing plans to fail or infrastructure to be destroyed and recreated unexpectedly.Solution
Pin providers in
required_providers with a pessimistic constraint operator that allows patch and minor bumps but blocks major version changes. Lock the exact resolved versions with .terraform.lock.hcl and commit it.terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
}Why
Terraform downloads the latest matching provider on first
terraform init. Without a lock file and explicit constraints, team members or CI pipelines can silently use different provider versions, causing plan drift.Gotchas
- Commit
.terraform.lock.hclto source control — it pins exact checksums for all platforms - Run
terraform init -upgradeintentionally when you want to bump a provider version - The
~> 5.0constraint allows5.x.xbut not6.0.0— this is the recommended pattern - Do not use
>= 5.0without an upper bound in production configurations
Code Snippets
Pinning Terraform CLI and provider versions together
terraform {
required_version = ">= 1.5.0, < 2.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.50"
}
}
}Context
Any Terraform project shared across a team or deployed via CI/CD
Revisions (0)
No revisions yet.