Um momento
0x90Lesson 10 of 16

Infrastructure as code

Describe servers, networks and buckets in versioned files, and let Terraform work out what to create, change and destroy.

30 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Explain why infrastructure as code beats clicking around a cloud console
  • Read Terraform configuration: providers, resources, variables and references
  • Read a plan - creates, in-place updates, replacements and destroys - before applying it

Byte Bakery’s production server was set up two years ago by an engineer clicking through the cloud console - an approach lovingly called ClickOps. She has since left. Nobody knows which settings matter, staging differs in forty undocumented ways, and rebuilding production after a disaster would take a week of archaeology. It’s a snowflake server: unique, fragile and irreplaceable.

Infrastructure as code (IaC) describes infrastructure in text files that live in Git. You get everything code gets: review in pull requests, history, reuse and automation. Rebuilding an environment becomes running a command, and staging can be a true copy of production.

Most IaC tools are declarative: you describe the end state (“one t3.small server, one bucket”), and the tool works out the steps. Running it again changes nothing - it’s idempotent. An imperative script (“create a server”) run twice gives you two servers.

Terraform

Terraform (and its open-source fork OpenTofu) is the most widely used IaC tool. You write HCL (HashiCorp Configuration Language); providers translate it into API calls for AWS, Azure, Google Cloud, Kubernetes, GitHub and hundreds more. Other tools include AWS CloudFormation, Azure Bicep and Pulumi (which uses general-purpose languages).

main.tf
1terraform {
2  required_providers {
3    aws = { source = "hashicorp/aws", version = "~> 5.0" }
4  }
5}
6
7provider "aws" {
8  region = "eu-west-1"
9}
10
11variable "environment" {
12  type    = string
13  default = "staging"
14}
15
16resource "aws_s3_bucket" "photos" {
17  bucket = "byte-bakery-${var.environment}-photos"
18}
19
20resource "aws_instance" "web" {
21  ami           = "ami-0b1e2c3d4e5f60718"
22  instance_type = var.environment == "production" ? "t3.medium" : "t3.small"
23  tags = {
24    Name        = "web-${var.environment}"
25    PhotoBucket = aws_s3_bucket.photos.bucket   # a reference: Terraform creates the bucket first
26  }
27}
28
29output "web_ip" {
30  value = aws_instance.web.public_ip
31}

The workflow:

  1. terraform init downloads the providers.
  2. terraform fmt and terraform validate tidy and check the files.
  3. terraform plan compares the configuration with what exists and shows exactly what it would do - read it carefully. Many teams post the plan on the pull request.
  4. terraform apply makes the changes.

In the plan, + means create, ~ update in place, - destroy, and -/+ replace: some attributes (a server’s machine image, a bucket’s name) can’t be changed in place, so the resource is destroyed and created again - which can mean downtime or lost data.

Try it

Read the plan

This is Byte Bakery’s staging infrastructure. Toggle edits to the configuration and read the plan.

  • Which edits update in place, and which force a replacement?
  • What would renaming the photo bucket do to the photos inside it?
  • Turn on a few edits, click terraform apply, and look at the plan again. Why is it empty?
Edit the configuration:

$ terraform plan

No changes. Your infrastructure matches the configuration.

Key takeaways

  • Infrastructure as code replaces hand-built snowflake servers with versioned, reviewable files.

  • Declarative tools like Terraform compute the steps from the desired end state, idempotently.

  • Resources reference each other, which tells Terraform what to create first.

  • Read every plan - especially replacements and destroys - before applying.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: automate DevOps chores in Python

Write the small Python tools DevOps teams really build - pipeline runners, plan checkers, metric calculators, scanners - and run them against sample inputs. They run locally in your browser; no servers or cloud accounts needed.

Exercise 1

Write a plan

+25 XP

The input is the current resources, ---, then the desired ones. Each line is address key=value ...; in the desired section, an attribute written !key=value forces replacement if it changes.

Print the plan: resources in desired order, then destroyed ones in current order:

  • + create aws_sqs_queue.orders
  • ~ update aws_instance.web: instance_type t3.small -> t3.medium (all changed attributes, in desired order, comma-separated; a missing value shows as (none))
  • -/+ replace aws_instance.web (ami forces replacement) (or (ami, bucket force replacement))
  • - destroy aws_security_group.legacy

End with Plan: 1 to add, 1 to change, 1 to destroy. (a replacement counts as one add and one destroy) or No changes. Your infrastructure matches the configuration.

  • Staging changes
  • Nothing to do
  • Attributes added and removed
  • In-place only
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Exercise 2

Work out the apply order

+25 XP

Each input line is address: references... - the resources this one refers to, which must exist first. Work out a creation order: repeatedly create the alphabetically first resource whose references have all been created. (Terraform creates independent resources in parallel; this exercise picks one at a time.) Destroying goes in the exact reverse order.

Print create: a -> b -> c and destroy: c -> b -> a. If some resources can never be created, print cycle: a, b with them alphabetically instead.

  • A small network
  • A cycle
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: