The terraform Block

The terraform block sets version constraints, required providers, and the state backend.

Syntaxterraform { required_version = ">= 1.5" required_providers { ... } }

The special terraform block configures Terraform itself, not your infrastructure. It usually lives at the top of main.tf (or its own versions.tf).

What it configures

  • required_version — which Terraform CLI versions are allowed.
  • required_providers — the source and version of each provider you use.
  • backend — where state is stored (see the State chapter).

required_providers

Each entry gives a source (like hashicorp/aws) and a version constraint. The ~> 5.0 operator means "5.x but not 6.0".

Example

Example · hcl
terraform {
  required_version = ">= 1.5.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

When to use it

  • A team pins required_version = "~> 1.9" in the terraform block to prevent team members with older CLI versions from accidentally running applies.
  • An organization uses the terraform block's backend stanza to configure S3 remote state so all engineers share the same state file.
  • A module maintainer sets required_providers with exact source addresses to ensure the module always uses the official HashiCorp provider, not a community fork.

More examples

CLI and provider version constraints

Pins both the Terraform CLI version and the AWS provider version, preventing unexpected behavior from untested upgrades.

Example · hcl
terraform {
  required_version = "~> 1.9"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.50"
    }
  }
}

S3 backend configuration

Configures a remote S3 backend with encryption and DynamoDB locking so teams share state safely.

Example · hcl
terraform {
  backend "s3" {
    bucket         = "my-tfstate-bucket"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}

Multiple providers with versions

Declares two providers in a single terraform block, each with its own source and version constraint.

Example · hcl
terraform {
  required_version = ">= 1.8.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

Discussion

  • Be the first to comment on this lesson.