terraform init and the lock file
What terraform init sets up (backend, modules, providers), what lives in .terraform, and why .terraform.lock.hcl belongs in Git while the cache never does.
By the end of this lesson you'll be able to
0 of 4 completeVerified lab: init output, the lock file, the .terraform cache and all three init errors. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: providers lock for other platforms and the .gitignore: explained, not run.
Cloud lab: none; nothing here needs a cloud account.
terraform init is the first command in every project, and the one people understand least. It
prepares the working directory: where state lives, which modules and providers to download, and
which exact versions to use. This lesson reads its real output line by line, then looks at the file
it creates that you must commit: the lock file.
terraform init
Here's the real output for the project with the local and random providers from the last
lesson:
$ terraform init Initializing the backend... Initializing provider plugins... - Finding hashicorp/random versions matching "~> 3.7"... - Finding hashicorp/local versions matching "~> 2.9"... - Installing hashicorp/random v3.9.1... - Installed hashicorp/random v3.9.1 (signed by HashiCorp) - Installing hashicorp/local v2.9.1... - Installed hashicorp/local v2.9.1 (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!
terraform initterraforminfrastructure as codeinitdownload providers, set up the folder
Line by line:
- "Initializing the backend..." No
backendblock here, so state is a local file,terraform.tfstate. With an S3 backend, init checks it can reach the bucket (the State lesson). - Modules would be downloaded next. This project has none, so the step is skipped. You'll see it in the Modules lesson.
- "Finding ... versions matching" reads your constraints, asks the registry which versions exist, and picks the newest allowed.
- "signed by HashiCorp" means the download's signature was checked. A tampered provider would be rejected.
- The lock file records the choice.
The downloads go into a hidden cache folder:
$ du -sh .terraform 35M .terraform $ find .terraform -maxdepth 6 -type d .terraform/providers/registry.terraform.io/hashicorp/random/3.9.1/linux_amd64 .terraform/providers/registry.terraform.io/hashicorp/local/2.9.1/linux_amd64
du -sh .terraformdudisk space used by files-stotal only-hhuman-readable sizes
find .terraform -maxdepth 6 -type dfindsearch for files-maxdepthhow many folder levels to go down-typef for files, d for directories
(find printed the parent folders too; they're trimmed here.) 35 MB for two tiny providers; the
AWS provider alone is several hundred MB unpacked. That's why .terraform/ is never committed:
anyone can re-create it with terraform init.
Useful flags
| Command | When |
|---|---|
terraform init | First time, and after changing providers, modules or the backend |
terraform init -upgrade | Move providers and modules to the newest versions your constraints allow |
terraform init -reconfigure | Backend settings changed; ignore the old ones |
terraform init -migrate-state | Move existing state to a new backend (local → S3) |
terraform init -backend-config=prod.hcl | Pass backend settings per environment |
You can run init as often as you like; it's safe and only changes what's needed.
The lock file
# .terraform.lock.hcl # This file is maintained automatically by "terraform init". # Manual edits may be lost in future updates. provider "registry.terraform.io/hashicorp/local" { version = "2.9.1" constraints = "~> 2.9" hashes = [ "h1:qGLHCuYSus+uHNnoEL4SuJqOs5yrNOcB7gnuHoVqizo=", "zh:25606c7a5e308144fb627f6e31611bb52ff72bb9ae2d27af39673ab1a6b3c1bf", "zh:2568c4ef4dab31821f6f7040af0d1a2aa2b9455b8d9cc546598b791b8ada34cd", ... ] }
That's the real file, cut after a few hashes. For each provider it stores:
version: the exact version chosen,2.9.1.constraints: the constraint it was chosen under, copied from your config.hashes: checksums of the provider package. Thezh:lines are checksums of the release files the registry publishes for each platform; theh1:line is a checksum of the unpacked package Terraform installed. On every later init, Terraform checks a download against them and refuses anything that doesn't match.
Why it matters: without the lock file, a teammate who runs init next month could get 2.10.0, while
CI gets 2.9.1, and the same code plans differently on two machines. With it, everyone gets 2.9.1
until someone deliberately runs terraform init -upgrade and commits the new lock file.
Different operating systems
If you work on Linux and a teammate on an M-series Mac, the lock file needs hashes for both platforms, or their init fails the check. Add them in one go and commit the result:
$ terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64terraforminfrastructure as code
What goes in .gitignore
# .gitignore .terraform/ *.tfstate *.tfstate.* *.tfplan crash.log
Commit .terraform.lock.hcl. Ignore the cache, state files (they hold secrets, and the State lesson
moves them to a remote backend) and saved plan files.
Set plugin_cache_dir in ~/.terraformrc (for example plugin_cache_dir = "$HOME/.terraform.d/plugin-cache")
so providers are downloaded once and reused by every project, instead of a fresh copy each time.
When init goes wrong
Three errors you'll meet in your first week, each captured in the lab:
1. No provider version matches your constraint.
- Finding hashicorp/local versions matching "~> 9.0"... Error: Failed to query available provider packages Could not retrieve the list of available versions for provider hashicorp/local: no available releases match the given constraints ~> 9.0
Cause: the constraint asks for a version that doesn't exist (here 9.x of a provider that's on 2.x),
or two modules ask for versions that can't both be met. Fix: run terraform providers to see who
asks for what, check the real versions on the registry page, and loosen or correct the constraint.
2. A module was added, but init wasn't re-run.
Error: Module not installed on main.tf line 11: 11: module "site" { This module is not yet installed. Run "terraform init" to install all modules required by this configuration.
Fix: terraform init. The same applies after changing a module's source or version.
3. The backend changed, but init wasn't re-run.
Error: Backend initialization required, please run "terraform init" Reason: Initial configuration of the requested backend "local" ... Changes to backend configurations require reinitialization. This allows Terraform to set up the new configuration, copy existing state, etc. Please run "terraform init" with either the "-reconfigure" or "-migrate-state" flags to use the current configuration.
Fix: decide what should happen to the existing state. -migrate-state copies it to the new backend
(moving from local to S3); -reconfigure ignores the old one (the new backend already holds the right
state). Choosing wrong can leave you with an empty state, so back the old state up first.
Set up a project the way a team would
Create a new project with the local and random providers pinned, run terraform init, add hashes for linux_amd64 and darwin_arm64, and write a .gitignore. Then run git status and confirm only the .tf files, the lock file and .gitignore would be committed.
.gitignore and .terraform.lock.hclReveal one safe solution
$ git init -q && terraform init $ terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 $ printf '.terraform/\n*.tfstate\n*.tfstate.*\n*.tfplan\n' > .gitignore $ git status --short
git init -q && terraform initgitversion controlinitcreate a repository here&&run the next command only if this one workedterraforminfrastructure as codeinitdownload providers, set up the folder
printf '.terraform/\n*.tfstate\n*.tfstate.*\n*.tfplan\n' > .gitignore>write output to a file, replacing it
git status --shortstatuswhat changed
git status should list your .tf files, .terraform.lock.hcl and .gitignore, and nothing under
.terraform/. If the cache shows up, check the spelling of .terraform/ in .gitignore.
Try it yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
Which file should you commit to Git?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.