Skip to content
watch on youtubeThe notes below cover everything in the video. Find it in the playlist on our channel.Open the YouTube channel
Lesson 8 of 1010 min video

Terraform: Infrastructure as Code

Learn Terraform on AWS: providers, resources, variables, outputs and state; build a security group and EC2 server from code; plan, apply and destroy.

Video chapters

  1. 00:00Intro
  2. 01:11Why infrastructure as code
  3. 01:58Terraform in six words
  4. 03:05Step 1: The security group, in code
  5. 04:05Step 2: The server, in code
  6. 05:00Step 3: init, plan, apply
  7. 06:22Step 4: Change it, then destroy it
  8. 07:21State: the file you must respect
  9. 08:27Habits of good Terraform code
  10. 09:19Your infrastructure is now code

Until now we've built everything by clicking. That doesn't scale, can't be reviewed, and is easy to get wrong. In this episode you describe a web server and its firewall in Terraform code, create it with one command, change it safely, and delete it completely.

What you need

  • AWS CLI configured (Episode 3)
  • Terraform installed (developer.hashicorp.com/terraform/install)
  • A code editor, e.g. VS Code with the Terraform extension

Why infrastructure as code

Why bother with infrastructure as code?

It's repeatable. The same code creates the same environment every time, with no forgotten checkbox.

It's reviewable. Infrastructure changes go through Git and pull requests, just like application code, so a teammate can catch a mistake before it reaches production.

It's documented. Instead of asking who created this server, and why, you read the code, and the Git history.

Teardown is clean. Terraform remembers what it created, and destroy removes all of it. No forgotten resources, no surprise bills.

And you can create many environments, like development, staging and production, from one codebase, just by changing a few variables.

Quick reference

  • Repeatable: Same code = same environment, every time
  • Reviewable: Changes go through Git and pull requests
  • Documented: The code IS the documentation of what exists
  • Clean teardown: destroy removes everything it created
  • Many environments: dev, staging, prod from one codebase

Terraform in six words

Six words again. A provider is a plugin that knows how to talk to a service's API. There are providers for AWS, Azure, Cloudflare, GitHub, and hundreds more.

A resource is one thing you want to exist, like a bucket, a security group, or a server.

Here's the start of every AWS project: a terraform block that says which provider we need, and pins a version range, and a provider block that sets the region. Terraform files end in dot t f, and the language is called H C L.

Variables are inputs, like the region or the instance type, so the same code works in different situations.

Outputs are values Terraform prints after it runs, like the server's public IP.

State is Terraform's record of what it created, and how that maps to real resources in AWS. It's the most important file in any Terraform project.

And a plan is a preview. Before changing anything, Terraform shows you exactly what it will create, change, or destroy.

Quick reference

  • Provider: Plugin that talks to an API: AWS, Cloudflare…
  • Resource: One thing to create: a bucket, a server
  • Variable: An input: region, instance type
  • Output: A value to print: the public IP
  • State: Terraform's record of what it created
  • Plan: A preview of exactly what will change

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = var.region
}

Step 1 · The security group, in code

Step one: the security group. Create a folder called web dash t f, with a main dot t f file, and a variables dot t f file.

Every resource block has two labels: the resource type, which comes from the provider, and a local name that you choose.

Here we create a security group, named web in our code. Then an ingress rule, allowing port eighty from anywhere. In the current AWS provider, each rule is its own resource, which makes changes cleaner and easier to review.

Notice how the rule points at the group: aws security group, dot web, dot I D. That's a reference. Terraform reads these references to work out the order: it must create the group before the rule. You never write the order yourself.

Add an egress rule as well, allowing outbound traffic, so the server can download packages. Unlike the console, Terraform doesn't add that rule automatically. It's all in the notes.

Quick reference

  1. Folder: web-tf/ · files: main.tf, variables.tf
  2. Resource type + local name
  3. References: aws_security_group.web.id
  4. Add egress rule too (allow outbound for apt)

main.tf (continued)

resource "aws_security_group" "web" {
  name = "sg-web-tf"
}

resource
  "aws_vpc_security_group_ingress_rule"
  "http" {
  security_group_id =
    aws_security_group.web.id
  cidr_ipv4   = "0.0.0.0/0"
  ip_protocol = "tcp"
  from_port   = 80
  to_port     = 80
}

Step 2 · The server, in code

Step two: the server. First, a data source. Data sources read information instead of creating anything. This one asks AWS for the latest Ubuntu twenty four oh four image, published by Canonical's official account, so your code never contains a hard-coded image I D that goes out of date.

The instance type comes from a variable, with t3 micro as the default in variables dot t f.

User data reads the same setup script from episode four, using the file function. Save it next to your code as setup dot s h.

Here's the full resource. Image from the data source, type from the variable, the security group by reference, the setup script, and a name tag. Read it out loud, and it's almost plain English.

And finally, an output that prints the server's public IP when we're done.

Quick reference

  1. Data source: find the latest Ubuntu 24.04 AMI
  2. Instance type from a variable
  3. user_data from the setup script (Episode 4)
  4. Output: print the public IP

main.tf (continued)

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type
  vpc_security_group_ids = [
    aws_security_group.web.id
  ]
  user_data = file("setup.sh")
  tags = { Name = "web-tf" }
}

output "public_ip" {
  value = aws_instance.web.public_ip
}

Step 3 · init, plan, apply

