Terraform Introduction

What Terraform is, how the write-plan-apply workflow works, and your first real configuration, tested end to end on Terraform 1.17 with no cloud account.

By The Dark DebuggerUpdated 21 min read

This is the first tutorial in the Terraform track. By the end of it you will have installed Terraform, written a real configuration, and run the full lifecycle (init, plan, apply, change, destroy) on your own machine. No cloud account, no credit card, no provider downloads.

You don't need to know anything about Terraform. You should be comfortable with the command line and with editing text files. The next tutorial, Variables, Locals, Outputs, and Expressions, builds directly on the project you create here.

The problem Terraform solves

Picture a staging environment that is supposed to match production: two servers, a database, and a handful of firewall rules. The wiki page describing it is six months out of date. Someone spends a day clicking through a cloud console to rebuild it, misses one security group rule, and the next morning goes to figuring out why the app can't reach the database.

That's the job Terraform eliminates. Instead of clicking through a console, or following a stale wiki page, you describe the infrastructure you want in code, and Terraform makes reality match. The configuration file becomes the documentation, and unlike the wiki page it can't quietly drift out of date, because it's the thing doing the work.

If you've ever thought "there has to be a better way than doing this by hand for the tenth time," this track is for you.

What Terraform actually is

Terraform is a command-line tool that manages infrastructure described in configuration files. Three ideas carry most of the weight:

  1. Declarative. You describe the end state you want ("this resource should exist with these settings"), not the steps to get there. Terraform works out the steps. This is the opposite of a shell script, and it's the whole point: you stop thinking about ordering and start thinking about outcomes.
  2. Providers. Terraform itself doesn't know what an AWS server or a GitHub repo is. Providers are plugins that teach it. There are thousands, and the workflow is identical no matter which one you use, which is why learning it once pays off everywhere. Providers and Resources covers them in depth.
  3. State. Terraform keeps a record of what it created (a file called terraform.tfstate). On every run it compares your configuration, the state file, and reality, then shows you the difference before changing anything. That comparison step is the feature that makes Terraform safe to use.

We'll see all three in action below.

The workflow: write, plan, apply

Almost everything you do with Terraform is three commands:

terraform init      # one-time setup per project directory
terraform plan      # preview what will change
terraform apply     # make the changes

plan before apply is not a suggestion. It's the discipline the whole tool is built around: plan shows you exactly what Terraform is about to do, in a diff you can read. You never apply blind. Every tutorial on this site follows that rule.

Installing Terraform

Terraform is a single binary. The official install page, developer.hashicorp.com/terraform/install, has instructions for every platform: Homebrew on macOS, HashiCorp's package repositories for the common Linux distributions, and a zip download for Windows.

If you'd rather not add a package repository, the zip works on Linux too. These are the steps I used, including the checksum check that most people skip:

TF_VERSION=1.17.1
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_amd64.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --check --ignore-missing "terraform_${TF_VERSION}_SHA256SUMS"
terraform_1.17.1_linux_amd64.zip: OK

Then unzip the terraform binary into a directory on your PATH, for example ~/.local/bin:

mkdir -p ~/.local/bin
unzip -o "terraform_${TF_VERSION}_linux_amd64.zip" terraform -d ~/.local/bin

Confirm it works:

terraform version
Terraform v1.17.1
on linux_amd64

If you see a version number, you're set. Everything in this article was run with v1.17.1 on Linux. If your version is newer, the workflow below is the same; it has been stable for years.

Your first configuration

Create a directory for the project, hello-terraform, and a file called main.tf inside it. The .tf extension is how Terraform finds configuration: every file in the directory ending in .tf is loaded together, so you can split a project across as many files as you like.

# main.tf: a first Terraform configuration.
# Everything here runs locally, so you can follow along
# without an AWS, Azure or Google Cloud account.
 
terraform {
  required_version = ">= 1.5"
}
 
variable "project_name" {
  description = "Name of the demo project"
  type        = string
  default     = "shellrag-demo"
}
 
locals {
  greeting = "Hello from ${var.project_name}!"
}
 
resource "terraform_data" "example" {
  input = {
    project    = var.project_name
    created_by = "terraform"
  }
}
 
output "greeting" {
  description = "A greeting built from a local value"
  value       = local.greeting
}
 
output "resource_id" {
  description = "The ID Terraform assigned to the resource"
  value       = terraform_data.example.id
}

