Plain language
The top-level terraform block sets two separate kinds of constraint:
required_versionrestricts which Terraform CLI versions can run this configuration.required_providersdeclares each provider's source and allowed versions.
terraform {
required_version = "~> 1.12.0" # Terraform CLI: 1.12.x only
required_providers {
random = {
source = "hashicorp/random" # where to get it
version = "~> 3.7" # which versions are allowed
}
docker = {
source = "kreuzwerker/docker"
version = ">= 3.0.0, < 4.0.0" # comma = AND
}
}
}Version constraint operators
| Operator | Meaning | Example | Allows |
|---|---|---|---|
= (or no operator) |
Exactly this version | = 3.7.2 |
3.7.2 only |
!= |
Exclude this version | != 3.7.1 |
Anything except 3.7.1 |
> >= < <= |
Comparisons | >= 3.0 |
3.0 and above |
~> |
Pessimistic constraint: only the rightmost given component may increase | ~> 3.7 |
≥ 3.7, < 4.0 |
~> 3.7.0 |
≥ 3.7.0, < 3.8.0 | ||
, |
Combine constraints (all must be true) | >= 3.5, < 3.8 |
3.5.0 – 3.7.x |
How to read ~>: strip the last number you wrote and increment the one before it. That gives the exclusive upper bound.
~> 3.7→ strip the7, increment the3→ upper bound< 4.0.~> 3.7.0→ strip the0, increment the7→ upper bound< 3.8.0.
Under the hood
- If several modules constrain the same provider, Terraform intersects all their constraints and picks the newest version that satisfies every one. If no version satisfies them all,
initfails. - Pre-release versions such as
3.8.0-beta1are selected only by an exact constraint (=or no operator). Ranges never match them. - Best practice: the root module sets upper bounds (for example
~>). Reusable child modules declare minimum versions only (>=), so they don't block callers from upgrading.