Skip to Content

Terraform Field Guide · Chapter 1 of 12

Why Terraform: from click-ops to code

Start here, even if you have only ever clicked around a cloud console. What goes wrong when infrastructure is built by hand, what infrastructure as code changes, and the plan-then-apply loop every chapter after this one builds on.

  • 35 min
  • Beginner
  • Hands-on
  • Free

By , founding engineer running Terraform in production. Updated .

Click-opsconsole, by hand, from memorydevt3.smallsg: 443alarmstagingt3.smallport 22alarmprodt3.largesg: 443alarm?Three environments, three shapesnobody knows which one is rightmain.tfin Gitterraform planterraform applydevt3.smallsg: 443alarmstagingt3.smallsg: 443alarmprodt3.smallsg: 443alarmAs codesame shape, sizes are inputs
The chapter in one pictureClicking builds environments that drift apart. Code builds the same thing every time, and shows you the change before it happens.

By the end you can

0 of 5

Infrastructure by hand

Most teams start the same way. Someone opens the AWS console, creates a network, launches a couple of servers, opens a port, sets up a load balancer and a database. It works. A month later the same person builds staging by doing it again, from memory.

That habit is called click-ops, and its problems arrive slowly:

  • No record. The console does not keep a readable history of why a port is open or why an instance is that size. The knowledge lives in someone's head.
  • Drift. Every hotfix made in one environment and not the others pulls them apart. "It works in staging" stops meaning anything.
  • No review. A change to production is a few clicks, seen by nobody else until something breaks.
  • No rebuild. If an environment is deleted, or you need a new region, you have to recreate it from screenshots and guesswork.

The picture at the top of this page is the result: three environments that were meant to match, and do not.

Infrastructure as code

Infrastructure as code means describing your infrastructure in text files that live in Git, and letting a tool create the real thing from them. The file becomes the single answer to "what does production look like?"

Terraform files are declarative: you describe the end result, not the steps. This is two instances of this size, not "click Launch, pick t3.small, click Launch again".

main.tf
resource "aws_instance" "web" {
  count         = 2
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.small"

  tags = {
    env = "dev"
  }
}
A resource block: the type (an EC2 instance) and a name you choose to refer to it.
Two identical instances. Change it to 3 and the next plan adds one.
An argument. Every argument a provider supports is documented on its page in the Terraform Registry.
Tags are free to change in place, without recreating anything.

Because it is text in Git, everything that works for code now works for infrastructure: pull requests, review, history, blame, revert. The same files build dev, staging and prod, so they can only differ where you say they do.

Plan, then apply

Terraform's whole workflow is one loop. You change the code. terraform plan compares it with what really exists and prints the difference. You read it. terraform apply makes exactly that change.

Step through it

What happens on terraform plan and apply

  1. Youmain.tf
  2. Terraformon your laptop or CI
  3. State filewhat it manages
  4. AWS APIwhat really exists

Step 0 of 7

Press Play, or step through with Next.

Now drive it yourself. Change the inputs, run a plan, read it, apply it. Then make a change "in the console" and see what the next plan says.

Interactive · Plan and apply

Change the code, read the plan, then apply it

main.tf what you want

