Terraform Tutorial — Provider Versioning
Providers release new versions frequently — adding resources, fixing bugs, and occasionally introducing breaking changes. Version constraints let you control which versions Terraform uses.
Version Constraint Operators
| Operator | Meaning | Example | Matches |
|---|---|---|---|
= (exact) |
Exactly this version | = 5.31.0 |
Only 5.31.0 |
!= |
Not this version | != 5.30.0 |
Everything except 5.30.0 |
>, >= |
Greater than | >= 5.0.0 |
5.0.0, 5.31.0, 6.0.0, … |
<, <= |
Less than | < 6.0.0 |
5.x.x but not 6.0.0 |
~> |
Pessimistic constraint | ~> 5.0 |
>= 5.0, < 6.0 (any 5.x) |
The ~> Operator (Most Common)
The pessimistic constraint operator ~> is the most commonly used. It allows the rightmost version component to increment:
# Allow any 5.x version (5.0.0, 5.31.0, 5.99.0, but not 6.0.0)
version = "~> 5.0"
# Allow any 5.31.x version (5.31.0, 5.31.1, but not 5.32.0)
version = "~> 5.31.0"
Why ~> 5.0 is recommended: Minor versions (5.30 → 5.31) add new features and bug fixes but shouldn’t break existing resources. Major versions (5.x → 6.x) may have breaking changes.
Combining Constraints
Use commas to combine multiple constraints:
# At least 5.0 but less than 6.0
version = ">= 5.0.0, < 6.0.0"
# Equivalent to ~> 5.0, but explicit
The Lock File
When you run terraform init, Terraform writes the exact resolved version to .terraform.lock.hcl:
provider "registry.terraform.io/hashicorp/aws" {
version = "5.31.0"
constraints = "~> 5.0"
hashes = [
"h1:ltYPMnfPhat6NjBMBn0NpsRMwa2dBbKaYZkHlLBbH1A=",
]
}
This lock file ensures every team member and CI runner uses exactly the same version, even if a newer version matching the constraint is available.
Always commit .terraform.lock.hcl to Git.
Upgrading Providers
To upgrade to a newer version within your constraints:
$ terraform init -upgrade
This re-resolves version constraints and updates the lock file. Review the changes before committing.
To upgrade to a new major version, update the constraint first:
# Before
version = "~> 4.0"
# After
version = "~> 5.0"
Then run terraform init -upgrade.
⚠️ Warning: Major version upgrades may include breaking changes. Read the provider’s changelog before upgrading. Run
terraform planto see if any resources would be affected.
Best Practices
| Practice | Why |
|---|---|
| Always specify version constraints | Prevents unexpected upgrades |
Use ~> X.0 for flexibility |
Gets bug fixes automatically |
Commit .terraform.lock.hcl |
Ensures version consistency |
| Review changelogs before upgrading | Catches breaking changes early |
| Pin exact versions in production | Maximum stability |
What’s Next?
You understand provider versioning. Now let’s configure the AWS provider — the one we’ll use throughout the rest of this tutorial.