Skip to content
$ lynuxpro
← Terraform

LESSON 2 OF 23 · BEGINNER · 18 MIN

Installing Terraform and the workflow

Free previewLesson 2 of the 2 free lessons in this Pro course.Unlock all 23

HOW IT WORKSThe Terraform workflow

initdownload pluginsfmt + validatetidy and checkplanpreviewapplymake it realdestroyremove all
1/5

init runs once per folder. It downloads providers and sets up the backend.

$ terraform init

In this lesson you install Terraform, run it for the first time, and learn the four commands you will use every day: init, plan, apply and destroy. We use the random and local providers first, because they need no cloud account and cost nothing. Everything you learn works the same with AWS.

In simple words

  • terraform init: prepares a folder: downloads providers and sets up where state is kept.
  • terraform plan: shows what Terraform would create, change or destroy, without doing it.
  • terraform apply: makes the changes for real, after you confirm.
  • terraform destroy: deletes everything this configuration created.

Installing

Terraform is a single program. Pick the way that suits your system.

# macOSbrew tap hashicorp/tapbrew install hashicorp/tap/terraform # Ubuntu / Debianwget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp.gpgecho "deb [signed-by=/usr/share/keyrings/hashicorp.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.listsudo apt-get update && sudo apt-get install terraform
SHELLbashutf-8 · 8L

Check it worked:

terraform version
SHELLbashutf-8 · 1L
Terraform v1.10.3on linux_amd64
OUTPUTterminalutf-8 · 2L

Turn on tab completion once, it saves a lot of typing:

terraform -install-autocomplete
SHELLbashutf-8 · 1L

Many versions on one machine

Projects pin different versions. A version manager such as tfenv or mise lets you switch per project:

tfenv install 1.10.3tfenv use 1.10.3
SHELLbashutf-8 · 2L

A first project

A Terraform project is just a folder of .tf files. Terraform reads every .tf file in the folder together, so file names do not matter. By habit people use:

FileHolds
main.tfThe resources
variables.tfInput variables
outputs.tfOutput values
versions.tfRequired Terraform and provider versions

Make a folder and a file:

mkdir hello-terraform && cd hello-terraform
SHELLbashutf-8 · 1L
# main.tfterraform {  required_version = ">= 1.6"  required_providers {    random = {      source  = "hashicorp/random"      version = "~> 3.6"    }    local = {      source  = "hashicorp/local"      version = "~> 2.5"    }  }} resource "random_pet" "name" {  length = 2} resource "local_file" "greeting" {  filename = "${path.module}/greeting.txt"  content  = "Hello from ${random_pet.name.id}\n"}
NORMALhclutf-8 · 23L

This makes a random two-word name, then writes it into a text file.

Step 1: init

terraform init
SHELLbashutf-8 · 1L
Initializing the backend...Initializing provider plugins...- Finding hashicorp/random versions matching "~> 3.6"...- Finding hashicorp/local versions matching "~> 2.5"...- Installing hashicorp/random v3.6.3...- Installing hashicorp/local v2.5.2...- Installed hashicorp/random v3.6.3 (signed by HashiCorp)- Installed hashicorp/local v2.5.2 (signed by HashiCorp)Terraform has created a lock file .terraform.lock.hcl to record the providerselections it made above. Include this file in your version control repositoryso that Terraform can guarantee to make the same selections by default whenyou run "terraform init" in the future.Terraform has been successfully initialized!
OUTPUTterminalutf-8 · 15L

init prepares the folder. It:

  • downloads the providers you listed into a hidden .terraform/ folder
  • sets up the backend, where state is stored (lesson 06)
  • writes .terraform.lock.hcl, which records exact provider versions and checksums

Rules for these files:

PathCommit to Git?
*.tfYes
.terraform.lock.hclYes, so everyone gets the same provider versions
.terraform/No, it is a download cache
terraform.tfstateNo, it can hold secrets (lesson 05)

A starter .gitignore:

