terraform init

terraform init prepares a directory, downloading the providers your configuration needs.

Syntaxterraform init

terraform init is the first command you run in any new or cloned Terraform project. It reads your configuration, downloads the required providers, and sets up the backend where state will be stored.

What init does

  • Downloads provider plugins into a hidden .terraform directory.
  • Creates a .terraform.lock.hcl file that pins exact provider versions.
  • Configures the state backend (local by default).

You must re-run init whenever you add a new provider or change the backend.

Example

Example · bash
terraform init

# Initializing the backend...
# Initializing provider plugins...
# - Finding hashicorp/aws versions matching "~> 5.0"...
# - Installing hashicorp/aws v5.60.0...
#
# Terraform has been successfully initialized!

When to use it

  • A new contributor clones a Terraform repository and runs terraform init to download all required provider plugins before writing any code.
  • A pipeline runs terraform init -backend-config=prod.hcl to configure the remote S3 backend before running plan in the production environment.
  • After adding a new provider to required_providers, an engineer runs terraform init to download and lock the new plugin version.

More examples

Basic init in a new directory

Runs init in a fresh directory to download the AWS provider plugin declared in the terraform block.

Example · bash
mkdir my-infra && cd my-infra

cat > main.tf <<'EOF'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws"; version = "~> 5.0" }
  }
}
EOF

terraform init
# Initializing provider plugins...
# - Installing hashicorp/aws v5.50.0...

Init with remote backend config

Passes backend configuration at init time, keeping sensitive bucket names out of committed .tf files.

Example · bash
terraform init \
  -backend-config="bucket=my-tfstate-bucket" \
  -backend-config="key=prod/terraform.tfstate" \
  -backend-config="region=us-east-1"

Upgrade providers after version bump

Uses -upgrade to download a newer provider version after the version constraint in main.tf is widened.

Example · bash
# After changing version = "~> 5.0" to "~> 5.50" in main.tf:
terraform init -upgrade
# Upgrading provider hashicorp/aws to 5.50.0...

# Lock file is updated automatically
cat .terraform.lock.hcl

Discussion

  • Be the first to comment on this lesson.