Let's walk through it block by block, because this file contains nearly the whole language:

  • terraform { … } holds settings about Terraform itself. Here it says which Terraform versions may run this configuration. Provider requirements go here too once we use real providers.
  • variable "project_name" is an input variable. Think of it as a function parameter for your configuration. It has a default, so nothing is required from you yet.
  • locals { … } defines local values: computed once, reused anywhere. greeting interpolates the variable with ${…} syntax.
  • resource "terraform_data" "example" is the thing we're managing. The first label is the resource type, the second is its name within our configuration. terraform_data is a built-in resource that stores a value and nothing else. That makes it perfect for learning: no provider download, no cloud account.
  • output blocks are values Terraform prints after applying. They are your window into what happened.

Resource names like "example" are for your configuration's internal use only. They never leave your files. Variables, locals and outputs get a full tutorial of their own in Variables, Locals, Outputs, and Expressions.

Initializing: terraform init

init prepares the working directory: it reads the configuration, downloads any providers and modules it needs, and sets up the backend where state is stored.

terraform init
Initializing the backend...
 
Initializing provider plugins...
- terraform.io/builtin/terraform is built in to Terraform
 
Terraform has been successfully initialized!
 
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
 
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Because terraform_data ships inside Terraform itself, there was nothing to download, and when I listed the directory afterwards there was still nothing in it but main.tf. With a registry provider you'd see an "Installing …" line here, plus a new .terraform/ directory and a .terraform.lock.hcl file. Same command, same idea; Providers and Resources shows that version in full. init is always safe to re-run.

Checking your work: fmt and validate

Two commands are worth running after every edit, before you even think about a plan:

terraform fmt
terraform validate
Success! The configuration is valid.

terraform fmt rewrites your files into the canonical style (aligned = signs, two-space indents) and prints the names of any files it changed. It printed nothing here because the file was already formatted. terraform validate checks syntax, references and types without touching any infrastructure. It's fast and it catches most typos; you'll see it fail in Common mistakes.

Previewing: terraform plan

Now the important one:

terraform plan
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create
 
Terraform will perform the following actions:
 
  # terraform_data.example will be created
  + resource "terraform_data" "example" {
      + id     = (known after apply)
      + input  = {
          + created_by = "terraform"
          + project    = "shellrag-demo"
        }
      + output = (known after apply)
    }
 
Plan: 1 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + greeting    = "Hello from shellrag-demo!"
  + resource_id = (known after apply)
 
─────────────────────────────────────────────────────────────────────────────
 
Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.

Read this the way you'd read a code review. The symbols are the whole language of plans:

  • + create, ~ update in place, - destroy. You'll see all three in this tutorial, and a fourth, -/+ (replace), in Providers and Resources.
  • (known after apply) means Terraform can't know the value until the resource exists. The ID is assigned at creation time, so there's nothing to preview yet.
  • The summary line, Plan: 1 to add, 0 to change, 0 to destroy, is what you check first. If it says anything you didn't expect, stop and investigate before applying.
  • The closing note about -out matters in team workflows. We'll use it in Where you'll use this.

Get in the habit of reading plans carefully now, while the stakes are zero. Later, when a plan says it's about to destroy a production database, that habit is what saves you.

Applying: terraform apply

The plan looks right, so apply it:

terraform apply -auto-approve
[…]
Plan: 1 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + greeting    = "Hello from shellrag-demo!"
  + resource_id = (known after apply)
terraform_data.example: Creating...
terraform_data.example: Creation complete after 0s [id=286addd6-ece8-17a9-e58c-5c58ea740078]
 
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
greeting = "Hello from shellrag-demo!"
resource_id = "286addd6-ece8-17a9-e58c-5c58ea740078"

(I trimmed the top of the output, which repeats the plan you just read.) A few things worth noticing:

  • I used -auto-approve to skip the interactive "Do you want to perform these actions?" prompt, since we had already reviewed the plan. Without that flag, apply prints the plan again and waits for you to type yes. That double-check is the default for a reason. In scripts and demos the flag is convenient; on real infrastructure, think twice before using it.
  • Terraform printed the outputs at the end. greeting used the default variable value; resource_id now has the real ID assigned at creation. Your ID will differ.
  • A file named terraform.tfstate now exists in the directory. That's the state file, Terraform's record of what it manages. Never edit it by hand.

You can ask Terraform what it's tracking:

terraform state list
terraform_data.example

And terraform show prints the full recorded state in readable form:

terraform show
# terraform_data.example:
resource "terraform_data" "example" {
    id     = "286addd6-ece8-17a9-e58c-5c58ea740078"
    input  = {
        created_by = "terraform"
        project    = "shellrag-demo"
    }
    output = {
        created_by = "terraform"
        project    = "shellrag-demo"
    }
}
 
 
Outputs:
 
