DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 4 of 17
Your progress · 0%
On this page
  1. terraform init
  2. The lock file
  3. When init goes wrong
↖ Course roadmap
Lesson 4 · Project initialization

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.

20 min read · beginner · hands-on

By the end of this lesson you'll be able to

0 of 4 complete
Lab status

Verified 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

init: backend, then modules, then providers, then the lock file.© Diagram: DevOps Academy

init: backend, then modules, then providers, then the lock file.© Diagram: DevOps Academy

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 init
  • terraforminfrastructure as code
  • initdownload providers, set up the folder

Line by line:

  1. "Initializing the backend..." No backend block here, so state is a local file, terraform.tfstate. With an S3 backend, init checks it can reach the bucket (the State lesson).
  2. Modules would be downloaded next. This project has none, so the step is skipped. You'll see it in the Modules lesson.
  3. "Finding ... versions matching" reads your constraints, asks the registry which versions exist, and picks the newest allowed.
  4. "signed by HashiCorp" means the download's signature was checked. A tampered provider would be rejected.
  5. 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 .terraform
  • dudisk space used by files
  • -stotal only
  • -hhuman-readable sizes
find .terraform -maxdepth 6 -type d
  • findsearch 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

CommandWhen
terraform initFirst time, and after changing providers, modules or the backend
terraform init -upgradeMove providers and modules to the newest versions your constraints allow
terraform init -reconfigureBackend settings changed; ignore the old ones
terraform init -migrate-stateMove existing state to a new backend (local → S3)
terraform init -backend-config=prod.hclPass 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. The zh: lines are checksums of the release files the registry publishes for each platform; the h1: 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_amd64
  • terraforminfrastructure 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.

Speed up init on your machine

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.

⌘
Mini mission

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.

Input: An empty folder with git initOutput: .gitignore and .terraform.lock.hcl
Reveal 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 init
  • gitversion control
  • initcreate a repository here
  • &&run the next command only if this one worked
  • terraforminfrastructure as code
  • initdownload providers, set up the folder
printf '.terraform/\n*.tfstate\n*.tfstate.*\n*.tfplan\n' > .gitignore
  • >write output to a file, replacing it
git status --short
  • statuswhat 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 done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

Which file should you commit to Git?

Go deeper

Official reading for this lesson

  • Docsterraform init commandHashiCorp ↗
  • DocsDependency lock fileHashiCorp ↗
  • Docsterraform providers lock commandHashiCorp ↗
  • ToolGitHub's Terraform .gitignore templateGitHub ↗

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.

← PreviousProviders and version pinningNext lesson →Resources: count, for_each and lifecycle