terraform init: what it does and the options you'll need
terraform init prepares a working directory so the other commands can run. It configures the backend where state is stored, downloads the modules your configuration calls, installs the providers it needs and records their exact versions in .terraform.lock.hcl. Run it first in any new or freshly cloned folder, and again after you change providers, modules or the backend. It is safe to run repeatedly.
What terraform init does
Every other command needs an initialised directory. terraform init works through four steps:
- Backend. Reads the
backendblock (orcloudblock for HCP Terraform) in theterraformblock and connects to where state lives. With no backend block, state is a localterraform.tfstatefile. - Modules. Finds every
moduleblock and downloads remote modules into.terraform/modules. Local modules (./modules/network) are referenced in place. - Providers. Reads
required_providers, picks the newest version that matches each constraint (or the version already in the lock file) and installs the plugin into.terraform/providers. - Lock file. Writes or updates
.terraform.lock.hclwith the chosen versions and their checksums.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/aws v5.100.0...
- Installed hashicorp/aws v5.100.0 (signed by HashiCorp)
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
Terraform has been successfully initialized!Init never touches your infrastructure and never deletes configuration or state. It only prepares the folder.
The .terraform directory and the lock file
| Path | What it holds | Commit it? |
|---|---|---|
.terraform/providers/ | Provider plugins downloaded by init | No |
.terraform/modules/ | Downloaded modules and modules.json | No |
.terraform/terraform.tfstate | The backend configuration init used (not your infrastructure state) | No |
.terraform/environment | The currently selected workspace, if not default | No |
.terraform.lock.hcl | Exact provider versions and checksums | Yes |
Add .terraform/ to .gitignore; anyone can recreate it with terraform init. Commit the lock file, so your teammates and CI install the same provider versions you tested with. A lock file entry looks like this:
provider "registry.terraform.io/hashicorp/aws" {
version = "5.100.0"
constraints = "~> 5.0"
hashes = [
"h1:...",
"zh:...",
]
}The lock file covers providers only. Modules aren't locked; pin them with version (registry modules) or ?ref= (Git sources). See Terraform providers and Terraform modules.
When to run terraform init again
Run it again when anything init is responsible for changes:
- You cloned the repository or switched to a fresh checkout or CI runner.
- You added a provider, or changed a provider's version constraint.
- You added a
moduleblock or changed a module'ssourceorversion. - You added, changed or removed the
backendblock.
Terraform tells you when it's needed: plan and validate stop with errors like Module not installed, Inconsistent dependency lock file or Backend initialization required. Re-running init on an unchanged folder does nothing harmful. It keeps the provider versions in the lock file and only installs modules added since the last run.
terraform init -upgrade
By default init respects the lock file: if it recorded hashicorp/aws 5.100.0, you get 5.100.0 even when a newer 5.x exists. -upgrade ignores the recorded versions, picks the newest provider versions that still match your constraints, updates the lock file, and also updates modules to the newest allowed version.
terraform init -upgradeYou need it after tightening or moving a version constraint past the locked version. Without it, init stops with:
Error: Failed to query available provider packages
Could not retrieve the list of available versions for provider
hashicorp/aws: locked provider registry.terraform.io/hashicorp/aws 5.100.0
does not match configured version constraint ~> 6.0; must use terraform init
-upgrade to allow selection of new versionsReview the lock file diff in your pull request like any other dependency upgrade, and run a plan before applying with the new provider.
terraform init -reconfigure vs -migrate-state
When the backend block changes (a new bucket, a new key, local to S3), Terraform won't silently use the new settings. Plan stops with Backend initialization required and init asks you to choose:
Error: Backend configuration changed
A change in the backend configuration has been detected, which may require
migrating existing state.
If you wish to attempt automatic migration of the state, use "terraform init
-migrate-state".
If you wish to store the current configuration with no changes to the state,
use "terraform init -reconfigure".| Option | What happens to existing state | Use it when |
|---|---|---|
-migrate-state | Copied from the old backend to the new one (Terraform asks for confirmation) | You are moving state, e.g. from a local file to S3, or to a new bucket |
-reconfigure | Ignored. Init uses the new settings without copying anything | The new backend already has the right state, or you are pointing at a different environment on purpose |
-force-copy | Like -migrate-state, answering yes to the prompts | Scripted migrations |
Moving local state into S3:
terraform {
backend "s3" {
bucket = "acme-terraform-state"
key = "network/terraform.tfstate"
region = "eu-west-1"
use_lockfile = true
}
}terraform init -migrate-state
terraform state list # check everything arriveduse_lockfile turns on S3's native state locking (Terraform 1.10 and later; DynamoDB-based locking is deprecated from 1.11). Take a copy of the state before any migration. More in Terraform state.
terraform init -backend-config: partial configuration
The backend block can't use variables, locals or data sources, because it is read before anything else is evaluated. To keep environment-specific or secret settings out of the code, leave them out of the block and pass them at init time. This is called partial configuration.
# main.tf
terraform {
backend "s3" {}
}# prod.s3.tfbackend
bucket = "acme-terraform-state"
key = "app/prod.tfstate"
region = "eu-west-1"
use_lockfile = trueterraform init -backend-config=prod.s3.tfbackend
# or key by key
terraform init \
-backend-config="bucket=acme-terraform-state" \
-backend-config="key=app/prod.tfstate" \
-backend-config="region=eu-west-1"Values from -backend-config are merged into the block, and you can mix files and key/value pairs. Credentials are better left to the environment (for S3, the usual AWS credential chain) than passed as flags, because init stores the backend settings in .terraform/terraform.tfstate and command lines end up in shell history and CI logs.
Other terraform init options
| Option | What it does |
|---|---|
-input=false | Never prompt; fail instead. Use in CI. |
-backend=false | Skip backend configuration. Handy for terraform validate in CI where there are no state credentials. |
-get=false | Skip module installation (only safe when modules are already installed). |
-lockfile=readonly | Don't change the lock file; fail if the configuration needs a provider it doesn't list. Verifies checksums. Can't be combined with -upgrade. |
-plugin-dir=PATH | Install providers only from this directory, e.g. an offline mirror. |
-lock=false | Don't lock state during backend changes. Risky with a shared backend. |
-lock-timeout=60s | Wait for a state lock instead of failing. |
-from-module=SOURCE | Copy a module into an empty directory, then initialise it. |
-json | Machine-readable output. |
terraform init in CI pipelines
A pipeline starts from a clean checkout every time, so init runs on every job. A typical setup:
export TF_IN_AUTOMATION=1
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"
mkdir -p "$TF_PLUGIN_CACHE_DIR"
terraform init -input=false -lockfile=readonly -backend-config=prod.s3.tfbackend
terraform plan -input=false -out=tfplan-input=falsemakes a missing value an error instead of a prompt that hangs the job.-lockfile=readonlycatches a lock file someone forgot to commit.TF_PLUGIN_CACHE_DIRlets jobs reuse downloaded providers; cache that directory between runs.- If developers use macOS and CI runs Linux, add hashes for both platforms with
terraform providers lock -platform=darwin_arm64 -platform=linux_amd64, or init with-lockfile=readonlymay fail on checksums.
Common terraform init errors and fixes
- Failed to query available provider packages / locked provider does not match configured version constraint: you changed a constraint. Run
terraform init -upgrade. - provider registry registry.terraform.io does not have a provider named …: a typo in
source, or a provider outside thehashicorpnamespace used without arequired_providersentry, so Terraform guessedhashicorp/NAME. Addsource = "NAMESPACE/NAME". - Backend configuration changed: choose
-migrate-stateor-reconfigureas above. - Access denied (403) from S3 or another backend: the credentials init is using can't read the state bucket. Check the environment's credentials and the bucket policy.
- Error acquiring the state lock: another run holds the lock. Wait, or pass
-lock-timeout; useterraform force-unlockonly for a lock you know is stale. - Module not installed during plan: you added a module block. Run
terraform init(orterraform getfor modules alone). - Variables not allowed in the backend block: move the value to
-backend-config.
Try it in a Lab
Planfile's first Lab, Your first apply, starts with an uninitialised folder: run terraform init, read what it installs, then plan and apply. The Lab's init installs the simulated providers and local modules, so it all runs offline on your iPhone with no cloud account.
Questions
What does the terraform init command do?
It prepares the working directory: configures the backend for state, downloads modules, installs the providers the configuration requires, and writes their exact versions to .terraform.lock.hcl. It doesn't change any infrastructure.
Do I need to run terraform init every time?
No. Run it once per working directory and again after changing providers, modules or the backend, or in a fresh clone or CI job. Running it more often is harmless.
What is the difference between terraform init -upgrade and plain init?
Plain init installs the provider versions already recorded in the lock file. -upgrade picks the newest versions allowed by your constraints, updates the lock file, and updates modules too.
When should I use terraform init -reconfigure?
When the backend configuration changed and you don't want existing state copied, for example when pointing at another environment's backend. To copy state to the new backend, use -migrate-state instead.
How do I pass backend config to terraform init?
Leave the values out of the backend block and run terraform init -backend-config=FILE, or -backend-config="key=value" once per setting. This is called partial configuration.
Should I commit the .terraform folder or .terraform.lock.hcl?
Commit .terraform.lock.hcl so everyone uses the same provider versions. Don't commit .terraform/; it holds downloaded plugins and modules that init recreates.