greeting = "Hello from shellrag-demo!"
resource_id = "286addd6-ece8-17a9-e58c-5c58ea740078"

The state file itself is JSON. The first lines show what it really is: a versioned record, with a serial that goes up on every change and a lineage that identifies this particular state's history:

head -8 terraform.tfstate
{
  "version": 4,
  "terraform_version": "1.17.1",
  "serial": 2,
  "lineage": "7851e276-0f41-1374-9137-cb66adbbb344",
  "outputs": {
    "greeting": {
      "value": "Hello from shellrag-demo!",

Where state lives in a team, and how to keep it safe, is the subject of Terraform State: Backends, Locking, and Refactoring.

Changing something

Real infrastructure changes constantly, so let's change the project name. Edit main.tf, change the variable default from "shellrag-demo" to "shellrag-demo-v2", and plan again:

terraform plan
terraform_data.example: Refreshing state... [id=286addd6-ece8-17a9-e58c-5c58ea740078]
 
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  ~ update in-place
 
Terraform will perform the following actions:
 
  # terraform_data.example will be updated in-place
  ~ resource "terraform_data" "example" {
        id     = "286addd6-ece8-17a9-e58c-5c58ea740078"
      ~ input  = {
          ~ project    = "shellrag-demo" -> "shellrag-demo-v2"
            # (1 unchanged attribute hidden)
        }
      ~ output = {
          - created_by = "terraform"
          - project    = "shellrag-demo"
        } -> (known after apply)
    }
 
Plan: 0 to add, 1 to change, 0 to destroy.
 
Changes to Outputs:
  ~ greeting    = "Hello from shellrag-demo!" -> "Hello from shellrag-demo-v2!"
[…]

Two things to notice. First, the ~ symbols and the "old" -> "new" arrows: the same diff language, now showing a modification instead of a creation. The ID stays the same, because this is an update to the existing object, not a new one. Second, the Refreshing state… line: before diffing, Terraform re-read the current state of the resource. Plans are computed against fresh reality, not a cached guess. That's why you can trust them.

Apply it, and the greeting output updates:

terraform apply -auto-approve
[…]
terraform_data.example: Modifying... [id=286addd6-ece8-17a9-e58c-5c58ea740078]
terraform_data.example: Modifications complete after 0s [id=286addd6-ece8-17a9-e58c-5c58ea740078]
 
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
 
Outputs:
 
greeting = "Hello from shellrag-demo-v2!"
resource_id = "286addd6-ece8-17a9-e58c-5c58ea740078"

The whole loop (edit, plan, read the diff, apply) is the daily rhythm of Terraform work.

Cleaning up: terraform destroy

When you're done, tear it down:

terraform destroy -auto-approve
terraform_data.example: Refreshing state... [id=286addd6-ece8-17a9-e58c-5c58ea740078]
 
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  - destroy
 
Terraform will perform the following actions:
 
  # terraform_data.example will be destroyed
  - resource "terraform_data" "example" {
      - id     = "286addd6-ece8-17a9-e58c-5c58ea740078" -> null
[…]
    }
 
Plan: 0 to add, 0 to change, 1 to destroy.
 
Changes to Outputs:
  - greeting    = "Hello from shellrag-demo-v2!" -> null
  - resource_id = "286addd6-ece8-17a9-e58c-5c58ea740078" -> null
terraform_data.example: Destroying... [id=286addd6-ece8-17a9-e58c-5c58ea740078]
terraform_data.example: Destruction complete after 0s
 
Destroy complete! Resources: 1 destroyed.

destroy is apply with an empty desired state: everything Terraform manages in this directory gets removed, and nothing else. Without -auto-approve it shows you the destruction plan and asks for confirmation. Read destroy plans twice. There's no undo.

Habits worth having from day one

  • Commit your .tf files to git. Always. The configuration is the documentation and the deployment mechanism in one. An uncommitted main.tf is a wiki page that hasn't been written down yet.
  • Commit .terraform.lock.hcl too, once you use registry providers. It records the exact provider versions and checksums, so your teammates and your CI system install the same binaries you tested with.
  • .gitignore the rest: .terraform/, *.tfstate, *.tfstate.backup, and saved plan files. State files and plans can contain passwords and keys in plain text, and local state doesn't belong in git anyway; teams keep it in a remote backend.
  • Plan before apply, every time. The day you skip it is the day the plan would have shown you the mistake.
  • Learn locally first. Everything here ran without a cloud account on purpose. The workflow is identical with real providers (init, plan and apply don't change), so build the muscle memory where mistakes are free.

Where you'll use this

The init/plan/apply loop you just ran is the same loop teams run against real cloud accounts every day. Some places it earns its keep:

  • Identical environments. Dev, staging and production come from the same code with different inputs, so "it works in staging" means something. You'll pass per-environment values in the next tutorial and separate their state in Managing Multiple Environments.
  • Pull request review of plans. A change to infrastructure is a pull request. CI runs terraform plan, posts the output on the PR, and a reviewer reads the diff (+, ~, -) before anything is merged or applied.
  • Disaster recovery. If a region or account is lost, the configuration describes everything that has to exist. Rebuilding is terraform apply against a new target, not an archaeology project through old tickets.
  • Onboarding. A new engineer can read main.tf to learn what the system is made of, and terraform plan tells them whether reality still matches it.

Here's the review flow from the second bullet, run against our project. The key is -out: it saves the exact plan the reviewer approved, and apply then executes that file instead of computing a new plan.

terraform plan -out=tfplan
[…]
Plan: 1 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + greeting    = "Hello from shellrag-demo!"
  + resource_id = (known after apply)
 
─────────────────────────────────────────────────────────────────────────────
 
Saved the plan to: tfplan
 
To perform exactly these actions, run the following command to apply:
    terraform apply "tfplan"

terraform show tfplan prints the saved plan in the same human-readable format, and that text is what CI pipelines usually paste into the pull request. After approval:

terraform apply tfplan
terraform_data.example: Creating...
terraform_data.example: Creation complete after 0s [id=216c4749-f3f2-21f7-21bb-7577e73ed522]
 
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
greeting = "Hello from shellrag-demo!"
resource_id = "216c4749-f3f2-21f7-21bb-7577e73ed522"

No confirmation prompt this time: approving the saved plan was the confirmation. And there's a safety net built in. If anyone changes the state between your plan and your apply, Terraform refuses to run the old plan. You'll trigger that on purpose in Exercise 4. Testing and CI for Terraform builds this flow into a full pipeline.

Common mistakes

"Reference to undeclared input variable"

The most common beginner error: you renamed a variable in its variable block but not where it's used, or you simply typo'd it. I changed var.project_name to var.projekt_name in the locals block and ran terraform validate:

╷
│ Error: Reference to undeclared input variable
│ 
│   on main.tf line 16, in locals:
│   16:   greeting = "Hello from ${var.projekt_name}!"
│ 
│ An input variable with the name "projekt_name" has not been declared. Did
│ you mean "project_name"?
╵

Note the "Did you mean" suggestion. Terraform's error messages are genuinely good: they name the file, the line and usually the fix. Read them fully before searching the internet, and run terraform validate after every edit to catch these in seconds.

"Inconsistent dependency lock file" after adding a provider

I added a resource from a registry provider (random_pet, from hashicorp/random) and ran terraform plan without re-running init:

╷
│ Error: Inconsistent dependency lock file
│ 
│ The following dependency selections recorded in the lock file are
│ inconsistent with the current configuration:
│   - provider registry.terraform.io/hashicorp/random: required by this configuration but no version is selected
│ 
│ To make the initial dependency selections that will initialize the
│ dependency lock file, run:
│   terraform init
╵

The configuration now needs a provider that was never downloaded. The fix is in the message: run terraform init. You'll hit the same thing after cloning someone else's project. init only prepares the working directory, so it is always safe to run.

Plan wants to create something that already exists

Terraform only knows about what its state file records. To see what that means, I applied the project, moved terraform.tfstate out of the directory, and planned again:

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create
 
Terraform will perform the following actions:
 
  # terraform_data.example will be created
[…]
Plan: 1 to add, 0 to change, 0 to destroy.

The resource still existed as far as reality was concerned, but without state Terraform had no idea, so it planned to create it again. With a real cloud resource, applying that plan would either create a duplicate or fail with an "already exists" error. If a plan wants to create something you know exists, stop: you are pointing at the wrong (or a missing) state, not looking at a Terraform bug. Don't hand-edit terraform.tfstate to "fix" it. Find out why the state and reality disagree first. (I put the file back, and the next plan was clean again.)

Summary

  • Terraform manages infrastructure described as code: you declare the end state, Terraform computes the steps and shows them to you first.
  • The workflow is init (prepare the directory), plan (preview the diff), apply (make it real). Read every plan like a code review, starting from the Plan: X to add, Y to change, Z to destroy line.
  • Plan symbols: + create, ~ update in place, - destroy; (known after apply) marks values that only exist once the resource does.
  • State (terraform.tfstate) is how Terraform knows what it manages. Lose it and Terraform forgets; never edit it by hand. Inspect it with terraform state list and terraform show.
  • terraform fmt and terraform validate are cheap, offline checks to run after every edit.
  • terraform plan -out=FILE plus terraform apply FILE applies exactly what was reviewed, and refuses to run if the state changed in between.
  • terraform destroy removes everything this configuration manages. Read destroy plans twice.

Exercises

Exercise 1: Change the greeting without editing the fileeasy

Make the greeting output say Hello from checkout-api! without changing main.tf. Apply it, then print just the greeting with terraform output, once quoted and once as a raw string you could use in a shell script.

Hint

terraform apply accepts -var 'name=value'. terraform output takes an output name, and has a -raw flag.

Show Solution
terraform apply -auto-approve -var 'project_name=checkout-api'
terraform output greeting
terraform output -raw greeting
[…]
Outputs:
 
greeting = "Hello from checkout-api!"
resource_id = "ff984642-b04b-720b-ba23-6576f930b36d"
"Hello from checkout-api!"
Hello from checkout-api!

-var overrides the default for this run only. That's how one configuration serves dev, staging and prod with different names. -raw drops the quotes, which is what you want when capturing the value with $(terraform output -raw greeting).

Exercise 2: Add a second resourceeasy

Add another terraform_data resource named second whose input is project = "billing-worker", then run plan. How many resources does the plan want to add? What happens to terraform_data.example? Apply, then check terraform state list.

Show Solution
resource "terraform_data" "second" {
  input = {
    project = "billing-worker"
  }
}
terraform plan -var 'project_name=checkout-api'
terraform_data.example: Refreshing state... [id=ff984642-b04b-720b-ba23-6576f930b36d]
[…]
  # terraform_data.second will be created
  + resource "terraform_data" "second" {
      + id     = (known after apply)
      + input  = {
          + project = "billing-worker"
        }
      + output = (known after apply)
    }
 
Plan: 1 to add, 0 to change, 0 to destroy.

I kept passing the -var from Exercise 1; without it, Terraform would also plan to change example back to the default name. The existing resource is refreshed but not changed, because its configuration didn't change. After applying with the same -var:

terraform state list
terraform_data.example
terraform_data.second

This is the declarative payoff: Terraform only touches what differs from the desired state.

Exercise 3: Break it on purpose, then fix itmedium

Introduce a typo in the variable reference inside locals (for example var.projekt_name) and run terraform validate. Read the error, fix the typo, validate again, then destroy everything you created.

Show Solution
terraform validate
╷
│ Error: Reference to undeclared input variable
│ 
│   on main.tf line 16, in locals:
│   16:   greeting = "Hello from ${var.projekt_name}!"
│ 
│ An input variable with the name "projekt_name" has not been declared. Did
│ you mean "project_name"?
╵

After fixing the reference:

terraform validate
terraform destroy -auto-approve
Success! The configuration is valid.
 
[…]
Destroy complete! Resources: 2 destroyed.

You'll see 2 destroyed if you did Exercise 2, 1 otherwise. validate never contacts any infrastructure, which is why it's safe to run constantly.

Exercise 4: Watch a saved plan go stalehard

Apply the project, then save a plan that changes project_name back to its default (terraform plan -out=tfplan). Before applying that file, run a different terraform apply -auto-approve -var 'project_name=other'. Now try terraform apply tfplan. What happens, and why is that the behaviour you want in a team?

Show Solution
terraform apply -auto-approve -var 'project_name=checkout-api'
terraform plan -out=tfplan
terraform apply -auto-approve -var 'project_name=other'
terraform apply tfplan

The last command refuses to run:

╷
│ Error: Saved plan is stale
│ 
│ The given plan file can no longer be applied because the state was changed
│ by another operation after the plan was created.
╵

The saved plan was computed against a state that no longer exists. Applying it blindly could undo or collide with whatever changed in between, so Terraform refuses. In a team this is exactly the protection you want when two pull requests touch the same infrastructure: the second one has to re-plan, and its reviewer sees a fresh diff. Run terraform plan -out=tfplan again and terraform apply tfplan succeeds.


Tested with: Terraform v1.17.1 on Ubuntu 24.04 (WSL2, linux_amd64), November 2026. Every command and output in this article was run as shown and pasted verbatim, with long repeated plan text trimmed where marked […]; IDs will differ on your machine. I verified the zip download and checksum steps but unzipped into a scratch directory rather than ~/.local/bin; the macOS and Windows install routes on the official page were not run. Re-tested from scratch for this update: on 1.17.1, init for a configuration that only uses terraform_data creates no .terraform/ directory and no lock file, which corrects the previous version of this page.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Terraform tutorial here is tested end to end before publishing.