Step three: run it. terraform init downloads the AWS provider plugin. You run it once per project, and again when you add providers.

terraform fmt tidies your formatting, and validate checks the syntax. Two seconds, and they catch typos early.

terraform plan compares your code with what exists, and shows what it would do.

Here it says four to add: the security group, two rules, and the instance. Nothing to change, and nothing to destroy. That's exactly what we expect.

terraform apply shows the plan again, and asks for confirmation. Type yes, and Terraform creates everything, in the right order, in about a minute.

At the end, it prints the output: the public IP. Open it in your browser, and the page from the setup script is there. You built a server without opening the console once.

Make reading the plan a habit. It's the last moment to catch a mistake for free. Especially look for anything that says destroy.

What if apply fails halfway, for example because of a typo in a setting, or a permission you don't have? Nothing is lost. Terraform records in the state whatever it managed to create. Fix the problem, and run apply again. It continues from where it stopped, instead of creating duplicates. That's the power of state.

Quick reference

terraform init        # downloads the AWS provider
terraform fmt && terraform validate
terraform plan
Plan: 4 to add, 0 to change, 0 to destroy.
terraform apply       # shows the plan again, type: yes
Outputs:  public_ip = "203.0.113.25"
Tip: Always read the plan. It's the last moment to catch a mistake for free.

Step 4 · Change it, then destroy it

Step four: change it. Set the instance type variable to t3 small, and run plan again.

Learn these symbols. Plus means create. Tilde means update in place. Minus slash plus means destroy and re-create. And minus means destroy. Here, the instance type will be updated in place. AWS stops the instance briefly to resize it.

Some changes can't happen in place. Change the user data script, for example, and the plan may show the instance will be replaced. A new server, with a new IP. The plan tells you before anything happens.

If someone changes a resource by hand in the console, the next plan shows the difference, called drift, and offers to put it back the way the code says. The code is the source of truth.

And when you're done, terraform destroy removes everything this project created, and nothing else. Run it now, and your account is clean again.

Quick reference

  1. Change instance_type to t3.small → plan
  2. Change the user_data → instance is replaced
  3. Changed something in the console? plan shows drift
  4. terraform destroy → everything removed

plan symbols

+    create
~    update in place
-/+  destroy and re-create
-    destroy

~ instance_type: "t3.micro"
              → "t3.small"

State: the file you must respect

Now the part that trips up teams: state.

The state file maps every resource in your code to its real I D in AWS. That's how Terraform knows that aws instance dot web is that particular server.

Never edit it by hand. If you need to rename or move something, Terraform has commands for that.

State can contain sensitive values, like database passwords. So never commit the state file to Git, even in a private repository.

On a team, store state remotely. The usual AWS setup is an S3 backend: a private, versioned bucket holds the state, and use lockfile equals true stops two people from applying at the same time. Recent Terraform versions support this lock natively in S3.

One more thing you'll hear about. In twenty twenty three, Terraform changed its license, and the community created OpenTofu, an open-source fork. The language and commands are nearly identical, so everything in this episode works in both.

Quick reference

  • What it is: Maps your code to real resource IDs in AWS
  • Never edit by hand: Use terraform state commands if you must
  • Contains secrets: Never commit terraform.tfstate to Git
  • Remote state: S3 backend, with use_lockfile = true
  • Terraform or OpenTofu: Same language. OpenTofu is the open-source fork

Habits of good Terraform code

Five habits that make Terraform code professional.

A good gitignore: the dot terraform folder, every state file, and any variables file that contains secrets.

Pin versions. Lock the Terraform version and the provider versions, so your code doesn't break the day a new major version is released.

Use default tags in the provider block, so every resource automatically gets your project and environment tags. Remember why tags matter from episode three.

Split big projects into small modules, like a network module and a web server module, and reuse them across environments.

And put the plan in code review. In the next episode, we'll build pipelines, and many teams run terraform plan automatically on every pull request, so reviewers see exactly what will change.

Quick reference

  • .gitignore: .terraform/, *.tfstate*, secret *.tfvars
  • Pin versions: Terraform and provider versions in code
  • default_tags: Tag every resource from the provider block
  • Small modules: Reusable building blocks, not one giant file
  • Plan in review: Show the plan in the pull request

Your infrastructure is now code

Let's recap. You learned why infrastructure as code matters, and the core Terraform ideas: providers, resources, data sources, variables, outputs, and state. You built a security group and a web server from code, read plans, changed things safely, and destroyed everything cleanly.

The loop is always the same: write, plan, review, apply, and destroy when you're done.

In the next episode, we connect everything to Git. With GitHub Actions, every push to your repository can test and deploy automatically to AWS, without storing a single access key in GitHub. The notes, with all the Terraform files from today, are linked in the description.

Quick reference

.tf code → plan → apply → AWS

write → plan → review → apply → destroy when done

Practice

  1. Add a variable for the port and use it in the security group.
  2. Add an S3 bucket resource with versioning, then destroy everything.
  3. Move the state to an S3 backend with use_lockfile = true.

Next episode

Episode 9: CI/CD with GitHub Actions, deploying to AWS on every push.

Key takeaways

  • Infrastructure as code makes environments repeatable, reviewable and easy to destroy
  • The workflow is init → plan → apply. Always read the plan before applying
  • State maps your code to real resources: never edit it by hand or commit it to Git
  • Pin versions, tag everything with default_tags, and keep team state remote in S3