Cloud Explainers

Terraform: Full Tutorial for Beginners

Terraform23 min video

A full Terraform tutorial for beginners, on a real AWS account: install Terraform on Ubuntu, write your first .tf file, terraform init, plan and apply, read the plan's symbols, the state file, a real EC2 web server with a security group and a data source for the newest Ubuntu image, variables and outputs, update in place vs replace (and prevent_destroy, create_before_destroy), drift, remote state in S3 with locking, and terraform destroy.

Terraform: Full Tutorial for Beginners, the full picture: diagram of Your.tf files, Terraform, State file, AWS provider, Shared state, S3 bucket, Security group, EC2 server, AWS, us-east-1
The whole picture, from the video's recap.

One line, one server

You changed one line of Terraform, and its plan says it will destroy your web server. In this tutorial, you'll learn to catch that, and swap servers safely.

one changed line
terraform plandata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 0s [id=ami-02fffd5f990bcc920]
aws_instance.web: Refreshing state... [id=i-0e180bd0282b39e8a]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_instance.web must be replaced
-/+ resource "aws_instance" "web" {
      ~ ami                                  = "ami-0b9493369813fed42" -> "ami-02fffd5f990bcc920" # forces replacement
      ~ arn                                  = "arn:aws:ec2:us-east-1:346882411366:instance/i-0e180bd0282b39e8a" -> (known after apply)
      ~ associate_public_ip_address          = true -> (known after apply)
      ~ availability_zone                    = "us-east-1c" -> (known after apply)
      ~ disable_api_stop                     = false -> (known after apply)
      ~ disable_api_termination              = false -> (known after apply)
      ~ ebs_optimized                        = false -> (known after apply)
      + enable_primary_ipv6                  = (known after apply)
      - hibernation                          = false -> null
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      ~ id                                   = "i-0e180bd0282b39e8a" -> (known after apply)
      ~ instance_initiated_shutdown_behavior = "stop" -> (known after apply)
      + instance_lifecycle                   = (known after apply)
      ~ instance_state                       = "running" -> (known after apply)
      ~ ipv6_address_count                   = 0 -> (known after apply)
      ~ ipv6_addresses                       = [] -> (known after apply)
      + key_name                             = (known after apply)
      ~ monitoring                           = false -> (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_group_id                   = (known after apply)
      ~ placement_partition_number           = 0 -> (known after apply)
      ~ primary_network_interface_id         = "eni-0e6df94b05eb9ce79" -> (known after apply)
      ~ private_dns                          = "ip-172-31-17-104.ec2.internal" -> (known after apply)
      ~ private_ip                           = "172.31.17.104" -> (known after apply)
      ~ public_dns                           = "ec2-54-172-142-44.compute-1.amazonaws.com" -> (known after apply)
      ~ public_ip                            = "54.172.142.44" -> (known after apply)
      ~ secondary_private_ips                = [] -> (known after apply)
      ~ security_groups                      = [
          - "piano-web",
        ] -> (known after apply)
      + spot_instance_request_id             = (known after apply)
      ~ subnet_id                            = "subnet-04e02fb01624522da" -> (known after apply)
        tags                                 = {
            "Name" = "piano-web"
        }
      ~ tenancy                              = "default" -> (known after apply)
      + user_data_base64                     = (known after apply)
        # (9 unchanged attributes hidden)

      ~ capacity_reservation_specification (known after apply)
      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> null
        }

      ~ cpu_options (known after apply)
      - cpu_options {
          - core_count            = 1 -> null
          - threads_per_core      = 2 -> null
            # (2 unchanged attributes hidden)
        }

      - credit_specification {
          - cpu_credits = "unlimited" -> null
        }

      ~ ebs_block_device (known after apply)

      ~ enclave_options (known after apply)
      - enclave_options {
          - enabled = false -> null
        }

      ~ ephemeral_block_device (known after apply)

      ~ instance_market_options (known after apply)

      ~ maintenance_options (known after apply)
      - maintenance_options {
          - auto_recovery = "default" -> null
        }

      ~ metadata_options (known after apply)
      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_protocol_ipv6          = "disabled" -> null
          - http_put_response_hop_limit = 2 -> null
          - http_tokens                 = "required" -> null
          - instance_metadata_tags      = "disabled" -> null
        }

      ~ network_interface (known after apply)

      ~ primary_network_interface (known after apply)
      - primary_network_interface {
          - delete_on_termination = true -> null
          - network_interface_id  = "eni-0e6df94b05eb9ce79" -> null
        }

      ~ private_dns_name_options (known after apply)
      - private_dns_name_options {
          - enable_resource_name_dns_a_record    = false -> null
          - enable_resource_name_dns_aaaa_record = false -> null
          - hostname_type                        = "ip-name" -> null
        }

      ~ root_block_device (known after apply)
      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/sda1" -> null
          - encrypted             = false -> null
          - iops                  = 3000 -> null
          - tags                  = {} -> null
          - tags_all              = {} -> null
          - throughput            = 125 -> null
          - volume_id             = "vol-09342b65be3603300" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp3" -> null
            # (1 unchanged attribute hidden)
        }

      ~ secondary_network_interface (known after apply)
    }

Plan: 1 to add, 0 to change, 1 to destroy.

