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 terraformCheck it worked:
terraform versionTerraform v1.10.3on linux_amd64Turn on tab completion once, it saves a lot of typing:
terraform -install-autocompleteMany 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.3A 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:
| File | Holds |
|---|---|
main.tf | The resources |
variables.tf | Input variables |
outputs.tf | Output values |
versions.tf | Required Terraform and provider versions |
Make a folder and a file:
mkdir hello-terraform && cd hello-terraform# 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"}This makes a random two-word name, then writes it into a text file.
Step 1: init
terraform initInitializing 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!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:
| Path | Commit to Git? |
|---|---|
*.tf | Yes |
.terraform.lock.hcl | Yes, so everyone gets the same provider versions |
.terraform/ | No, it is a download cache |
terraform.tfstate | No, it can hold secrets (lesson 05) |
A starter .gitignore:
.terraform/*.tfstate*.tfstate.*crash.log*.tfvarsRun init again whenever you add a provider, change a module, or change the backend.
Step 2: plan
terraform planTerraform 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.The plan compares three things: your code, the state, and the real world. Then it shows the difference. Learn these symbols:
| Symbol | Meaning |
|---|---|
+ | 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 tfplanStep 3: apply
terraform applyPlan: 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.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.txtHello from lucky-heronRun apply again
terraform applyNo changes. Your infrastructure matches the configuration.Apply complete! Resources: 0 added, 0 changed, 0 destroyed.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"} # 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.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 destroyPlan: 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.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
| Command | What it does |
|---|---|
terraform fmt | Fixes spacing and style in your files |
terraform fmt -check | Fails if files need formatting (use in CI) |
terraform validate | Checks syntax and types, without contacting any API |
terraform show | Prints the current state in readable form |
terraform output | Prints output values |
terraform console | Opens a prompt to try expressions |
Try console:
terraform console> upper("terraform")"TERRAFORM"> cidrsubnet("10.0.0.0/16", 8, 2)"10.0.2.0/24"> exitA broken file is caught by validate:
terraform validateError: 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.The workflow in one picture
edit .tf -> fmt -> validate -> plan -> review -> apply (init first time, or after adding providers)Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Running plan before init | "Required plugins are not installed" | Run terraform init |
| Not committing the lock file | Teammates get different provider versions | Commit .terraform.lock.hcl |
Using -auto-approve by hand | No chance to read the plan | Use it only in pipelines with a reviewed plan file |
| Running in the wrong folder | Changes the wrong project | Check pwd before apply and destroy |
Summary
- Install one binary; check with
terraform version. initdownloads providers and sets up the backend.planshows changes.applymakes them.destroyremoves them.- Plans use
+,-,~and-/+.forces replacementdeserves extra attention. - Running apply twice changes nothing: Terraform is idempotent.
- Use
fmtandvalidatebefore every commit.
CHECK YOUR UNDERSTANDING
3 quick questions
1. What does terraform init do?
2. A plan shows '-/+ resource' and '# forces replacement'. What will happen on apply?
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