# Infrastructure as code, and where Terraform fits

Why clicking in the console stops working, what infrastructure as code gives you, how Terraform works, how it differs from Ansible, and your first plan and apply.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 1. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/01-infrastructure-as-code

## What you will learn

- Explain what goes wrong when infrastructure is built by hand in a console
- Describe infrastructure as code and the four things it gives a team
- Explain Terraform's moving parts (configuration, providers, state, plan and apply)
- Tell provisioning tools like Terraform apart from configuration tools like Ansible
- Install Terraform and run a full init, plan, apply and destroy

> **Lab status.** **Verified lab:** your first plan, apply and drift repair with the local provider. The output shown is real. <br />**Code walkthrough:** the apt and Homebrew install commands (they differ per machine): explained, not run. <br />**Cloud lab:** none; nothing here needs a cloud account.

## Why clicking in the console doesn't scale

The first server is easy: open the AWS console, click through the wizard, done. Six months
later you have 40 resources, and:

- Nobody remembers which settings staging was built with, so production is "almost the same".
- Rebuilding after a bad day means following a wiki page that's three changes out of date.
- A security group was opened "just for a minute" in March, and it's still open.
- There's no review: one wrong click goes straight to production, and there's no history of who did it.

None of that is anyone's fault. It's what happens when the only record of your infrastructure
is the infrastructure itself.

## Infrastructure as code

**Infrastructure as code (IaC)** means describing servers, networks, databases and permissions
in text files, and letting a tool create them from those files. The files live in Git, next to
the app. That gives you four things:

1. **Repeatable.** Run the same code and get the same environment, for staging, production or a new region.
2. **Reviewed.** A change is a pull request. Teammates read it, and CI checks it, before it touches anything real.
3. **Versioned.** `git log` tells you who changed the firewall, when and why, and `git revert` takes it back.
4. **Documented.** The code is always an up-to-date description of what exists.

Most IaC tools are **declarative**: you describe the end result ("one bucket, versioning on"),
not the steps. The tool works out what to create, change or delete to get there.

## How Terraform works

**Terraform** is the most widely used IaC tool. You write configuration in **HCL**, a readable
language made of blocks, and Terraform talks to cloud APIs for you.

> **Figure.** The Terraform workflow: write .tf files, terraform init downloads providers, terraform plan compares the code with the state file and the real infrastructure, and terraform apply calls the provider APIs to make the changes and updates the state.
>
> Write, init, plan, apply. The state file is how Terraform remembers what it built.

| Piece         | What it does                                                                              |
| ------------- | ----------------------------------------------------------------------------------------- |
| Configuration | Your `.tf` files: the resources you want                                                  |
| Providers     | Plugins that know one API: AWS, Azure, Google Cloud, Kubernetes, GitHub and hundreds more |
| State         | `terraform.tfstate`: which real object each resource in your code belongs to              |
| Plan          | A preview of every create, change and destroy, before anything happens                    |
| Apply         | Makes the plan real through the provider, then updates the state                          |

The workflow is the same for every provider, which is the main reason Terraform spread: learn
it once for AWS and you can manage DNS, GitHub repos or Kubernetes the same way.

> **Terraform or OpenTofu?.** In 2023 HashiCorp moved Terraform from an open-source licence to the Business Source Licence. The community forked it as **OpenTofu**, now a Linux Foundation project. The two use the same language and workflow, and everything in this course works in both: swap `terraform` for `tofu`.

## What teams use it for

- Building whole environments in the cloud: networks, servers, load balancers, databases.
- Creating the same setup in several regions or accounts from one module.
- Managing things around the cloud, too: DNS records, monitoring alerts, GitHub repositories and team permissions.
- Short-lived environments: a full copy of the stack for each pull request, destroyed when it merges.

## Terraform vs Ansible

People often ask "Terraform or Ansible?" They mostly do different jobs:

|               | Terraform (provisioning)                       | Ansible (configuration management)                |
| ------------- | ---------------------------------------------- | ------------------------------------------------- |
| Builds        | The infrastructure: VMs, networks, buckets     | What's inside a server: packages, files, services |
| Works through | Cloud and service APIs                         | SSH into existing machines                        |
| Style         | Declarative, with a state file                 | Ordered tasks in playbooks, no state file         |
| Typical use   | "Create 3 VMs, a load balancer and a database" | "Install nginx, write its config, restart it"     |

A common split: Terraform creates the servers, and Ansible, cloud-init or a pre-built image
sets them up. With containers, there's often nothing left to configure inside the server at
all.

## Install it and run your first plan

```sh
# Ubuntu / Debian: add HashiCorp's signed package repository, then install
$ wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
$ echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
$ sudo apt update && sudo apt install terraform

# macOS
$ brew tap hashicorp/tap && brew install hashicorp/tap/terraform

$ terraform version
Terraform v1.17.1         # this course needs 1.11 or newer; the labs were run on 1.17.1
```