terraform.tfstate what Terraform remembers

    AWS what really exists

      Three things to take from that:

      • Plan is safe. It only reads. Run it as often as you like.
      • Apply is repeatable. Running it twice changes nothing the second time. That property is called idempotence, and it is what makes automation safe.
      • Some changes replace. Renaming a bucket deletes the old one. The plan tells you; you have to read it.

      The rebuild test

      Day to day, code is a little faster than clicking. The real difference shows on the worst day. Production's network and servers are deleted at 15:00. Play both rebuilds.

      Interactive · The rebuild test

      15:00. Production is gone. Rebuild it.

      Built by hand in the console

      Down

        Built with Terraform

        Down

          One honest limit: Terraform rebuilds infrastructure, not the data inside it. A recreated database is empty. Backups are still your job.

          Do you need it?

          For a five-minute experiment you will delete this afternoon, clicking is fine. For anything that has to exist next month, or exist twice, write it down as code. The cost is a few hours to learn the basics; the payoff starts the first time you build a second environment.

          SituationBy handAs code
          Throwaway experimentFineOverkill
          One small server, one personWorks, until it does notWorth it once it matters
          Dev, staging and prodThey will driftBuilt from the same code
          A team changing productionChanges nobody reviewedEvery change is a pull request
          A new region or a disasterDays, from memoryOne apply

          Hands-on: your first plan

          You do not need a cloud account for this. The local provider manages files on your own disk, which is enough to see the whole loop for free.

          Install (macOS with Homebrew)
          brew tap hashicorp/tap
          brew install hashicorp/tap/terraform
          terraform -version
          
          hashicorp/tap
          HashiCorp's own Homebrew tap, with current releases.
          opentofu
          Prefer the open-source fork? brew install opentofu, then use tofu instead of terraform.

          On Linux or Windows, follow the official install page.

          Make a folder called hello-terraform and save this as main.tf inside it:

          main.tf
          terraform {
            required_providers {
              local = {
                source  = "hashicorp/local"
                version = "~> 2.5"
              }
            }
          }
          
          variable "greeting" {
            default = "Hello from Terraform"
          }
          
          resource "local_file" "hello" {
            filename = "${path.module}/hello.txt"
            content  = var.greeting
          }
          Which plugins this code needs. The local provider manages files; the AWS provider would manage AWS.
          Any 2.x from 2.5 up. Pinning stops a surprise major upgrade.
          An input with a default. Chapter 4 covers variables properly.
          The one resource: a file on disk.
          init, plan, apply
          terraform init
          terraform plan
          terraform apply
          Terraform has been successfully initialized!
          
          Terraform will perform the following actions:
          
            # local_file.hello will be created
            + resource "local_file" "hello" {
                + content  = "Hello from Terraform"
                + filename = "./hello.txt"
                + id       = (known after apply)
                ...
              }
          
          Plan: 1 to add, 0 to change, 0 to destroy.
          
          Do you want to perform these actions?
            Enter a value: yes
          
          local_file.hello: Creating...
          local_file.hello: Creation complete after 0s
          
          Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
          init
          Downloads the providers into .terraform/ and writes a lock file. Run it once per folder, and again when providers change.
          plan
          Shows what would change. Nothing happens yet.
          apply
          Shows the plan again and waits for you to type yes.

          Look around: there is a hello.txt, and a terraform.tfstate that records it. Run terraform plan again and it says No changes.

          Clean up
          terraform destroy
          
          destroy
          Plans the removal of everything in the state, asks for yes, then deletes it. On a real cloud account, this is how you stop paying for a lab.

          Mini mission

          Change it, and read the plan

          Apply again, then run terraform apply -var 'greeting=Hi again'. Before you type yes, find the line that says what will happen to the file. Is it updated in place, or replaced? Then add a second local_file resource and plan again.

          Reveal one safe solution
          Terminal
          terraform apply -var 'greeting=Hi again'
            # local_file.hello must be replaced
          -/+ resource "local_file" "hello" {
                ~ content  = "Hello from Terraform" -> "Hi again" # forces replacement
          
          Plan: 1 to add, 0 to change, 1 to destroy.

          The local provider cannot edit a file's content in place, so it deletes the file and writes a new one: -/+, one to add and one to destroy. Harmless here; for a database it would not be. A second resource shows up as 1 to add, and the existing file is untouched.

          Check yourself

          Quiz

          0 of 5 answered

          1. 1. Staging and production were both built by hand from the same runbook. What usually happens over a year?
          2. 2. What does terraform plan change in your cloud account?
          3. 3. A plan line starts with -/+. What will happen to that resource?
          4. 4. What is the state file for?
          5. 5. Someone changes an instance size in the console. What does the next terraform plan do?

          Further reading