.terraform/*.tfstate*.tfstate.*crash.log*.tfvars
OUTPUTterminalutf-8 · 5L

Run init again whenever you add a provider, change a module, or change the backend.

Step 2: plan

terraform plan
SHELLbashutf-8 · 1L
Terraform will perform the following actions:  # local_file.greeting will be created  + resource "local_file" "greeting" {      + content              = (known after apply)      + filename             = "./greeting.txt"      + id                   = (known after apply)    }  # random_pet.name will be created  + resource "random_pet" "name" {      + id        = (known after apply)      + length    = 2      + separator = "-"    }Plan: 2 to add, 0 to change, 0 to destroy.
OUTPUTterminalutf-8 · 17L

The plan compares three things: your code, the state, and the real world. Then it shows the difference. Learn these symbols:

SymbolMeaning
+will be created
-will be destroyed
~will be changed in place
-/+will be replaced (destroyed, then created)
<=will be read (a data source)

(known after apply) means the value does not exist until the resource is made, such as an ID that AWS chooses.

Save a plan to a file and apply exactly that plan later. This is how pipelines guarantee that what was reviewed is what runs:

terraform plan -out=tfplanterraform apply tfplan
SHELLbashutf-8 · 2L

Step 3: apply

terraform apply
SHELLbashutf-8 · 1L
Plan: 2 to add, 0 to change, 0 to destroy.Do you want to perform these actions?  Terraform will perform the actions described above.  Only 'yes' will be accepted to approve.  Enter a value: yesrandom_pet.name: Creating...random_pet.name: Creation complete after 0s [id=lucky-heron]local_file.greeting: Creating...local_file.greeting: Creation complete after 0s [id=3f1b...]Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
OUTPUTterminalutf-8 · 14L

Notice Terraform created random_pet first. The file uses its value, so Terraform worked out the order by itself. Lesson 07 explains this dependency graph.

cat greeting.txt
SHELLbashutf-8 · 1L
Hello from lucky-heron
OUTPUTterminalutf-8 · 1L

Run apply again

terraform apply
SHELLbashutf-8 · 1L
No changes. Your infrastructure matches the configuration.Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
OUTPUTterminalutf-8 · 3L

This is the payoff of declarative code. Nothing changes because nothing needs to. Run it ten times and the result is the same. This property is called idempotent.

Make a change

Change the greeting text and plan again:

resource "local_file" "greeting" {  filename = "${path.module}/greeting.txt"  content  = "Welcome, ${random_pet.name.id}!\n"}
NORMALhclutf-8 · 4L
  # local_file.greeting must be replaced-/+ resource "local_file" "greeting" {      ~ content = "Hello from lucky-heron\n" -> "Welcome, lucky-heron!\n" # forces replacement    }Plan: 1 to add, 0 to change, 1 to destroy.
OUTPUTterminalutf-8 · 6L

Read # forces replacement carefully. Some settings cannot be changed in place, so Terraform deletes and recreates the resource. For a text file that is harmless. For a database it would be a disaster. This is why you read every plan.

Step 4: destroy

terraform destroy
SHELLbashutf-8 · 1L
Plan: 0 to add, 0 to change, 2 to destroy.Do you really want to destroy all resources?  Enter a value: yeslocal_file.greeting: Destroying...random_pet.name: Destroying...Destroy complete! Resources: 2 destroyed.
OUTPUTterminalutf-8 · 8L

destroy removes everything this project manages. Great for test environments. Dangerous in production, so be careful which folder and workspace you are in.

Helper commands

CommandWhat it does
terraform fmtFixes spacing and style in your files
terraform fmt -checkFails if files need formatting (use in CI)
terraform validateChecks syntax and types, without contacting any API
terraform showPrints the current state in readable form
terraform outputPrints output values
terraform consoleOpens a prompt to try expressions

Try console:

terraform console
SHELLbashutf-8 · 1L
> upper("terraform")"TERRAFORM"> cidrsubnet("10.0.0.0/16", 8, 2)"10.0.2.0/24"> exit
OUTPUTterminalutf-8 · 5L

A broken file is caught by validate:

terraform validate
SHELLbashutf-8 · 1L
Error: Reference to undeclared resource  on main.tf line 18, in resource "local_file" "greeting":  18:   content  = "Hi ${random_pet.nme.id}"A managed resource "random_pet" "nme" has not been declared in the root module.
OUTPUTterminalutf-8 · 6L

The workflow in one picture

edit .tf  ->  fmt  ->  validate  ->  plan  ->  review  ->  apply                  (init first time, or after adding providers)
OUTPUTterminalutf-8 · 2L

Common mistakes

MistakeWhat happensFix
Running plan before init"Required plugins are not installed"Run terraform init
Not committing the lock fileTeammates get different provider versionsCommit .terraform.lock.hcl
Using -auto-approve by handNo chance to read the planUse it only in pipelines with a reviewed plan file
Running in the wrong folderChanges the wrong projectCheck pwd before apply and destroy

Summary

  • Install one binary; check with terraform version.
  • init downloads providers and sets up the backend. plan shows changes. apply makes them. destroy removes them.
  • Plans use +, -, ~ and -/+. forces replacement deserves extra attention.
  • Running apply twice changes nothing: Terraform is idempotent.
  • Use fmt and validate before every commit.

CHECK YOUR UNDERSTANDING

3 quick questions

  1. 1. What does terraform init do?

  2. 2. A plan shows '-/+ resource' and '# forces replacement'. What will happen on apply?

  3. 3. You run terraform apply twice in a row without changing any code. What happens the second time?

You've finished the free preview of Terraform

Upgrade to Pro to unlock the remaining 21 lessons, every practice lab and a certificate when you finish.

See plans