Changes to Outputs:
  ~ url = "http://54.172.142.44" -> (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.

Was Terraform wrong, or was it right? By the end, you'll know exactly why one line can mean a whole new server.

The one line: code change of web.tf, values = ["ubuntu/images/*/ubuntu-resolute-26.04-amd64-server-*"] (24.04 to 26.04), Wrong, or right? You'll see

Today you'll build this page on a real AWS server, from an empty folder, then change it, share it, and delete it, with Terraform.

One line, one server: browser screenshot from the video

Why Terraform

Terraform is infrastructure as code. You describe the servers and firewalls you want in text files; Terraform makes the cloud match them, and the files live in Git.

Clicking vs code: comparison table of Clicking in the console vs Terraform files, The settings, Where they live, Making it match, History and reviews

Here's why that matters for that lesson page. Ben teaches piano, and students book lessons on it. Ana set up its server by clicking through the AWS console: dozens of settings, written down nowhere. If it breaks, nobody can build it again the same way. With Terraform, the same files build it again, in another region, or for a second studio.

Ben's piano lessons: diagram of booked online, clicked by hand, written nowhere

Here's the whole picture. Your files say what you want. Terraform reads them, and a plugin called a provider turns them into AWS requests. AWS builds the real things, and Terraform writes down what it built in a state file.

Providers are also why Terraform isn't only for AWS. The AWS one alone has been downloaded almost nine billion times, and there are others for Azure, Google Cloud and Kubernetes, all with the same plan and apply.

One tool, many providers: diagram of Terraform, AWS, Azure, Google Cloud, Kubernetes

Think of a builder with a blueprint. You draw the blueprint. The builder checks it against the building and their own notes, tells you exactly what they'll build, change or knock down, and waits for your yes.

Every Terraform project runs the same few commands. Write the files. terraform init gets the provider. terraform plan shows what would change. terraform apply makes it real. And terraform destroy removes it all. You'll run each one in the next few minutes, on a real AWS account.

The Terraform loop: diagram of Write, init, plan, apply, destroy

Install Terraform

First, install it. On Ubuntu, HashiCorp's install page gives you two lines that add their package list; they're linked below. Then one command: sudo apt install terraform. Terraform is one program, written in Go, about 34 megabytes to download.

Ben's laptop: ~/piano-site
sudo apt install -y terraformReading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  terraform
0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded.
Need to get 33.9 MB of archives.
After this operation, 119 MB of additional disk space will be used.
Get:1 https://apt.releases.hashicorp.com noble/main arm64 terraform arm64 1.17.2-1 [33.9 MB]
Fetched 33.9 MB in 1s (63.7 MB/s)
debconf: delaying package configuration, since apt-utils is not installed

Selecting previously unselected package terraform.
(Reading database ... 8485 files and directories currently installed.)
Preparing to unpack .../terraform_1.17.2-1_arm64.deb ...
Unpacking terraform (1.17.2-1) ...
Setting up terraform (1.17.2-1) ...

terraform dash version checks it: version 1 point 17 point 2, on Linux for ARM.

The same page covers a Mac, with Homebrew, and Windows, with a download. Every command after this works the same on all three. And if your output ever looks different, check the versions first.

Install it anywhere: cards of Linux, macOS, Windows, Same commands, Output looks different?, Check the versions

Your first resource

Make a folder for the project, and in it, in any text editor, a file called main dot T F. Terraform reads every file ending in dot T F in that folder. This one has three blocks. The first names the provider we need: hashicorp slash aws, version six. The second sets the AWS region: us-east-1, in Northern Virginia. The third is the thing we want: a storage bucket in S3, for the students' sheet music.

Ben's laptop: ~/piano-site
mkdir piano-site && cd piano-site
Ben's laptop: ~/piano-site
cat main.tfterraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "sheets" {
  bucket = "sheetmusic"
}

Read a resource block like this. resource means: build something. Next, the type: an AWS S3 bucket. Then your own name for it, sheets, used only inside Terraform. The braces hold its settings.

A resource block: diagram of resource "aws_s3_bucket" "sheets" {, resource = build something, "aws_s3_bucket" = the type, "sheets" = your name for it, { = its settings, Its address: aws_s3_bucket.sheets

Terraform's language is HCL, with just a few rules. A block starts with its type and a name or two, then curly braces. Inside, each setting is a name, an equals sign, and a value. Text goes in quotes, numbers don't, and a hash sign starts a comment.

Before init, take a guess: will terraform plan work? No. It stops at once, with an error about a lock file: a file that init creates, and you haven't run init yet. It hasn't downloaded the AWS provider either, and the error ends with the fix: terraform init. Read Terraform's errors to the end; they often say what to run.

Ben's laptop: ~/piano-site
terraform plan╷
│ 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/aws: 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
╵

terraform init finds the newest AWS provider that fits version six, here 6 point 74 point 0, and downloads it into a hidden folder, dot terraform. It also writes a lock file with that exact version. Keep the lock file in Git, so everyone on the team gets the same provider.

Ben's laptop: ~/piano-site
terraform initInitializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 6.0"...
- Installing hashicorp/aws v6.74.0...
- Installed hashicorp/aws v6.74.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.
Ben's laptop: ~/piano-site
ls -a.  ..  .terraform  .terraform.lock.hcl  main.tf

About that version line. The tilde and arrow mean: any version six point something, 6 point 74 point 0 today, but never seven. A new major version can change how things work, so you move to it on purpose, not by accident.

version = "~> 6.0": diagram of 6.0, 6.74.0, 7.0

How does Terraform log in to AWS? You'll need three things first: an AWS account, the AWS command line, and an access key. The steps for each are linked below. Run aws configure once and paste the key in; it's saved in your home folder, in dot aws slash credentials. The provider reads it from there and signs every request, so keys never go in your dot T F files.

How Terraform signs in to AWS: diagram of AWS account, aws configure, ~/.aws/credentials, AWS provider, AWS

Now terraform plan works. The plus sign means create. Known after apply means AWS will decide that value, like the bucket's address. Then read the last line first: one to add, zero to change, zero to destroy. You set one argument; the other twenty lines are the provider's defaults and values AWS fills in. And plan on its own never changes anything; only apply changes anything in AWS.

Ben's laptop: ~/piano-site
terraform planTerraform 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:

  # aws_s3_bucket.sheets will be created
  + resource "aws_s3_bucket" "sheets" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "sheetmusic"
      + bucket_domain_name          = (known after apply)
      + bucket_namespace            = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_region               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = "us-east-1"
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)

      + cors_rule (known after apply)

      + grant (known after apply)

      + lifecycle_rule (known after apply)

      + logging (known after apply)

      + object_lock_configuration (known after apply)

      + replication_configuration (known after apply)

      + server_side_encryption_configuration (known after apply)

      + versioning (known after apply)

      + website (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

───────────────────────────────────────────────────────────────────────────────

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.

terraform apply shows the same plan and asks for a yes. Type yes, and AWS refuses: bucket already exists. Bucket names are shared by every AWS account in the world, and someone already owns sheetmusic. Every bucket gets its own web address, so no two can share a name.

Ben's laptop: ~/piano-site
terraform applyTerraform 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:

  # aws_s3_bucket.sheets will be created
  + resource "aws_s3_bucket" "sheets" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "sheetmusic"
      + bucket_domain_name          = (known after apply)
      + bucket_namespace            = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_region               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = "us-east-1"
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)

      + cors_rule (known after apply)

      + grant (known after apply)

      + lifecycle_rule (known after apply)

      + logging (known after apply)

      + object_lock_configuration (known after apply)

      + replication_configuration (known after apply)

      + server_side_encryption_configuration (known after apply)

      + versioning (known after apply)

      + website (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_s3_bucket.sheets: Creating...
╷
│ Error: creating S3 Bucket (sheetmusic): operation error S3: CreateBucket, https response error StatusCode: 409, RequestID: TY48RPDKQNWKQMRG, HostID: zD9YEiQ5do8TSfFUF1PbZfgDXF9SlJRe5BzYb5r/E7o8rqMRK5FytDvmawqgcy9jobiIwbjt2VgSXgA0N4oROqwyc4IuuHKE, BucketAlreadyExists: The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.
│
│   with aws_s3_bucket.sheets,
│   on main.tf line 14, in resource "aws_s3_bucket" "sheets":
│   14: resource "aws_s3_bucket" "sheets" {
│
╵

Amazon's own rules say so: one namespace, shared by everyone.

The fix is one word. Swap bucket for bucket prefix, and Terraform adds a unique ending to the name for you.

Let Terraform finish the name: code change of main.tf, bucket_prefix = "sheetmusic-" (a unique ending), Terraform finishes the name

Apply again, yes, and 1 second later: creation complete, with its real name, sheetmusic and a long random ending. Apply complete: one added. That's a real bucket in AWS, made from a text file, and you never opened the console.

Ben's laptop: ~/piano-site
terraform applyTerraform 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:

  # aws_s3_bucket.sheets will be created
  + resource "aws_s3_bucket" "sheets" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = (known after apply)
      + bucket_domain_name          = (known after apply)
      + bucket_namespace            = (known after apply)
      + bucket_prefix               = "sheetmusic-"
      + bucket_region               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = "us-east-1"
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)

      + cors_rule (known after apply)

      + grant (known after apply)

      + lifecycle_rule (known after apply)

      + logging (known after apply)

      + object_lock_configuration (known after apply)

      + replication_configuration (known after apply)

      + server_side_encryption_configuration (known after apply)

      + versioning (known after apply)

      + website (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_s3_bucket.sheets: Creating...
aws_s3_bucket.sheets: Creation complete after 1s [id=sheetmusic-aaeb994ed2623c75fa005636c6]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state file

Now, take a guess. You run terraform apply again, with nothing changed. Does it make a second bucket? No. No changes: Terraform remembered that bucket, checked it in AWS, saw it still matches your file, and did nothing. But how did it remember?

Ben's laptop: ~/piano-site
terraform applyaws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and
found no differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

After every apply, Terraform writes down what it built in a file called terraform dot T F state. It's JSON: the Terraform version, and a list of resources. terraform state list shows the one entry, the bucket. Its address is the type, a dot, and your name for it.

Ben's laptop: ~/piano-site
lsmain.tf  terraform.tfstate  terraform.tfstate.backup
Ben's laptop: ~/piano-site
head -n 16 terraform.tfstate{
  "version": 4,
  "terraform_version": "1.17.2",
  "serial": 4,
  "lineage": "ef56721d-ee3a-eead-9798-413ba70ce99d",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_s3_bucket",
      "name": "sheets",
      "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
Ben's laptop: ~/piano-site
terraform state listaws_s3_bucket.sheets

That record is how Terraform maps sheets, the name in your file, to one real bucket in AWS. Never edit it by hand, and keep it out of Git; it can hold secrets, like database passwords.

HashiCorp's own docs start there: Terraform must store state.

And if the state file is lost? Terraform forgets what it built. The bucket is still there in AWS, still on your bill, but the next plan would try to create everything again. That's why, later, the state moves somewhere safer than one laptop.

No state: Terraform forgets: diagram of main.tf, State file, Terraform, The real bucket, A second bucket?

A real web server

Now the real thing: the lesson page, on a server. It takes three new pieces. A data source, which looks up the newest Ubuntu image: the ready-made copy of an operating system that a new server starts from. A security group: AWS's firewall, letting web traffic in. And the server itself, an EC2 instance.

In a new file, web dot T F, the data block asks AWS for the most recent AMI, an Amazon Machine Image, named Ubuntu 24.04, owned by Canonical, the company behind Ubuntu. Data sources only read. They never create anything.

web.tf: look up an image: code change of web.tf, data "aws_ami" "ubuntu" { (a data block), most_recent = true (the newest), values = ["ubuntu/images/*/ubuntu-noble-24.04-amd64-server-*"] (Ubuntu 24.04)

You didn't write a network, and you don't need to yet. Every AWS account comes with a ready-made network in each region, the default VPC, a Virtual Private Cloud, and your server lands there, with a public address. Real projects build their own.

Where the server lands: diagram of Region: us-east-1, Default VPC, A default subnet, Your server

The security group is the server's firewall. Its ingress rule, for incoming traffic, lets web traffic in on port eighty, from the whole internet, and everything else stays out. Its egress rule, for outgoing traffic, lets the server reach out to anywhere, to download updates.

web.tf: the security group: diagram of The internet, Security group, EC2 server

And the server: an aws instance resource. Its image is the data block's result. Its firewall is the security group's id. References like these tell Terraform what depends on what. And user data hands the server a startup script: Terraform's file function reads it in from web dot S H.

web.tf: the server: code change of web.tf, ami = data.aws_ami.ubuntu.id (the data block's result), vpc_security_group_ids = [aws_security_group.web.id] (the group's id), user_data = file("web.sh") (web.sh, on first boot)

That startup script is web dot S H, in the same folder. On the first boot, it writes the lesson page. Then it sets up a systemd service, a small program that runs in the background. It serves the page with Python on port eighty, and starts again after every restart. That detail matters later.

web.sh, on the first boot: diagram of First boot, web.sh, systemd, run user data, index.html, a systemd service, port 80, enabled, after a restart, systemd: runs programs in the background

The server's size shouldn't be buried in web dot T F, so it comes from a variable, in variables dot T F: type string, default t3 micro, AWS's name for a small, low-cost server size. web dot T F reads it as var dot instance type. And outputs dot T F prints the server's address after every apply, so you never dig through the console for it.

Ben's laptop: ~/piano-site
cat variables.tfvariable "instance_type" {
  description = "Size of the web server"
  type        = string
  default     = "t3.micro"
}
Ben's laptop: ~/piano-site
cat outputs.tfoutput "url" {
  value = "http://${aws_instance.web.public_ip}"
}

Before you plan, terraform validate checks the files. Here it caught a typo: an argument named instance typ, spelled T Y P, and it even asks: did you mean instance type? Fixed, it says success. validate needs init first, because it checks your arguments against the provider's own list. And terraform fmt lines everything up the standard way. Run both before every plan; they're fast and catch silly mistakes.

Ben's laptop: ~/piano-site
terraform validate╷
│ Error: Unsupported argument
│
│   on web.tf line 31, in resource "aws_instance" "web":
│   31:   instance_typ           = var.instance_type
│
│ An argument named "instance_typ" is not expected here. Did you mean
│ "instance_type"?
╵
Ben's laptop: ~/piano-site
terraform validateSuccess! The configuration is valid.
Ben's laptop: ~/piano-site
terraform fmt

The plan reads the image first: the newest Ubuntu 24.04, ami zero b nine four and so on. Then two to add: the security group and the server. And one new output, the url, known after apply, because the address doesn't exist until AWS starts the server.

Ben's laptop: ~/piano-site
terraform plandata.aws_ami.ubuntu: Reading...
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 1s [id=ami-0b9493369813fed42]

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:

  # aws_instance.web will be created
  + resource "aws_instance" "web" {
      + ami                                  = "ami-0b9493369813fed42"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + enable_primary_ipv6                  = (known after apply)
      + force_destroy                        = false
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_lifecycle                   = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t3.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_group_id                   = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + region                               = "us-east-1"
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + spot_instance_request_id             = (known after apply)
      + subnet_id                            = (known after apply)
      + tags                                 = {
          + "Name" = "piano-web"
        }
      + tags_all                             = {
          + "Name" = "piano-web"
        }
      + tenancy                              = (known after apply)
      + user_data                            = <<-EOT
            #!/bin/bash
            mkdir -p /srv/site && cd /srv/site
            cat > index.html <<'HTML'
            <!doctype html>
            <html><head><meta charset="utf-8"><title>Piano lessons with Ben</title>
            <style>
            body{font-family:Georgia,serif;background:#fbf7ef;color:#2b2118;margin:0;padding:64px 80px}
            h1{font-size:56px;margin:0 0 12px} p{font-size:26px;margin:8px 0}
            .slots{margin-top:28px;display:flex;gap:18px}
            .slot{background:#fff;border:2px solid #2b2118;border-radius:12px;padding:16px 22px;font-size:24px}
            small{display:block;margin-top:36px;font-family:monospace;font-size:20px;color:#6b5a48}
            </style></head><body>
            <h1>Piano lessons with Ben</h1>
            <p>Beginners welcome. Book a 30-minute lesson.</p>
            <div class="slots"><div class="slot">Tue 4:00 pm</div><div class="slot">Tue 5:00 pm</div><div class="slot">Thu 4:30 pm</div></div>
            <small>served from SERVER_ID</small>
            </body></html>
            HTML
            sed -i "s/SERVER_ID/$(cloud-init query ds.meta_data.instance_id)/" index.html
            cat > /etc/systemd/system/site.service <<'UNIT'
            [Unit]
            Description=Piano lessons page
            After=network-online.target

            [Service]
            WorkingDirectory=/srv/site
            ExecStart=/usr/bin/python3 -m http.server 80

            [Install]
            WantedBy=multi-user.target
            UNIT
            systemctl enable --now site.service
        EOT
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)

      + capacity_reservation_specification (known after apply)

      + cpu_options (known after apply)

      + ebs_block_device (known after apply)

      + enclave_options (known after apply)

      + ephemeral_block_device (known after apply)

      + instance_market_options (known after apply)

      + maintenance_options (known after apply)

      + metadata_options (known after apply)

      + network_interface (known after apply)

      + primary_network_interface (known after apply)

      + private_dns_name_options (known after apply)

      + root_block_device (known after apply)

      + secondary_network_interface (known after apply)
    }

  # aws_security_group.web will be created
  + resource "aws_security_group" "web" {
      + arn                    = (known after apply)
      + description            = "Managed by Terraform"
      + egress                 = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + from_port        = 0
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "-1"
              + security_groups  = []
              + self             = false
              + to_port          = 0
                # (1 unchanged attribute hidden)
            },
        ]
      + id                     = (known after apply)
      + ingress                = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + from_port        = 80
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "tcp"
              + security_groups  = []
              + self             = false
              + to_port          = 80
                # (1 unchanged attribute hidden)
            },
        ]
      + name                   = "piano-web"
      + name_prefix            = (known after apply)
      + owner_id               = (known after apply)
      + region                 = "us-east-1"
      + revoke_rules_on_delete = false
      + tags_all               = (known after apply)
      + vpc_id                 = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + url = (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.

Apply, yes, and watch the order. The security group comes first, in 3 seconds, because the server needs its id. Then the server: still creating at ten seconds, done at 13. And the output: the server's public address.

Ben's laptop: ~/piano-site
terraform applydata.aws_ami.ubuntu: Reading...
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 1s [id=ami-0b9493369813fed42]

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:

  # aws_instance.web will be created
  + resource "aws_instance" "web" {
      + ami                                  = "ami-0b9493369813fed42"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + enable_primary_ipv6                  = (known after apply)
      + force_destroy                        = false
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_lifecycle                   = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t3.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_group_id                   = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + region                               = "us-east-1"
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + spot_instance_request_id             = (known after apply)
      + subnet_id                            = (known after apply)
      + tags                                 = {
          + "Name" = "piano-web"
        }
      + tags_all                             = {
          + "Name" = "piano-web"
        }
      + tenancy                              = (known after apply)
      + user_data                            = <<-EOT
            #!/bin/bash
            mkdir -p /srv/site && cd /srv/site
            cat > index.html <<'HTML'
            <!doctype html>
            <html><head><meta charset="utf-8"><title>Piano lessons with Ben</title>
            <style>
            body{font-family:Georgia,serif;background:#fbf7ef;color:#2b2118;margin:0;padding:64px 80px}
            h1{font-size:56px;margin:0 0 12px} p{font-size:26px;margin:8px 0}
            .slots{margin-top:28px;display:flex;gap:18px}
            .slot{background:#fff;border:2px solid #2b2118;border-radius:12px;padding:16px 22px;font-size:24px}
            small{display:block;margin-top:36px;font-family:monospace;font-size:20px;color:#6b5a48}
            </style></head><body>
            <h1>Piano lessons with Ben</h1>
            <p>Beginners welcome. Book a 30-minute lesson.</p>
            <div class="slots"><div class="slot">Tue 4:00 pm</div><div class="slot">Tue 5:00 pm</div><div class="slot">Thu 4:30 pm</div></div>
            <small>served from SERVER_ID</small>
            </body></html>
            HTML
            sed -i "s/SERVER_ID/$(cloud-init query ds.meta_data.instance_id)/" index.html
            cat > /etc/systemd/system/site.service <<'UNIT'
            [Unit]
            Description=Piano lessons page
            After=network-online.target

            [Service]
            WorkingDirectory=/srv/site
            ExecStart=/usr/bin/python3 -m http.server 80

            [Install]
            WantedBy=multi-user.target
            UNIT
            systemctl enable --now site.service
        EOT
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)

      + capacity_reservation_specification (known after apply)

      + cpu_options (known after apply)

      + ebs_block_device (known after apply)

      + enclave_options (known after apply)

      + ephemeral_block_device (known after apply)

      + instance_market_options (known after apply)

      + maintenance_options (known after apply)

      + metadata_options (known after apply)

      + network_interface (known after apply)

      + primary_network_interface (known after apply)

      + private_dns_name_options (known after apply)

      + root_block_device (known after apply)

      + secondary_network_interface (known after apply)
    }

  # aws_security_group.web will be created
  + resource "aws_security_group" "web" {
      + arn                    = (known after apply)
      + description            = "Managed by Terraform"
      + egress                 = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + from_port        = 0
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "-1"
              + security_groups  = []
              + self             = false
              + to_port          = 0
                # (1 unchanged attribute hidden)
            },
        ]
      + id                     = (known after apply)
      + ingress                = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + from_port        = 80
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "tcp"
              + security_groups  = []
              + self             = false
              + to_port          = 80
                # (1 unchanged attribute hidden)
            },
        ]
      + name                   = "piano-web"
      + name_prefix            = (known after apply)
      + owner_id               = (known after apply)
      + region                 = "us-east-1"
      + revoke_rules_on_delete = false
      + tags_all               = (known after apply)
      + vpc_id                 = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + url = (known after apply)

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_security_group.web: Creating...
aws_security_group.web: Creation complete after 3s [id=sg-0b43c99b2ba1907b6]
aws_instance.web: Creating...
aws_instance.web: Still creating... [00m10s elapsed]
aws_instance.web: Creation complete after 13s [id=i-0e180bd0282b39e8a]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

url = "http://54.172.142.44"

How did Terraform know that order? From the references. The server points at the image and at the security group, so both come first. The bucket points at nothing, so it doesn't have to wait. On a fresh build, Terraform would make it alongside the rest, up to ten things at once. Write the references, and the order takes care of itself.

References decide the order: diagram of data.aws_ami.ubuntu, aws_security_group.web, aws_instance.web, aws_s3_bucket.sheets

The server needs a moment to boot and run its script; here it answered after about 10 seconds. terraform output prints the address again, and curl fetches it: the lesson page, from the new server. From an empty folder to a live page took two applies.

Ben's laptop: ~/piano-site
terraform outputurl = "http://54.172.142.44"
Ben's laptop: ~/piano-site
curl -s http://54.172.142.44 | head -n 12<!doctype html>
<html><head><meta charset="utf-8"><title>Piano lessons with Ben</title>
<style>
body{font-family:Georgia,serif;background:#fbf7ef;color:#2b2118;margin:0;padding:64px 80px}
h1{font-size:56px;margin:0 0 12px} p{font-size:26px;margin:8px 0}
.slots{margin-top:28px;display:flex;gap:18px}
.slot{background:#fff;border:2px solid #2b2118;border-radius:12px;padding:16px 22px;font-size:24px}
small{display:block;margin-top:36px;font-family:monospace;font-size:20px;color:#6b5a48}
</style></head><body>
<h1>Piano lessons with Ben</h1>
<p>Beginners welcome. Book a 30-minute lesson.</p>
<div class="slots"><div class="slot">Tue 4:00 pm</div><div class="slot">Tue 5:00 pm</div><div class="slot">Thu 4:30 pm</div></div>

In a browser, it's the same: piano lessons, with three times to book, served from this exact server.

A real web server: browser screenshot from the video

While it runs, it costs money: about a cent an hour for this t3 micro, plus half a cent for its public address.

What the server costs: figure of 0.01 an hour t3.micro, Linux, us-east-1, source: AWS EC2 on-demand pricing (Price List API, 2026-12-01); Amazon VPC pricing

Check the state again: four entries now. The bucket, the security group, the server, and even the data source's answer, the image it found, so the next plan can tell what changed.

Ben's laptop: ~/piano-site
terraform state listdata.aws_ami.ubuntu
aws_instance.web
aws_s3_bucket.sheets
aws_security_group.web

Variables and outputs

The lessons are busy, and a bigger server would help, without editing web dot T F. That instance type variable can be set three ways. Leave the default. Put it in terraform dot T F vars, which Terraform reads by itself. Or pass dash var, for a one-off. Your team sees the file, not your command line.

Three ways to set instance_type: diagram of The default, terraform.tfvars, -var on the command line, var.instance_type, web.tf

Say the lessons get busy, and you want a bigger server, t3 small. Will Terraform update this server, or build a new one? It updates it in place: the tilde. Only the size changes, micro to small, one to change, nothing destroyed.

Ben's laptop: ~/piano-site
terraform plan -var instance_type=t3.smalldata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 0s [id=ami-0b9493369813fed42]
aws_instance.web: Refreshing state... [id=i-0e180bd0282b39e8a]

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:

  # aws_instance.web will be updated in-place
  ~ resource "aws_instance" "web" {
        id                                   = "i-0e180bd0282b39e8a"
      ~ instance_type                        = "t3.micro" -> "t3.small"
      ~ public_dns                           = "ec2-54-172-142-44.compute-1.amazonaws.com" -> (known after apply)
      ~ public_ip                            = "54.172.142.44" -> (known after apply)
        tags                                 = {
            "Name" = "piano-web"
        }
        # (38 unchanged attributes hidden)

        # (9 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Changes to Outputs:
  ~ url = "http://54.172.142.44" -> (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 one plan line like this. The tilde says update. Then the argument, instance type. On the left, what AWS has now. After the arrow, what it will be.

One plan line: diagram of ~ instance_type = "t3.micro" -> "t3.small", ~ = update in place, instance_type = the argument, "t3.micro" = now, "t3.small" = after apply, symbol, argument, now -> after

The provider's docs say what in place means here: AWS stops the server, resizes it, and starts it again.

Notice the note under every plan: you didn't use the dash out option. Between your plan and your apply, things can change. So save the plan to a file, with terraform plan dash out and a name, like plan dot out. Then terraform apply plan dot out does exactly what you read, nothing else. We won't apply this one yet. The server stays a t3 micro for now; it gets bigger later, as a team.

Update or replace

Now the line from the start. Ubuntu 26.04 is out, so you change noble, 24.04, to resolute, 26.04. It looks as small as the size change.

Upgrade Ubuntu: one line: code change of web.tf, values = ["ubuntu/images/*/ubuntu-resolute-26.04-amd64-server-*"] (noble to resolute), Looks small. It isn't.

It isn't. The plan: minus slash plus, must be replaced. A running server can't swap its image, so the ami line says forces replacement. One to add, one to destroy. Anything saved on that server's disk would go with it.

Four symbols cover almost every plan. Plus: create. Tilde: update in place. Minus slash plus: replace, destroy then create. And minus: destroy. Like a builder marking what comes down: find the minuses first.

Read the symbols before you say yes: cards of +, ~, -/+, -, Before every yes, Before every yes: find the minuses

This can also happen without you touching a line. most recent equals true asks for the newest image every time you plan. When Canonical publishes a fresh 24.04 image, the next plan wants to replace your server. Once a server is live, pin the image id you tested.

most_recent = true: a quiet replacement: diagram of Canonical, data.aws_ami, Your server, most_recent = true, the newest 24.04, a fresh image, ami changes, pin the tested id, No line changed

To stop this happening by accident, add a lifecycle block inside the server's resource, with prevent destroy. Now the same plan stops with an error: instance cannot be destroyed. That's its whole job: reject any plan that would destroy the server.

Ben's laptop: ~/piano-site
terraform plandata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 1s [id=ami-02fffd5f990bcc920]
aws_instance.web: Refreshing state... [id=i-0e180bd0282b39e8a]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform planned the following actions, but then encountered a problem:

  # aws_instance.web must be replaced
-/+ resource "aws_instance" "web" {
      ~ ami                                  = "ami-0b9493369813fed42" -> "ami-02fffd5f990bcc920" # forces replacement
      ~ arn                                  = "arn:aws:ec2:us-east-1:346882411366:instance/i-0e180bd0282b39e8a" -> (known after apply)
      ~ associate_public_ip_address          = true -> (known after apply)
      ~ availability_zone                    = "us-east-1c" -> (known after apply)
      ~ disable_api_stop                     = false -> (known after apply)
      ~ disable_api_termination              = false -> (known after apply)
      ~ ebs_optimized                        = false -> (known after apply)
      + enable_primary_ipv6                  = (known after apply)
      - hibernation                          = false -> null
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      ~ id                                   = "i-0e180bd0282b39e8a" -> (known after apply)
      ~ instance_initiated_shutdown_behavior = "stop" -> (known after apply)
      + instance_lifecycle                   = (known after apply)
      ~ instance_state                       = "running" -> (known after apply)
      ~ ipv6_address_count                   = 0 -> (known after apply)
      ~ ipv6_addresses                       = [] -> (known after apply)
      + key_name                             = (known after apply)
      ~ monitoring                           = false -> (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_group_id                   = (known after apply)
      ~ placement_partition_number           = 0 -> (known after apply)
      ~ primary_network_interface_id         = "eni-0e6df94b05eb9ce79" -> (known after apply)
      ~ private_dns                          = "ip-172-31-17-104.ec2.internal" -> (known after apply)
      ~ private_ip                           = "172.31.17.104" -> (known after apply)
      ~ public_dns                           = "ec2-54-172-142-44.compute-1.amazonaws.com" -> (known after apply)
      ~ public_ip                            = "54.172.142.44" -> (known after apply)
      ~ secondary_private_ips                = [] -> (known after apply)
      ~ security_groups                      = [
          - "piano-web",
        ] -> (known after apply)
      + spot_instance_request_id             = (known after apply)
      ~ subnet_id                            = "subnet-04e02fb01624522da" -> (known after apply)
        tags                                 = {
            "Name" = "piano-web"
        }
      ~ tenancy                              = "default" -> (known after apply)
      + user_data_base64                     = (known after apply)
        # (9 unchanged attributes hidden)

      ~ capacity_reservation_specification (known after apply)
      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> null
        }

      ~ cpu_options (known after apply)
      - cpu_options {
          - core_count            = 1 -> null
          - threads_per_core      = 2 -> null
            # (2 unchanged attributes hidden)
        }

      - credit_specification {
          - cpu_credits = "unlimited" -> null
        }

      ~ ebs_block_device (known after apply)

      ~ enclave_options (known after apply)
      - enclave_options {
          - enabled = false -> null
        }

      ~ ephemeral_block_device (known after apply)

      ~ instance_market_options (known after apply)

      ~ maintenance_options (known after apply)
      - maintenance_options {
          - auto_recovery = "default" -> null
        }

      ~ metadata_options (known after apply)
      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_protocol_ipv6          = "disabled" -> null
          - http_put_response_hop_limit = 2 -> null
          - http_tokens                 = "required" -> null
          - instance_metadata_tags      = "disabled" -> null
        }

      ~ network_interface (known after apply)

      ~ primary_network_interface (known after apply)
      - primary_network_interface {
          - delete_on_termination = true -> null
          - network_interface_id  = "eni-0e6df94b05eb9ce79" -> null
        }

      ~ private_dns_name_options (known after apply)
      - private_dns_name_options {
          - enable_resource_name_dns_a_record    = false -> null
          - enable_resource_name_dns_aaaa_record = false -> null
          - hostname_type                        = "ip-name" -> null
        }

      ~ root_block_device (known after apply)
      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/sda1" -> null
          - encrypted             = false -> null
          - iops                  = 3000 -> null
          - tags                  = {} -> null
          - tags_all              = {} -> null
          - throughput            = 125 -> null
          - volume_id             = "vol-09342b65be3603300" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp3" -> null
            # (1 unchanged attribute hidden)
        }

      ~ secondary_network_interface (known after apply)
    }

Plan: 1 to add, 0 to change, 1 to destroy.
╷
│ Error: Instance cannot be destroyed
│
│   on web.tf line 29:
│   29: resource "aws_instance" "web" {
│
│ Resource aws_instance.web has lifecycle.prevent_destroy set, but the plan
│ calls for this resource to be destroyed. To avoid this error and continue
│ with the plan, either disable lifecycle.prevent_destroy or reduce the scope
│ of the plan using the -target option.
╵

Here, though, you want the upgrade, and nothing's stored on that disk. So swap prevent destroy for create before destroy: the new server comes first.

New server first: code change of web.tf, create_before_destroy = true (create before destroy), You want this upgrade

Apply. The new server is ready in 13 seconds, and only then does the old one go, in 20. One added, one destroyed. But look at the url: a new address. A new server gets a new public IP, which is why real sites put a fixed address in front.

Ben's laptop: ~/piano-site
terraform applydata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 0s [id=ami-02fffd5f990bcc920]
aws_instance.web: Refreshing state... [id=i-0e180bd0282b39e8a]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
+/- create replacement and then destroy

Terraform will perform the following actions:

  # aws_instance.web must be replaced
+/- resource "aws_instance" "web" {
      ~ ami                                  = "ami-0b9493369813fed42" -> "ami-02fffd5f990bcc920" # forces replacement
      ~ arn                                  = "arn:aws:ec2:us-east-1:346882411366:instance/i-0e180bd0282b39e8a" -> (known after apply)
      ~ associate_public_ip_address          = true -> (known after apply)
      ~ availability_zone                    = "us-east-1c" -> (known after apply)
      ~ disable_api_stop                     = false -> (known after apply)
      ~ disable_api_termination              = false -> (known after apply)
      ~ ebs_optimized                        = false -> (known after apply)
      + enable_primary_ipv6                  = (known after apply)
      - hibernation                          = false -> null
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      ~ id                                   = "i-0e180bd0282b39e8a" -> (known after apply)
      ~ instance_initiated_shutdown_behavior = "stop" -> (known after apply)
      + instance_lifecycle                   = (known after apply)
      ~ instance_state                       = "running" -> (known after apply)
      ~ ipv6_address_count                   = 0 -> (known after apply)
      ~ ipv6_addresses                       = [] -> (known after apply)
      + key_name                             = (known after apply)
      ~ monitoring                           = false -> (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_group_id                   = (known after apply)
      ~ placement_partition_number           = 0 -> (known after apply)
      ~ primary_network_interface_id         = "eni-0e6df94b05eb9ce79" -> (known after apply)
      ~ private_dns                          = "ip-172-31-17-104.ec2.internal" -> (known after apply)
      ~ private_ip                           = "172.31.17.104" -> (known after apply)
      ~ public_dns                           = "ec2-54-172-142-44.compute-1.amazonaws.com" -> (known after apply)
      ~ public_ip                            = "54.172.142.44" -> (known after apply)
      ~ secondary_private_ips                = [] -> (known after apply)
      ~ security_groups                      = [
          - "piano-web",
        ] -> (known after apply)
      + spot_instance_request_id             = (known after apply)
      ~ subnet_id                            = "subnet-04e02fb01624522da" -> (known after apply)
        tags                                 = {
            "Name" = "piano-web"
        }
      ~ tenancy                              = "default" -> (known after apply)
      + user_data_base64                     = (known after apply)
        # (9 unchanged attributes hidden)

      ~ capacity_reservation_specification (known after apply)
      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> null
        }

      ~ cpu_options (known after apply)
      - cpu_options {
          - core_count            = 1 -> null
          - threads_per_core      = 2 -> null
            # (2 unchanged attributes hidden)
        }

      - credit_specification {
          - cpu_credits = "unlimited" -> null
        }

      ~ ebs_block_device (known after apply)

      ~ enclave_options (known after apply)
      - enclave_options {
          - enabled = false -> null
        }

      ~ ephemeral_block_device (known after apply)

      ~ instance_market_options (known after apply)

      ~ maintenance_options (known after apply)
      - maintenance_options {
          - auto_recovery = "default" -> null
        }

      ~ metadata_options (known after apply)
      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_protocol_ipv6          = "disabled" -> null
          - http_put_response_hop_limit = 2 -> null
          - http_tokens                 = "required" -> null
          - instance_metadata_tags      = "disabled" -> null
        }

      ~ network_interface (known after apply)

      ~ primary_network_interface (known after apply)
      - primary_network_interface {
          - delete_on_termination = true -> null
          - network_interface_id  = "eni-0e6df94b05eb9ce79" -> null
        }

      ~ private_dns_name_options (known after apply)
      - private_dns_name_options {
          - enable_resource_name_dns_a_record    = false -> null
          - enable_resource_name_dns_aaaa_record = false -> null
          - hostname_type                        = "ip-name" -> null
        }

      ~ root_block_device (known after apply)
      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/sda1" -> null
          - encrypted             = false -> null
          - iops                  = 3000 -> null
          - tags                  = {} -> null
          - tags_all              = {} -> null
          - throughput            = 125 -> null
          - volume_id             = "vol-09342b65be3603300" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp3" -> null
            # (1 unchanged attribute hidden)
        }

      ~ secondary_network_interface (known after apply)
    }

Plan: 1 to add, 0 to change, 1 to destroy.

Changes to Outputs:
  ~ url = "http://54.172.142.44" -> (known after apply)

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.web: Creating...
aws_instance.web: Still creating... [00m10s elapsed]
aws_instance.web: Creation complete after 13s [id=i-0a5975b4ee81b2997]
aws_instance.web (deposed object 576b0a2d): Destroying... [id=i-0e180bd0282b39e8a]
aws_instance.web: Still destroying... [id=i-0e180bd0282b39e8a, 00m10s elapsed]
aws_instance.web: Destruction complete after 20s

Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

Outputs:

url = "http://34.236.143.237"

curl the new address, and the lesson page answers again. Its last line names the server that sent it, and that's the new server's id. The old address is gone for good.

Ben's laptop: ~/piano-site
curl -s http://34.236.143.237 | grep served<small>served from i-0a5975b4ee81b2997</small>

Changes outside Terraform

Now someone changes things outside Terraform. Ana needs to log in to the server. So from her laptop, she uses the AWS command line to open port twenty-two, for S S H, to the whole internet. She changes it straight in AWS, not in the files. AWS says true: done. An S S H port open to everyone gets password-guessing traffic within minutes, so this is a change worth catching.

Ana's laptop
aws ec2 authorize-security-group-ingress --group-name piano-web --protocol tcp --port 22 --cidr 0.0.0.0/0 --query Returntrue

Next time you run terraform plan, take a guess: does Terraform keep that port twenty-two rule, or remove it? Removes it. Terraform reads the real firewall from AWS, finds a rule the files don't have, and plans to put it back the way the file says: update in place, and port twenty-two goes.

Ben's laptop: ~/piano-site
terraform plandata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 0s [id=ami-02fffd5f990bcc920]
aws_instance.web: Refreshing state... [id=i-0a5975b4ee81b2997]

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:

  # aws_security_group.web will be updated in-place
  ~ resource "aws_security_group" "web" {
        id                     = "sg-0b43c99b2ba1907b6"
      ~ ingress                = [
          - {
              - cidr_blocks      = [
                  - "0.0.0.0/0",
                ]
              - from_port        = 22
              - ipv6_cidr_blocks = []
              - prefix_list_ids  = []
              - protocol         = "tcp"
              - security_groups  = []
              - self             = false
              - to_port          = 22
                # (1 unchanged attribute hidden)
            },
          - {
              - cidr_blocks      = [
                  - "0.0.0.0/0",
                ]
              - from_port        = 80
              - ipv6_cidr_blocks = []
              - prefix_list_ids  = []
              - protocol         = "tcp"
              - security_groups  = []
              - self             = false
              - to_port          = 80
                # (1 unchanged attribute hidden)
            },
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + from_port        = 80
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "tcp"
              + security_groups  = []
              + self             = false
              + to_port          = 80
            },
        ]
        name                   = "piano-web"
        tags                   = {}
        # (9 unchanged attributes hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

───────────────────────────────────────────────────────────────────────────────

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.

Apply, and port twenty-two is shut again. A change made outside Terraform is called drift, and the next apply undoes it. So if a change is right, put it in the files, where everyone can see it, and run plan often, to catch drift early.

And servers someone clicked together before Terraform? Terraform ignores them until you import them. You write an import block with two things: the server's ID in AWS, and the name you want for it in your files, like aws instance dot web, next to a matching resource block. The next apply adds it to the state, without rebuilding it. Since Terraform 1.5, import blocks live in your dot T F files, so they get reviewed like everything else.

Bringing in what was clicked by hand: diagram of A server made by hand, An import block, State

Working as a team

There's a catch once a team shares the files. The state lives on one laptop. A teammate with the same files but no state would plan to build everything a second time, and two applies at once could break the state file. And your teammate is about to need it.

So keep the state in S3. A backend is where Terraform keeps its state. Why make this bucket by hand, not with Terraform? Because Terraform needs somewhere to keep its state before it can build anything else. Make a bucket for it with the AWS command line: aws S3 m b, make bucket, and add a backend block: the bucket, a key that names the file inside it, the region, and use lockfile, true. Bucket names are global, remember, so this one ends in today's date.

Ben's laptop: ~/piano-site
aws s3 mb s3://piano-tfstate-20261130make_bucket: piano-tfstate-20261130
Ben's laptop: ~/piano-site
cat backend.tfterraform {
  backend "s3" {
    bucket       = "piano-tfstate-20261130"
    key          = "piano-site/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true
  }
}

terraform init with dash migrate state sees the new backend, and asks to copy your existing state into it. It even explains: state was found in the old local backend, and none in S3 yet. Yes. From now on, the state lives in the bucket, for everyone.

Ben's laptop: ~/piano-site
terraform init -migrate-stateInitializing the backend...
Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "local" backend to the
  newly configured "s3" backend. No existing state was found in the newly
  configured "s3" backend. Do you want to copy this state to the new "s3"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value: yes


Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
- Reusing version 6.74.0 of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v6.74.0

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.

While you're at it, decide what goes in Git. Commit the dot T F files, and the provider lock file, dot terraform dot lock dot H C L. Leave out the dot terraform folder, which init downloads again, and any state file, which now lives in S3 anyway.

What goes in Git: cards of Commit, Leave out, init gets it back

On a teammate's laptop, it's the same files and one terraform init. It connects to the same state in S3, and look: reusing version six point seven four from the lock file. Same provider, same state, no copying.

Ana's laptop
terraform initInitializing the backend...

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
- Reusing version 6.74.0 of hashicorp/aws from the dependency lock file
- Installing hashicorp/aws v6.74.0...
- Installed hashicorp/aws v6.74.0 (signed by HashiCorp)

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.

Now two people use it. Ben sets the size to t3 small in terraform dot T F vars, and runs terraform apply. While his plan waits for a yes, Ana runs terraform plan, and gets: error acquiring the state lock, and who holds it: Ben, on his laptop. That's the lock doing its job: one command at a time, and plan takes the lock too.

Ben's laptop: ~/piano-site
cat terraform.tfvarsinstance_type = "t3.small"
Ben's laptop: ~/piano-site
terraform applydata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 0s [id=ami-02fffd5f990bcc920]
aws_instance.web: Refreshing state... [id=i-0a5975b4ee81b2997]

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:

  # aws_instance.web will be updated in-place
  ~ resource "aws_instance" "web" {
        id                                   = "i-0a5975b4ee81b2997"
      ~ instance_type                        = "t3.micro" -> "t3.small"
      ~ public_dns                           = "ec2-34-236-143-237.compute-1.amazonaws.com" -> (known after apply)
      ~ public_ip                            = "34.236.143.237" -> (known after apply)
        tags                                 = {
            "Name" = "piano-web"
        }
        # (38 unchanged attributes hidden)

        # (9 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Changes to Outputs:
  ~ url = "http://34.236.143.237" -> (known after apply)

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.web: Modifying... [id=i-0a5975b4ee81b2997]
aws_instance.web: Still modifying... [id=i-0a5975b4ee81b2997, 00m10s elapsed]
aws_instance.web: Still modifying... [id=i-0a5975b4ee81b2997, 00m20s elapsed]
aws_instance.web: Still modifying... [id=i-0a5975b4ee81b2997, 00m30s elapsed]
aws_instance.web: Modifications complete after 32s [id=i-0a5975b4ee81b2997]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Outputs:

url = "http://100.30.254.250"
Ben's laptop: ~/piano-site
terraform plan╷
│ Error: Error acquiring the state lock
│
│ Error message: operation error S3: PutObject, https response error
│ StatusCode: 412, RequestID: H4PXP1R0Q9GTSVYF, HostID:
│ U9N31+denePX3kqdHGDbJzu9ues7dKVXBPKTnzZZgMLiLzKlfq6sn/TsO8q2ZidJg/uNxPzTWaM5vKrUIPIQtn0v8y73cXzj,
│ api error PreconditionFailed: At least one of the pre-conditions you
│ specified did not hold
│ Lock Info:
│   ID:        01928f2e-df5b-dba6-8c93-8209819f52b2
│   Path:      piano-tfstate-20261130/piano-site/terraform.tfstate
│   Operation: OperationTypeApply
│   Who:       ben@laptop
│   Version:   1.17.2
│   Created:   2026-12-01 03:53:54.474301134 +0000 UTC
│   Info:
│
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.
╵

This is a different lock from the provider lock file: while a command runs, Terraform keeps a small lock file next to your state in S3.

Two different locks: comparison table of .terraform.lock.hcl vs The state lock, in S3, What it holds, Made by, Lives, Its job, Its error

When the apply finishes, the lock goes. The server stopped, grew to t3 small and started again in 32 seconds, and look: a new public address again, since it restarted. Same server, same id, just bigger. The plan even warned you: public ip, known after apply. curl the new address, and it's the same server id, still serving the page, because that systemd service started it again.

Ben's laptop: ~/piano-site
curl -s http://100.30.254.250 | grep served<small>served from i-0a5975b4ee81b2997</small>

One last thing about locks. If an apply crashes halfway, its lock can stay behind. terraform force-unlock with the lock's ID removes it, but only once you're sure nobody is still running.

A lock left behind: diagram of An apply, Lock file, You, crashes halfway, the lock stays, terraform force-unlock, removed, only if nobody's running, Locks can outlive a crash

Clean up

Finally, clean up. terraform destroy plans a minus for all three: three to destroy. It asks more seriously this time: there is no undo. Yes, and 30 seconds later: destroy complete. terraform state list now prints nothing. The page, the firewall and the bucket are gone, and you stop paying for them. That's why anything you can't lose gets the lifecycle setting prevent destroy. And notice what it didn't touch: the state bucket you made by hand. Terraform only destroys what's in its state.

Ben's laptop: ~/piano-site
terraform destroydata.aws_ami.ubuntu: Reading...
aws_security_group.web: Refreshing state... [id=sg-0b43c99b2ba1907b6]
aws_s3_bucket.sheets: Refreshing state... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
data.aws_ami.ubuntu: Read complete after 0s [id=ami-02fffd5f990bcc920]
aws_instance.web: Refreshing state... [id=i-0a5975b4ee81b2997]

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:

  # aws_instance.web will be destroyed
  - resource "aws_instance" "web" {
      - ami                                  = "ami-02fffd5f990bcc920" -> null
      - arn                                  = "arn:aws:ec2:us-east-1:346882411366:instance/i-0a5975b4ee81b2997" -> null
      - associate_public_ip_address          = true -> null
      - availability_zone                    = "us-east-1c" -> null
      - disable_api_stop                     = false -> null
      - disable_api_termination              = false -> null
      - ebs_optimized                        = false -> null
      - force_destroy                        = false -> null
      - get_password_data                    = false -> null
      - hibernation                          = false -> null
      - id                                   = "i-0a5975b4ee81b2997" -> null
      - instance_initiated_shutdown_behavior = "stop" -> null
      - instance_state                       = "running" -> null
      - instance_type                        = "t3.small" -> null
      - ipv6_address_count                   = 0 -> null
      - ipv6_addresses                       = [] -> null
      - monitoring                           = false -> null
      - placement_partition_number           = 0 -> null
      - primary_network_interface_id         = "eni-06af605d744cf84de" -> null
      - private_dns                          = "ip-172-31-24-143.ec2.internal" -> null
      - private_ip                           = "172.31.24.143" -> null
      - public_dns                           = "ec2-100-30-254-250.compute-1.amazonaws.com" -> null
      - public_ip                            = "100.30.254.250" -> null
      - region                               = "us-east-1" -> null
      - secondary_private_ips                = [] -> null
      - security_groups                      = [
          - "piano-web",
        ] -> null
      - source_dest_check                    = true -> null
      - subnet_id                            = "subnet-04e02fb01624522da" -> null
      - tags                                 = {
          - "Name" = "piano-web"
        } -> null
      - tags_all                             = {
          - "Name" = "piano-web"
        } -> null
      - tenancy                              = "default" -> null
      - user_data                            = <<-EOT
            #!/bin/bash
            mkdir -p /srv/site && cd /srv/site
            cat > index.html <<'HTML'
            <!doctype html>
            <html><head><meta charset="utf-8"><title>Piano lessons with Ben</title>
            <style>
            body{font-family:Georgia,serif;background:#fbf7ef;color:#2b2118;margin:0;padding:64px 80px}
            h1{font-size:56px;margin:0 0 12px} p{font-size:26px;margin:8px 0}
            .slots{margin-top:28px;display:flex;gap:18px}
            .slot{background:#fff;border:2px solid #2b2118;border-radius:12px;padding:16px 22px;font-size:24px}
            small{display:block;margin-top:36px;font-family:monospace;font-size:20px;color:#6b5a48}
            </style></head><body>
            <h1>Piano lessons with Ben</h1>
            <p>Beginners welcome. Book a 30-minute lesson.</p>
            <div class="slots"><div class="slot">Tue 4:00 pm</div><div class="slot">Tue 5:00 pm</div><div class="slot">Thu 4:30 pm</div></div>
            <small>served from SERVER_ID</small>
            </body></html>
            HTML
            sed -i "s/SERVER_ID/$(cloud-init query ds.meta_data.instance_id)/" index.html
            cat > /etc/systemd/system/site.service <<'UNIT'
            [Unit]
            Description=Piano lessons page
            After=network-online.target

            [Service]
            WorkingDirectory=/srv/site
            ExecStart=/usr/bin/python3 -m http.server 80

            [Install]
            WantedBy=multi-user.target
            UNIT
            systemctl enable --now site.service
        EOT -> null
      - user_data_replace_on_change          = false -> null
      - vpc_security_group_ids               = [
          - "sg-0b43c99b2ba1907b6",
        ] -> null
        # (9 unchanged attributes hidden)

      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> null
        }

      - cpu_options {
          - core_count            = 1 -> null
          - threads_per_core      = 2 -> null
            # (2 unchanged attributes hidden)
        }

      - credit_specification {
          - cpu_credits = "unlimited" -> null
        }

      - enclave_options {
          - enabled = false -> null
        }

      - maintenance_options {
          - auto_recovery = "default" -> null
        }

      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_protocol_ipv6          = "disabled" -> null
          - http_put_response_hop_limit = 2 -> null
          - http_tokens                 = "required" -> null
          - instance_metadata_tags      = "disabled" -> null
        }

      - primary_network_interface {
          - delete_on_termination = true -> null
          - network_interface_id  = "eni-06af605d744cf84de" -> null
        }

      - private_dns_name_options {
          - enable_resource_name_dns_a_record    = false -> null
          - enable_resource_name_dns_aaaa_record = false -> null
          - hostname_type                        = "ip-name" -> null
        }

      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/sda1" -> null
          - encrypted             = false -> null
          - iops                  = 3000 -> null
          - tags                  = {} -> null
          - tags_all              = {} -> null
          - throughput            = 125 -> null
          - volume_id             = "vol-08bea602913e168ca" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp3" -> null
            # (1 unchanged attribute hidden)
        }
    }

  # aws_s3_bucket.sheets will be destroyed
  - resource "aws_s3_bucket" "sheets" {
      - arn                         = "arn:aws:s3:::sheetmusic-aaeb994ed2623c75fa005636c6" -> null
      - bucket                      = "sheetmusic-aaeb994ed2623c75fa005636c6" -> null
      - bucket_domain_name          = "sheetmusic-aaeb994ed2623c75fa005636c6.s3.amazonaws.com" -> null
      - bucket_namespace            = "global" -> null
      - bucket_prefix               = "sheetmusic-" -> null
      - bucket_region               = "us-east-1" -> null
      - bucket_regional_domain_name = "sheetmusic-aaeb994ed2623c75fa005636c6.s3.us-east-1.amazonaws.com" -> null
      - force_destroy               = false -> null
      - hosted_zone_id              = "Z3AQBSTGFYJSTF" -> null
      - id                          = "sheetmusic-aaeb994ed2623c75fa005636c6" -> null
      - object_lock_enabled         = false -> null
      - region                      = "us-east-1" -> null
      - request_payer               = "BucketOwner" -> null
      - tags                        = {} -> null
      - tags_all                    = {} -> null
        # (2 unchanged attributes hidden)

      - grant {
          - id          = "6ab2cdc88801c1bb9d31402ea6250547c841b4cb0d67216b42f218190abfc900" -> null
          - permissions = [
              - "FULL_CONTROL",
            ] -> null
          - type        = "CanonicalUser" -> null
            # (1 unchanged attribute hidden)
        }

      - server_side_encryption_configuration {
          - rule {
              - bucket_key_enabled = false -> null

              - apply_server_side_encryption_by_default {
                  - sse_algorithm     = "AES256" -> null
                    # (1 unchanged attribute hidden)
                }
            }
        }

      - versioning {
          - enabled    = false -> null
          - mfa_delete = false -> null
        }
    }

  # aws_security_group.web will be destroyed
  - resource "aws_security_group" "web" {
      - arn                    = "arn:aws:ec2:us-east-1:346882411366:security-group/sg-0b43c99b2ba1907b6" -> null
      - description            = "Managed by Terraform" -> null
      - egress                 = [
          - {
              - cidr_blocks      = [
                  - "0.0.0.0/0",
                ]
              - from_port        = 0
              - ipv6_cidr_blocks = []
              - prefix_list_ids  = []
              - protocol         = "-1"
              - security_groups  = []
              - self             = false
              - to_port          = 0
                # (1 unchanged attribute hidden)
            },
        ] -> null
      - id                     = "sg-0b43c99b2ba1907b6" -> null
      - ingress                = [
          - {
              - cidr_blocks      = [
                  - "0.0.0.0/0",
                ]
              - from_port        = 80
              - ipv6_cidr_blocks = []
              - prefix_list_ids  = []
              - protocol         = "tcp"
              - security_groups  = []
              - self             = false
              - to_port          = 80
                # (1 unchanged attribute hidden)
            },
        ] -> null
      - name                   = "piano-web" -> null
      - owner_id               = "346882411366" -> null
      - region                 = "us-east-1" -> null
      - revoke_rules_on_delete = false -> null
      - tags                   = {} -> null
      - tags_all               = {} -> null
      - vpc_id                 = "vpc-082c347be87c9955a" -> null
        # (1 unchanged attribute hidden)
    }

Plan: 0 to add, 0 to change, 3 to destroy.

Changes to Outputs:
  - url = "http://100.30.254.250" -> null

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

aws_s3_bucket.sheets: Destroying... [id=sheetmusic-aaeb994ed2623c75fa005636c6]
aws_instance.web: Destroying... [id=i-0a5975b4ee81b2997]
aws_s3_bucket.sheets: Destruction complete after 0s
aws_instance.web: Still destroying... [id=i-0a5975b4ee81b2997, 00m10s elapsed]
aws_instance.web: Still destroying... [id=i-0a5975b4ee81b2997, 00m20s elapsed]
aws_instance.web: Still destroying... [id=i-0a5975b4ee81b2997, 00m30s elapsed]
aws_instance.web: Destruction complete after 30s
aws_security_group.web: Destroying... [id=sg-0b43c99b2ba1907b6]
aws_security_group.web: Destruction complete after 1s

Destroy complete! Resources: 3 destroyed.
Ben's laptop: ~/piano-site
terraform state list

Measured in this run: the bucket took one second, the server 13, the safe swap 33, and tearing it all down 30. The slow part is typing the files.

Seconds on AWS, measured in this run: chart of Bucket: 1 seconds, Server: 13 seconds, Replace the server: 33 seconds, Destroy all: 30 seconds, Typing is the slow part

From here, three things are worth learning next. Modules, which package a group of resources so you can reuse them. Running plan on every pull request, a proposed change in Git, so your team reviews the plan, not just the code. And more providers, with the same plan and apply.

Where to go next: cards of Modules, Reuse, Plan on pull requests, Reviews, More providers

And Ben's lesson page? It's no longer a server nobody can rebuild. It's four small files in Git. If it breaks, Ana runs terraform apply, and about 23 seconds later, students can book again.

Ben's piano lessons, as code: diagram of four.tf files, in Git, rebuilt with one apply, bookings open again

Recap

To sum up: your files say what you want. init gets the provider. plan shows plus, tilde and minus before anything happens. apply makes it real and records it in state, and that state belongs in a shared, locked bucket.

If you'd like more cloud tools built for real, from an empty folder, a like helps other beginners find this, and subscribing brings the next one.

Every plan and error here came from a real AWS account, and the lab files, every dot T F file included, are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: two Ubuntu laptops in Docker and a real AWS account (everything destroyed at the end). Every command and output was real. Watch the full video on YouTube.

More videos

Kubernetes10 min

Docker vs Kubernetes: What's the Difference?

HTTP & HTTPS11 min

Every HTTP Status Code You Need to Know

PostgreSQL8 min

How to Fix PostgreSQL 'Relation Does Not Exist' Errors

Git9 min

Git Merge vs Rebase: Which One Should You Use?

APIs10 min

How API Webhooks Work

LLM infrastructure9 min

How LLM Tokens Work

Docker9 min

Docker Containers vs Virtual Machines: What's the Difference?

PostgreSQL9 min

MySQL vs PostgreSQL: Which One Should You Use?

Local LLMs (Ollama)15 min

Ollama: Full Tutorial for Beginners

GitHub Actions15 min

GitHub Actions: Full Tutorial for Beginners

Certificates & PKI (ADCS)8 min

How to Fix Certificate Errors: 'Your Connection Is Not Private'

AWS9 min

How the Amazon Ergo AI Model Works

LLM infrastructure9 min

How to Fix LLM API Rate Limit Errors (429)

LLM infrastructure9 min

RAG vs Fine-Tuning: Which One Should You Use?

Load balancing & Nginx24 min

Nginx: Full Tutorial for Beginners

Go (Golang)5 min

Golang go func(): Starting Goroutines in 5 Minutes

Go (Golang)5 min

Golang Generics ([T any]) in 5 Minutes

AWS9 min

How AWS Bedrock Works

LLM infrastructure8 min

How LLM Embeddings Work

Python9 min

How to Fix Python CUDA Memory Errors in PyTorch

Go (Golang)5 min

Golang Type Assertions in 5 Minutes

LLM infrastructure10 min

CPU vs GPU for LLM Inference: What Actually Changes

Google Colab (Jupyter notebooks in the cloud)15 min

Google Colab: Full Tutorial for Beginners

AWS8 min

Amazon Bedrock vs OpenRouter: Which One Should You Use?

Go (Golang)5 min

Golang Channels (chan) in 5 Minutes

Homelab & self-hosting21 min

Tailscale: Full Tutorial for Beginners

LLM infrastructure9 min

How RAG Works

Git11 min

Every Git Setting to Change on Day One

Linux9 min

WSL vs a Linux Virtual Machine: Which One Should You Use?

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Python8 min

How to Fix Python 'Address Already in Use' Errors

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Git7 min

How to Fix Git 'Detached HEAD' State

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Auth (OAuth, JWT)9 min

How to Fix OAuth 'invalid_grant' Errors

Databases & SQL11 min

The SQL Roadmap for Beginners

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Go (Golang)5 min

Golang context.Context in 5 Minutes

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index