> **Which Terraform version.** This course needs **Terraform 1.11 or newer**: later lessons use native S3 state locking and ephemeral variables (both 1.10) and write-only arguments (1.11). Every lab was run on **1.17.1**, so that's the version to install if you want your output to match. Providers are pinned in each example's `required_providers`, and the lock file pins their exact builds.

Your first configuration doesn't need a cloud account. The `local` provider manages files on
your own machine, which is perfect for learning the workflow:

```hcl
# ~/tf-hello/main.tf
terraform {
  required_version = ">= 1.11"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
  }
}

resource "local_file" "hello" {
  filename = "${path.module}/hello.txt"
  content  = "Built by Terraform"
}
```

```sh
$ cd ~/tf-hello
$ terraform init               # downloads the providers into .terraform/
Terraform has been successfully initialized!
$ terraform plan
  # local_file.hello will be created
  + resource "local_file" "hello" {
      + content  = "Built by Terraform"
      + filename = "./hello.txt"
      ...
    }

Plan: 1 to add, 0 to change, 0 to destroy.
$ terraform apply              # shows the plan again and waits for you to type yes
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ cat hello.txt
Built by Terraform
```

Read every plan before you apply it. The last line, `Plan: 1 to add, 0 to change, 0 to
destroy`, is the one to check first: an unexpected number in the destroy column is how outages
start.

> **State holds secrets.** `terraform.tfstate` can contain passwords and keys in plain text. Never commit it to Git. Add `.terraform/`, `*.tfstate` and `*.tfstate.*` to `.gitignore` in every Terraform project. The *State* stage shows how teams store it remotely, encrypted and locked.

> **In production.** Once Terraform manages something, change it only through Terraform. Teams run `terraform plan` on every pull request and `apply` only from the pipeline after merge, so every change is reviewed and recorded.

## Mission: Let Terraform repair what you broke

Terraform manages ~/tf-hello/hello.txt. Someone deletes it by hand. Use Terraform to notice the drift and put the file back, without editing main.tf.

- You need: ~/tf-hello/main.tf from this lesson, already applied
- You'll have: ~/tf-hello/hello.txt

```sh
$ cd ~/tf-hello
$ rm hello.txt                     # the "manual change"
$ terraform plan
  # local_file.hello will be created
...
Plan: 1 to add, 0 to change, 0 to destroy.
$ terraform apply -auto-approve
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ cat hello.txt
Built by Terraform
```

Before planning, Terraform refreshes what it knows from the real world, sees the file is
missing, and plans to recreate it. That's drift detection, and on a real cloud account it's
how you catch the security group someone opened by hand. Use `-auto-approve` only when you
have just read the plan yourself.

## Try it

- Install Terraform and run `terraform version`.
- Create `~/tf-hello/main.tf` with the `local_file` example from this lesson, and run `terraform init`.
- Run `terraform plan` and find the line that says how many resources will be added.
- Run `terraform apply`, type `yes`, and check that `hello.txt` exists.
- Change the `content`, run `terraform plan` again, and read what Terraform wants to do.
- Run `terraform destroy` and confirm the file is gone.

## Quiz

1. What does `terraform plan` do?
   - Creates the resources straight away
   - **Compares your configuration with the state and the real world, and shows what it would change without changing anything** (answer)
   - Downloads the providers
   Why: `plan` is a dry run. It shows every create, change and destroy, so you (and your reviewers) can check it before `apply` makes it real.

2. Your team needs to create 3 VMs and then install and configure nginx on them. Which split makes most sense?
   - **Terraform creates the VMs; a configuration tool like Ansible (or a baked image) sets up nginx** (answer)
   - Ansible creates the VMs; Terraform installs nginx
   - Bash scripts for both
   Why: Terraform is built to provision infrastructure through cloud APIs. Configuring software inside a server is what Ansible, cloud-init or a pre-built image is for.

3. What is Terraform's state file for?
   - It stores your variables' default values
   - **It maps each resource in your code to the real object it created, so Terraform knows what exists and what to change** (answer)
   - It's a log of every command you ran
   Why: Without state, Terraform couldn't tell which real server belongs to which block of code. Treat it as sensitive and, in a team, keep it in shared remote storage with locking.

4. Someone changed a security group by hand in the AWS console. What will the next `terraform plan` show?
   - Nothing, Terraform only tracks its own changes
   - **A change to put the security group back to what the code says** (answer)
   - An error, and Terraform refuses to run
   Why: Terraform refreshes the real state before planning, notices the drift and plans to undo it. That's why manual changes and infrastructure as code don't mix.

## Resources

- [What is Terraform?](https://developer.hashicorp.com/terraform/intro) (HashiCorp)
- [Install Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) (HashiCorp)
- [The Terraform language](https://developer.hashicorp.com/terraform/language) (HashiCorp)
- [terraform init](https://developer.hashicorp.com/terraform/cli/commands/init) (HashiCorp)
- [The local provider](https://registry.terraform.io/providers/hashicorp/local/latest/docs) (Terraform Registry)
- [Infrastructure as code](https://martinfowler.com/bliki/InfrastructureAsCode.html) (Martin Fowler)
- [OpenTofu, the open-source fork](https://opentofu.org/) (OpenTofu)
