# 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.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 4. About 20 minutes, beginner. Source: https://devops.rajeev.pro/courses/terraform/04-project-initialization

## What you will learn

- Explain the three things terraform init does, in order
- Say which files to commit and which to ignore
- Read a lock file and explain versions, constraints and hashes
- Upgrade providers on purpose with init -upgrade, and add hashes for other platforms

> **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. <br />**Code walkthrough:** providers lock for other platforms and the .gitignore: explained, not run. <br />**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

> **Figure.** terraform init runs three steps: 1 the backend, where state lives, such as a local file, S3 or HCP; 2 modules, downloaded into .terraform/modules; 3 providers, versions resolved, signatures verified and downloaded. It writes the lock file with versions and hashes, which you commit. Below, an excerpt of .terraform.lock.hcl for hashicorp/local version 2.9.1 with constraint tilde-greater 2.9 and hashes, and the .terraform cache folder, 35 MB in the lab, which goes in .gitignore.
>
> init: backend, then modules, then providers, then the lock file.

Here's the real output for the project with the `local` and `random` providers from the last
lesson:

```sh
$ 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!
```

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:

```sh
$ 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
```

(`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

```hcl
# .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:

```sh
$ terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
```

### What goes in .gitignore

```text
# .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.**

```text
- 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.**

```text
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.**

```text
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.

## 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.

- You need: An empty folder with git init
- You'll have: .gitignore and .terraform.lock.hcl

```sh
$ 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 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

- Run `terraform init` in a new project and read every line of its output.
- Open `.terraform.lock.hcl` and find the version and constraint for each provider.
- Run `du -sh .terraform` and see how big the provider cache is.
- Run `terraform providers lock -platform=linux_amd64 -platform=darwin_arm64` and see the lock file change.
- Do the mini mission and keep your `.gitignore`.

## Quiz

1. Which file should you commit to Git?
   - The .terraform/ folder
   - **.terraform.lock.hcl** (answer)
   - terraform.tfstate
   Why: The lock file records exact provider versions and hashes so everyone gets the same builds. .terraform/ is a downloadable cache, and state can hold secrets.

2. When must you run terraform init again?
   - Before every plan
   - **After adding or changing providers, modules or the backend** (answer)
   - Only once per computer
   Why: init prepares the working directory. Other commands tell you to re-run it if the configuration needs something it hasn't set up.

3. The lock file says local 2.9.1. A teammate runs init after 2.9.5 is released. What do they get?
   - 2.9.5, the newest allowed
   - **2.9.1, the locked version, unless they run init -upgrade** (answer)
   - An error
   Why: init respects the lock file. -upgrade moves to the newest version the constraint allows and updates the lock file.

## Resources

- [terraform init command](https://developer.hashicorp.com/terraform/cli/commands/init) (HashiCorp)
- [Dependency lock file](https://developer.hashicorp.com/terraform/language/files/dependency-lock) (HashiCorp)
- [terraform providers lock command](https://developer.hashicorp.com/terraform/cli/commands/providers/lock) (HashiCorp)
- [GitHub's Terraform .gitignore template](https://github.com/github/gitignore/blob/main/Terraform.gitignore) (GitHub)
