Terraform: Full Tutorial for Beginners
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.

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.
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](/img/terraform-full-tutorial-for-beginners/paradox.jpg)
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.

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.

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.

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.

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.

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.
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.

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.
mkdir piano-site && cd 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.

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.
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.
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.
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.

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.

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.
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.
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.

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.
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?
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.
lsmain.tf terraform.tfstate terraform.tfstate.backup
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": {
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.

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)](/img/terraform-full-tutorial-for-beginners/amidata.jpg)
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.

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.

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)](/img/terraform-full-tutorial-for-beginners/instblock.jpg)
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.

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.
cat variables.tfvariable "instance_type" { description = "Size of the web server" type = string default = "t3.micro" }
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.
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"? ╵
terraform validateSuccess! The configuration is valid.
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.
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.
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.

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.
terraform outputurl = "http://54.172.142.44"
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.

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

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.
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.

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.
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.

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.](/img/terraform-full-tutorial-for-beginners/upgrade.jpg)
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.

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.

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.
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.

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.
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.
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.
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.
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.

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.
aws s3 mb s3://piano-tfstate-20261130make_bucket: piano-tfstate-20261130
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.
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.

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.
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.
cat terraform.tfvarsinstance_type = "t3.small"
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"
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.

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.
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.

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.
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.
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.

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.

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.

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
- HashiCorp, Install Terraform (the two lines that add HashiCorp's package list, then apt install)
- Create an AWS account
- Install the AWS CLI
- Create an access key (and aws configure)
- AWS EC2 on-demand pricing: https://aws.amazon.com/ec2/pricing/on-demand/ ; public IPv4 addresses
- HashiCorp, State
- HashiCorp, terraform plan
- HashiCorp, the lifecycle meta-argument
- HashiCorp, the S3 backend (use_lockfile)
- AWS provider, aws_instance
- Amazon S3 bucket naming rules
- Terraform Registry, hashicorp/aws (downloads)
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.