By the end you'll know
- Where Terraform's state should live on AWS, and why the bucket needs versioning, encryption and a lock
- How the AWS provider's default tags, data sources and modules keep the code short
- How to plan, save the plan, and apply exactly what was reviewed
- What drift looks like, and how Terraform puts it back
- How to read a plan for the changes that destroy things, before they happen
- Why the state file is sensitive, and what a team does about it
Before you start
- You need: the
juniper-ryeprofile, signed in, Lesson 20's virtual environment, Docker running, and Terraform 1.11 or newer. On a Mac:brew install hashicorp/tap/terraform. - This lesson builds on two others. Lesson 27 built the same service with a script. The Terraform basics track covers reading a plan, state, remote state and modules; this lesson is about doing them on AWS.
- The lab:
lesson-28in the practice folder:lab.pyand aterraformfolder. Everything it creates is namedjr-lesson28-*and taggedlesson=28. - How Terraform runs: through
python lab.py tf, which hands Terraform your sign-in as short-lived keys for that one run, and hides your account ID and IP in what it prints. The "By hand" section shows plainterraform. - Where you run things: your own machine, labeled (Your machine).
- Every output below is from a real run on November 15, 2026, with Terraform 1.11.3 and the AWS provider 6.73.0. Some outputs are trimmed to the part that matters; each block is a continuous piece of the real output.
The state file is a map of your account
Terraform's state holds every resource's ID, ARN and settings, and anything secret that passes through Terraform, like a database password, in plain text. Keep it in a private, encrypted bucket, never in Git, and give few people access. While the service runs it also bills about 6 cents an hour, like Lesson 27: finish with the destroy and delete steps.
The short version
- State goes in S3, with versioning and a lock file, so a team shares one record and two runs can't collide.
- Plan to a file, review it, apply that file, so what changes is exactly what was read.
- Count the destroys in every plan. One changed number here would have replaced 13 resources, the network included.
- Drift is what someone changed by hand; the next plan shows it and the apply puts it back.
- Terraform works out the order of creating and deleting, and waits for AWS when it has to.
What this lesson costs
| Part | Cost, in us-east-2 |
|---|---|
| Two copies on Fargate, Arm | $0.0198 an hour together |
| The load balancer | $0.0225 an hour |
| Four public IPv4 addresses | $0.020 an hour |
| The state bucket, about 50 KB a version | A fraction of a cent a month |
| This lesson, about an hour | About 6 cents, from credits |
Why Terraform, after a script
Lesson 27's script was about 950 lines, and over 200 of them were about deleting: the order things have to go in, retries while AWS lets go, and a target group that stayed "in use" for 20 minutes. Every resource needed code to create it, code to find it again, and code to delete it.
Terraform turns that around. You write down what should exist, about 350 lines here, comments included, and Terraform works out what to create, change or delete to get there, in what order, and keeps a record of what it made so it can find it all again.
| File | Holds |
|---|---|
versions.tf | The Terraform and provider versions allowed, and an empty s3 backend |
providers.tf | The AWS provider: Region, and tags for everything |
variables.tf | What can change: name, address range, image tag, copies, who may connect |
main.tf | Security groups, load balancer, roles, logs, cluster, task definition, service |
modules/network/ | The VPC, two subnets, internet gateway and routes, as a reusable block |
outputs.tf | The address, the task definition revision, the subnets |
.gitignore | Keeps .terraform/, saved plans, state and your IP out of Git |
Where state lives
Terraform's state is its record of what it made: each resource's ID and settings, so the next run knows that aws_lb.menu is one particular load balancer. On a laptop it's a file; for anything shared, it goes in S3.
(Your machine)
cd ~/Apps/aws-practice/lesson-28
source ../lesson-20/.venv/bin/activate
python lab.py fence
python lab.py state
== Is Terraform installed?
yes: Terraform 1.11.3
== Is Docker running?
yes: linux/arm64 29.9.2
== Can Terraform use your sign-in?
yes: short-lived keys from the juniper-rye profile, with a session token; passed to Terraform on each run, never saved
== What it costs while the service runs (from the Price List API)
2 copies $0.0198, load balancer $0.0225, 4 public IPs $0.020: about $0.062 an hour
the state bucket: a few KB, a fraction of a cent a month
== A bucket for Terraform's state: jr-lesson28-state-2ac15a56
== jr-lesson28-state-2ac15a56: versioning enabled, encrypted, public access blocked, HTTPS only
== backend.hcl, for terraform init:
| bucket = "jr-lesson28-state-2ac15a56"
| key = "menu/terraform.tfstate"
| region = "us-east-2"
| use_lockfile = true
| encrypt = true
== my-ip.auto.tfvars: allowed_cidr = "your IP/32" (Terraform reads *.auto.tfvars by itself)
| Setting | Why |
|---|---|
| Versioning | Every write keeps the old version, so a bad apply or a corrupted file can be rolled back |
| Encryption | The state holds IDs, ARNs and sometimes secrets |
| Public access blocked, HTTPS only | Nobody reads it by accident, or over plain HTTP |
use_lockfile = true | Terraform writes a .tflock file next to the state while it works, so a second run can't start |
| A random suffix on the name | Bucket names are global across every AWS account |
The lock used to need a DynamoDB table; since Terraform 1.11 it doesn't. S3 can now refuse to write a file that already exists, and Terraform uses that: the first run creates terraform.tfstate.tflock, and any other run that tries finds it there. Older guides still set up DynamoDB for this; with 1.11 or newer, it's one less thing to make.
The bucket itself is made by the script, not by Terraform, because Terraform needs it to exist before it can store anything. In real systems the state bucket is made once, by a small separate Terraform configuration or by hand, and then left alone. The image repository is outside this configuration for the same reason: images must be pushed before a service can run them.
python lab.py image
== The image repository, made outside Terraform: images have to exist before a service can run them
pushed jr-lesson28-menu:v1
pushed jr-lesson28-menu:v2
The code
Four parts of the code are specific to AWS and worth reading closely.
Tags on everything, written once. The provider adds these to every resource that takes tags, which is why every resource in the plan below has a tags_all with them:
provider "aws" {
region = var.region
default_tags {
tags = {
lesson = "28"
owner = "juniper-rye"
managed_by = "terraform"
}
}
}
Things Terraform reads but doesn't own are data sources. The repository is found by name, and its address goes into the task definition; Terraform will never change or delete it:
data "aws_ecr_repository" "menu" {
name = "${var.name}-menu"
}
The network is a module, called with two values. Inside, it makes the VPC, a subnet in each of two zones with count, the internet gateway and the routes; outside, the rest of the code sees only module.network.vpc_id and module.network.subnet_ids:
module "network" {
source = "./modules/network"
name = var.name
cidr = var.vpc_cidr
}
The service waits until it's healthy. Without wait_for_steady_state, Terraform reports success as soon as ECS accepts the change, even if the new copies then fail to start:
resource "aws_ecs_service" "menu" {
name = "${var.name}-menu"
cluster = aws_ecs_cluster.menu.id
task_definition = aws_ecs_task_definition.menu.arn
desired_count = var.desired_count
launch_type = "FARGATE"
health_check_grace_period_seconds = 30
deployment_minimum_healthy_percent = 100
deployment_maximum_percent = 200
wait_for_steady_state = true
Plan, then apply the saved plan
python lab.py tf init -backend-config=backend.hcl
python lab.py tf fmt -check -recursive
python lab.py tf validate
Initializing the backend...
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing modules...
- network in modules/network
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 6.0"...
- Installing hashicorp/aws v6.73.0...
- Installed hashicorp/aws v6.73.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!
Success! The configuration is valid.
fmt -check printed nothing, which means the files were already formatted. Two kinds of lock file now exist, and they're easy to mix up: .terraform.lock.hcl pins the provider version and belongs in Git; the .tflock in S3 is the state lock and lasts only while a run works.
python lab.py tf plan -out=tfplan
The plan lists all 23 resources, each with every setting. One of them, and the end:
# aws_ecs_cluster.menu will be created
+ resource "aws_ecs_cluster" "menu" {
+ arn = (known after apply)
+ id = (known after apply)
+ name = "jr-lesson28"
+ region = "us-east-2"
+ tags_all = {
+ "lesson" = "28"
+ "managed_by" = "terraform"
+ "owner" = "juniper-rye"
}
+ setting (known after apply)
}
Plan: 23 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ subnets = [
+ (known after apply),
+ (known after apply),
]
+ task_definition_revision = (known after apply)
+ url = (known after apply)
python lab.py tf apply tfplan
python lab.py call
aws_lb.menu: Creation complete after 2m22s [id=arn:aws:elasticloadbalancing:us-east-2:111122223333:loadbalancer/app/jr-lesson28-alb/547133f7cc1b1315]
aws_lb_listener.http: Creating...
aws_lb_listener.http: Creation complete after 0s [id=arn:aws:elasticloadbalancing:us-east-2:111122223333:listener/app/jr-lesson28-alb/547133f7cc1b1315/29cee957325bf92f]
aws_ecs_service.menu: Creating...
aws_ecs_service.menu: Still creating... [10s elapsed]
aws_ecs_service.menu: Still creating... [20s elapsed]
aws_ecs_service.menu: Still creating... [30s elapsed]
aws_ecs_service.menu: Still creating... [40s elapsed]
aws_ecs_service.menu: Still creating... [50s elapsed]
aws_ecs_service.menu: Still creating... [1m0s elapsed]
aws_ecs_service.menu: Still creating... [1m10s elapsed]
aws_ecs_service.menu: Still creating... [1m20s elapsed]
aws_ecs_service.menu: Creation complete after 1m27s [id=arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu]
Apply complete! Resources: 23 added, 0 changed, 0 destroyed.
Outputs:
subnets = [
"subnet-0338e38151eb30ec6",
"subnet-05b7eb916d97ad35d",
]
task_definition_revision = 1
url = "http://jr-lesson28-alb-619766516.us-east-2.elb.amazonaws.com"
== GET http://jr-lesson28-alb-619766516.us-east-2.elb.amazonaws.com/ ten times
v1 task 238169ff answered 5
v1 task e7e24227 answered 5
Applying tfplan applied exactly the plan that was read, with no second question. Terraform worked through the 23 in the order the references allow: the VPC before its subnets, the subnets and security groups before the load balancer, the listener before the service, because of the depends_on. Things that didn't depend on each other, like the roles and the network, were made at the same time. The load balancer took 2m22s; then wait_for_steady_state held the service until both copies were healthy, 1m27s later.
Drift: changes made behind Terraform's back
Drift is when what's really running in AWS no longer matches what the code says, usually because someone changed something by hand in the console or the CLI. Terraform doesn't notice when it happens; it finds out the next time anyone runs a plan.
Here's the same thing in the lab. Someone opens the console "just for tonight", drops the service to one copy and changes a tag.
python lab.py drift
python lab.py tf plan -out=tfplan
== Behind Terraform's back, as someone in the console might:
the service now wants 1 copy, not 2 ("just for tonight, to save money")
the cluster's owner tag is now someone-else
== Terraform doesn't know yet. Run: python lab.py tf plan
Terraform will perform the following actions:
# aws_ecs_cluster.menu will be updated in-place
~ resource "aws_ecs_cluster" "menu" {
id = "arn:aws:ecs:us-east-2:111122223333:cluster/jr-lesson28"
name = "jr-lesson28"
~ tags = {
- "owner" = "someone-else" -> null
}
~ tags_all = {
~ "owner" = "someone-else" -> "juniper-rye"
# (2 unchanged elements hidden)
}
# (2 unchanged attributes hidden)
# (1 unchanged block hidden)
}
# aws_ecs_service.menu will be updated in-place
~ resource "aws_ecs_service" "menu" {
~ desired_count = 1 -> 2
id = "arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu"
name = "jr-lesson28-menu"
tags = {}
# (18 unchanged attributes hidden)
# (5 unchanged blocks hidden)
}
Plan: 0 to add, 2 to change, 0 to destroy.
python lab.py tf apply tfplan
aws_ecs_cluster.menu: Modifying... [id=arn:aws:ecs:us-east-2:111122223333:cluster/jr-lesson28]
aws_ecs_cluster.menu: Modifications complete after 0s [id=arn:aws:ecs:us-east-2:111122223333:cluster/jr-lesson28]
aws_ecs_service.menu: Modifying... [id=arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu]
aws_ecs_service.menu: Modifications complete after 1s [id=arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu]
Apply complete! Resources: 0 added, 2 changed, 0 destroyed.
Every plan starts by reading what really exists, the "Refreshing state" lines, so drift shows up the next time anyone runs one. The apply put both back, and that's the point to take seriously: a change made by hand lasts only until the next apply. If dropping to one copy was right, the fix is to change desired_count in the code, so the next apply keeps it.
Not everything is drift Terraform can see. It only checks the settings it manages: a security group rule added by hand to a group Terraform doesn't know about, or a whole resource made in the console, is invisible to it.
The lock
python lab.py lock
== Two plans against the same state, the second started 3 seconds after the first
first plan: finished after 4 seconds
No changes. Your infrastructure matches the configuration.
second plan: failed after 1 seconds
Error: Error acquiring the state lock
Error message: operation error S3: PutObject, https response error
Lock Info:
ID: 95289c35-41ed-3235-ec86-b7c7a38d0d41
Path: jr-lesson28-state-2ac15a56/menu/terraform.tfstate
Operation: OperationTypePlan
Who: <you>@<your machine>
Created: 2026-11-15 20:39:03.419554 +0000 UTC
== While the first plan ran, the bucket held: menu/terraform.tfstate.tflock
== And now: menu/terraform.tfstate
The second plan stopped in 1 second instead of working from state that was about to change. The lock info says who holds it, what they're doing and since when, which is what a teammate needs to know before waiting or asking. When the first plan finished, the .tflock file was gone.
The lab used -lock-timeout=0s to fail at once. Normally you'd give a few minutes, so a run waits its turn. If a run crashes and leaves the lock behind, terraform force-unlock with the ID removes it, but only after you've checked that nothing is still running.
Ship v2 by changing one value
python lab.py tf plan -var image_tag=v2 -out=tfplan
Terraform will perform the following actions:
# aws_ecs_service.menu will be updated in-place
~ resource "aws_ecs_service" "menu" {
id = "arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu"
name = "jr-lesson28-menu"
tags = {}
~ task_definition = "arn:aws:ecs:us-east-2:111122223333:task-definition/jr-lesson28-menu:1" -> (known after apply)
# (18 unchanged attributes hidden)
# (5 unchanged blocks hidden)
}
# aws_ecs_task_definition.menu must be replaced
-/+ resource "aws_ecs_task_definition" "menu" {
~ arn = "arn:aws:ecs:us-east-2:111122223333:task-definition/jr-lesson28-menu:1" -> (known after apply)
~ arn_without_revision = "arn:aws:ecs:us-east-2:111122223333:task-definition/jr-lesson28-menu" -> (known after apply)
~ container_definitions = jsonencode(
~ [
~ {
- environment = []
~ image = "111122223333.dkr.ecr.us-east-2.amazonaws.com/jr-lesson28-menu:v1" -> "111122223333.dkr.ecr.us-east-2.amazonaws.com/jr-lesson28-menu:v2"
- mountPoints = []
name = "menu"
~ portMappings = [
~ {
- hostPort = 8080
# (2 unchanged attributes hidden)
},
]
- systemControls = []
- volumesFrom = []
# (2 unchanged attributes hidden)
},
] # forces replacement
)
~ enable_fault_injection = false -> (known after apply)
~ id = "jr-lesson28-menu" -> (known after apply)
~ revision = 1 -> (known after apply)
- tags = {} -> null
# (13 unchanged attributes hidden)
# (1 unchanged block hidden)
}
Plan: 1 to add, 1 to change, 1 to destroy.
python lab.py tf apply tfplan
python lab.py call
aws_ecs_task_definition.menu: Destroying... [id=jr-lesson28-menu]
aws_ecs_task_definition.menu: Destruction complete after 1s
aws_ecs_task_definition.menu: Creating...
aws_ecs_task_definition.menu: Creation complete after 0s [id=jr-lesson28-menu]
aws_ecs_service.menu: Modifying... [id=arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu]
aws_ecs_service.menu: Modifications complete after 1m57s [id=arn:aws:ecs:us-east-2:111122223333:service/jr-lesson28/jr-lesson28-menu]
Apply complete! Resources: 1 added, 1 changed, 1 destroyed.
Outputs:
subnets = [
"subnet-0338e38151eb30ec6",
"subnet-05b7eb916d97ad35d",
]
task_definition_revision = 2
url = "http://jr-lesson28-alb-619766516.us-east-2.elb.amazonaws.com"
== GET http://jr-lesson28-alb-619766516.us-east-2.elb.amazonaws.com/ ten times
v2 task 268fd99f answered 5
v2 task a8eb3d75 answered 5
"1 to destroy" sounds alarming, and here it's harmless, which is why a plan has to be read, not just counted. A task definition can't be edited, so a new image means a new revision: Terraform "destroys" revision 1, which only deregisters it, and creates revision 2. The copies running revision 1 kept running until ECS's rolling deployment replaced them, the same no-downtime rollout as Lesson 27, which Terraform waited 1m57s for.
The plan also shows lines that aren't changes: environment = [], mountPoints = [], hostPort = 8080 being "removed". Those are defaults AWS filled in that the code never mentioned. They appear whenever this resource changes, and they're noise; the line that matters is the image, and the comment # forces replacement.
A one-line change that rebuilds the network
Not every small change is small. Here's the plan for changing the network's address range, which was never applied:
python lab.py tf plan -var image_tag=v2 -var vpc_cidr=10.29.0.0/16
# module.network.aws_vpc.this must be replaced
-/+ resource "aws_vpc" "this" {
~ arn = "arn:aws:ec2:us-east-2:111122223333:vpc/vpc-034ffcb8c2316dd8f" -> (known after apply)
- assign_generated_ipv6_cidr_block = false -> null
~ cidr_block = "10.28.0.0/16" -> "10.29.0.0/16" # forces replacement
# aws_lb_target_group.menu must be replaced
-/+ resource "aws_lb_target_group" "menu" {
Plan: 13 to add, 4 to change, 13 to destroy.
One changed value, and 13 resources would be destroyed and made again: the VPC, both subnets, the route table and its links, both security groups and their four rules, and the target group. The load balancer and the service would be changed to point at the new ones. While that ran, the service would be unreachable.
| In the plan | Means | Read it as |
|---|---|---|
+ create | Something new | Usually safe |
~ update in-place | Changed without being replaced | Usually safe; check what changed |
-/+ destroy and then create replacement | Deleted, then made again with a new ID | Stop: anything using it may break, and data in it is gone |
# forces replacement | The setting that caused it | Is there another way to make this change? |
- destroy | Deleted | Was that intended? |
For things that must never be replaced by accident, like a database or the state bucket, Terraform has lifecycle { prevent_destroy = true }: any plan that would destroy it fails instead. The Terraform track's Reading a plan goes further into this.
The state, and its history
python lab.py history
python lab.py tf state list
== menu/terraform.tfstate in jr-lesson28-state-2ac15a56: 6 versions, newest first
20:41:12 serial 6 25 resources 49,571 bytes
20:41:12 serial 5 25 resources 49,344 bytes
20:39:02 serial 4 25 resources 49,569 bytes
20:38:52 serial 3 25 resources 47,684 bytes
20:38:51 serial 2 25 resources 47,457 bytes
20:37:24 serial 1 23 resources 39,303 bytes
== What the newest one holds, besides the resource list:
Terraform 1.11.3; account IDs in it: 1; ARNs in it: 39
it is a full record of your infrastructure: treat it like a secret
data.aws_caller_identity.current
data.aws_ecr_repository.menu
data.aws_iam_policy_document.ecs_tasks_trust
aws_cloudwatch_log_group.menu
aws_ecs_cluster.menu
aws_ecs_service.menu
aws_ecs_task_definition.menu
aws_iam_role.execution
aws_iam_role.task
aws_iam_role_policy_attachment.execution
aws_lb.menu
aws_lb_listener.http
aws_lb_target_group.menu
aws_security_group.alb
aws_security_group.tasks
aws_vpc_security_group_egress_rule.alb_out
aws_vpc_security_group_egress_rule.tasks_out
aws_vpc_security_group_ingress_rule.alb_http
aws_vpc_security_group_ingress_rule.tasks_from_alb
module.network.data.aws_availability_zones.available
module.network.aws_internet_gateway.this
module.network.aws_route_table.public
module.network.aws_route_table_association.public[0]
module.network.aws_route_table_association.public[1]
module.network.aws_subnet.public[0]
module.network.aws_subnet.public[1]
module.network.aws_vpc.this
Six versions in about four minutes, because every apply writes the state, and a long apply also saves part-way through: serial 1, with 23 entries, was written while the first apply was still waiting on the service. With versioning on, any of them can be restored if a run goes wrong. The "25 resources" is the state's own count of resource blocks, data sources included, so it doesn't match the 23 the plan created.
The newest version holds your account ID and 39 ARNs. Here that's only a map of the account; in a configuration with a database, it would also hold the database's password in plain text, because Terraform stores whatever the provider returns. That's why the bucket is private and encrypted, why state never goes in Git, and why who can read the bucket is as important as who can run apply.
terraform state list shows the address of everything Terraform tracks. Inside the module, addresses start module.network., and resources made with count have an index, like aws_subnet.public[0].
Take it down
python lab.py tf plan -destroy -var image_tag=v2 -out=tfplan
python lab.py tf apply tfplan
python lab.py delete
The destroy plan ended Plan: 0 to add, 0 to change, 23 to destroy. The apply's last minutes:
aws_ecs_service.menu: Destruction complete after 3m20s
aws_iam_role_policy_attachment.execution: Destroying... [id=jr-lesson28-execution-role/arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy]
aws_security_group.tasks: Destroying... [id=sg-0f6fa886f60238e13]
aws_ecs_cluster.menu: Destroying... [id=arn:aws:ecs:us-east-2:111122223333:cluster/jr-lesson28]
aws_ecs_task_definition.menu: Destroying... [id=jr-lesson28-menu]
aws_lb_listener.http: Destroying... [id=arn:aws:elasticloadbalancing:us-east-2:111122223333:listener/app/jr-lesson28-alb/547133f7cc1b1315/29cee957325bf92f]
aws_ecs_task_definition.menu: Destruction complete after 1s
aws_cloudwatch_log_group.menu: Destroying... [id=/ecs/jr-lesson28-menu]
aws_iam_role.task: Destroying... [id=jr-lesson28-task-role]
aws_ecs_cluster.menu: Destruction complete after 1s
aws_iam_role_policy_attachment.execution: Destruction complete after 1s
aws_iam_role.execution: Destroying... [id=jr-lesson28-execution-role]
aws_lb_listener.http: Destruction complete after 1s
aws_lb_target_group.menu: Destroying... [id=arn:aws:elasticloadbalancing:us-east-2:111122223333:targetgroup/jr-lesson28-tg/82cf8c6bb8363d97]
aws_lb.menu: Destroying... [id=arn:aws:elasticloadbalancing:us-east-2:111122223333:loadbalancer/app/jr-lesson28-alb/547133f7cc1b1315]
module.network.aws_internet_gateway.this: Still destroying... [id=igw-0f90675b8af5ea9ba, 3m20s elapsed]
aws_iam_role.task: Destruction complete after 0s
aws_iam_role.execution: Destruction complete after 0s
aws_cloudwatch_log_group.menu: Destruction complete after 0s
aws_lb_target_group.menu: Destruction complete after 0s
aws_security_group.tasks: Destruction complete after 1s
aws_lb.menu: Destruction complete after 8s
module.network.aws_subnet.public[0]: Destroying... [id=subnet-0338e38151eb30ec6]
module.network.aws_subnet.public[1]: Destroying... [id=subnet-05b7eb916d97ad35d]
aws_security_group.alb: Destroying... [id=sg-0a4862fa0e47544a7]
module.network.aws_subnet.public[0]: Destruction complete after 1s
module.network.aws_internet_gateway.this: Still destroying... [id=igw-0f90675b8af5ea9ba, 3m30s elapsed]
aws_security_group.alb: Destruction complete after 10s
module.network.aws_subnet.public[1]: Destruction complete after 10s
module.network.aws_internet_gateway.this: Still destroying... [id=igw-0f90675b8af5ea9ba, 3m40s elapsed]
module.network.aws_internet_gateway.this: Destruction complete after 3m44s
module.network.aws_vpc.this: Destroying... [id=vpc-034ffcb8c2316dd8f]
module.network.aws_vpc.this: Destruction complete after 0s
Apply complete! Resources: 0 added, 0 changed, 23 destroyed.
== Deleting the repository and its images
== Deleting the state bucket jr-lesson28-state-2ac15a56, every version of every file in it
== Removed backend.hcl, my-ip.auto.tfvars, the saved plan and .terraform from ./terraform
== Removing 2 image tags from your machine, and the registry login
== Anything left from Lesson 28
ec2 sgr-020d369b997337546, ec2 sgr-04eee90f7d0522370, ec2 sgr-07057a5afc9f4d61f, ec2 sgr-0a97fec3e711a07af, ecs jr-lesson28, ecs jr-lesson28-menu, ecs jr-lesson28-menu:1, ecs jr-lesson28-menu:2
(the tagging API can list things for a few minutes after they're deleted; run check again to be sure)
Terraform worked out the order, and waited when AWS wasn't ready. The internet gateway couldn't be detached while the copies still held public IP addresses, so Terraform kept trying for 3m44s until the service was gone and its addresses were released; then the subnets, the VPC, and done. In Lesson 27, that ordering and waiting took over 200 lines of the script.
The tagging API still listed eight things that were already gone. It's a separate index that catches up within minutes; python lab.py check a little later shows nothing: all clear. It's the same lesson as Lesson 27's target group: what AWS reports can lag what AWS has done.
By hand: plain Terraform, without the helper
(Your machine) Give Terraform your sign-in as short-lived keys for this terminal, then run it directly. The eval keeps the keys out of your screen and your shell history:
cd ~/Apps/aws-practice/lesson-28/terraform
eval "$(aws configure export-credentials --profile juniper-rye --format env)"
export AWS_REGION=us-east-2
terraform init -backend-config=backend.hcl
terraform fmt -recursive
terraform validate
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan
terraform output url
Change one value without editing files, and destroy at the end:
terraform plan -var image_tag=v2 -out=tfplan
terraform apply tfplan
terraform plan -destroy -out=tfplan
terraform apply tfplan
The keys from export-credentials expire with your sign-in; run the eval line again if Terraform reports expired credentials. The helper exists because Terraform's output includes your account ID and IP, which it hides.
The commands, and when to reach for them
This lesson ran Terraform through python lab.py tf, but every command is plain Terraform underneath. The ones you used, and a few you'll need soon:
Setting up and checking
terraform init -backend-config=backend.hcl: downloads providers and modules, and connects to the state. Run it again after adding a module or changing the backend;-upgrademoves providers to the newest version the code allows.terraform fmt -recursive: formats every.tffile the standard way. In a pipeline, add-check: it changes nothing, and fails if anything needs formatting.terraform validate: checks the code makes sense, without calling AWS. It catches typos and wrong types in seconds, before a slow plan.
Planning and applying
terraform plan -out=tfplan: compares code, state and AWS, and saves the proposal. Read the last line first, then search for-/+andforces replacement. The track's Reading a plan goes further.terraform show tfplan: prints a saved plan again, for reviewing one someone else made.-jsongives it to scripts.terraform apply tfplan: carries out exactly that saved plan. It's refused if the state changed since the plan was made, so it can't run stale.terraform plan -var image_tag=v2: plans with one value changed, without editing files. Good for trying things; for lasting changes, edit the code or a.tfvarsfile. See Variables and outputs.terraform plan -destroy -out=tfplan: plans deleting everything in this state. Apply the file like any other plan, so the destroy is reviewed too.
Looking at what Terraform knows
terraform output -raw url: prints one output with no quotes, for scripts likelab.py call.terraform state list: lists the address of everything in the state. The quickest answer to "what does Terraform think it manages?" See State.terraform state show aws_lb.menu: shows everything recorded about one resource, its ID, ARN and settings, without opening the console.terraform plan -refresh-only: shows drift only: what changed in AWS, without proposing to undo it.terraform console: a prompt for trying expressions. Typecidrsubnet("10.28.0.0/16", 8, 1)to see what the second subnet would be.
When something's stuck
terraform force-unlock, with the ID from the lock error: removes a lock a crashed run left behind. Only after you've checked that nothing is still running. See Remote state and working in a team.
Three commands change state without changing AWS, and deserve care. terraform state rm makes Terraform forget a resource, which then keeps running with nothing managing it. terraform state mv renames an address; a moved block in the code does the same thing reviewably, and is the better habit. terraform import, or an import block, brings something made by hand under Terraform's management. The Terraform track's State lesson covers moved and state rm; for import blocks, see the HashiCorp link in "Go deeper".
One flag to know and avoid: -target plans or applies only one resource. It exists for emergencies; used routinely, it leaves the rest of the state out of step with the code.
In real systems
- Plans run on every pull request, and applies run from a pipeline, never a laptop. The pipeline signs in to AWS with OIDC, no stored keys (Lesson 31).
- Each environment has its own state, often its own account: a bad apply in staging can't touch production.
- Modules are versioned and shared, from a registry or a Git tag, so teams reuse one tested network module instead of copying it.
- Stateful things get
prevent_destroy, and plans that replace them get a second reviewer. - Drift is checked on a schedule, with a plan that alerts if it isn't empty.
- Resources made by hand are brought in with
importblocks, and renames usemovedblocks, so Terraform doesn't destroy and recreate them. - OpenTofu is the open-source fork of Terraform, started when Terraform's license changed in 2023. The code in this lesson runs on either.
Spot the problem
Work out what's wrong before you read the explanation.
"We applied the plan we approved, and it did more." A team reviews terraform plan output on each pull request. After approval, someone runs terraform apply from their laptop. One day the apply also deletes a security group rule nobody had reviewed, because another change had been merged in between. What's wrong? terraform apply with no plan file makes a new plan at that moment, so what was reviewed and what ran were two different plans. The fix: save the plan with -out, review that file, and apply that file, from a pipeline rather than a laptop. A saved plan is refused if the state has changed since it was made, so a stale plan can't run. Then check: make a plan file, apply any other change, then apply the old file; does Terraform refuse it as stale?
Keep this
| Remember | Why |
|---|---|
| State in S3: versioned, encrypted, private | A shared record that can be rolled back |
use_lockfile = true | The second plan stopped in 1 second; no DynamoDB needed |
| Plan to a file, apply that file | What runs is what was reviewed |
Count the -/+ lines | One value would have replaced 13 resources |
| Hand changes last until the next apply | Drift was put back in 1 second |
default_tags | Every resource tagged, written once |
| Data sources for what you don't own | The repository, read but never changed |
wait_for_steady_state | Success means healthy, not just accepted |
| State is sensitive | Account ID, 39 ARNs, and any secrets |
Where you are now
Juniper & Rye's menu service is now code: about 350 lines that build 23 resources in one apply, with state in a versioned, locked S3 bucket, tags on everything, and the network as a module. You caught drift and put it back, watched the lock stop a second run, shipped v2 by changing one value, read a plan that would have rebuilt the network before it could, and destroyed it all without writing a single delete. Next, Lesson 29 uses Terraform to build an EKS cluster, where the number of parts makes a script impractical.
Check yourself
Why does the state bucket have versioning turned on?
The second plan failed in 1 second. What stopped it?
After drift, the next apply set the service back to 2 copies. What should you do if 1 copy was the right choice?
Shipping v2 showed 1 to destroy. What was destroyed?
What did the plan with vpc_cidr=10.29.0.0/16 show?
Why apply tfplan instead of running terraform apply on its own?
Why did the internet gateway take 3m44s to delete?
Key terms
- Terraform: a tool that makes infrastructure match code you write.
- State: Terraform's record of what it made, with each resource's ID and settings.
- Backend: where the state is kept; here, an S3 bucket.
- State lock: a marker that lets only one run change the state at a time; here, a
.tflockfile in S3. - Plan: what Terraform proposes to create, change or destroy, compared with what exists.
- Saved plan: a plan written to a file with
-out, applied exactly as reviewed. - Drift: a difference between what the code says and what really exists, usually from changes by hand.
- Provider: the plugin that talks to a service; here, the AWS provider.
- Data source: something Terraform reads but doesn't manage.
- Module: a reusable block of Terraform code, called with inputs, giving outputs.
default_tags: tags the AWS provider adds to every resource it creates.- Replacement: destroying a resource and making a new one, because a setting can't be changed in place.
Go deeper
- Terraform track: Reading a plan, State, Remote state and working in a team, and Modules.
- HashiCorp: the S3 backend (opens in a new tab), and the AWS provider's resources (opens in a new tab).
- HashiCorp: the lifecycle meta-argument (opens in a new tab), and import blocks (opens in a new tab).
- Try: after the first apply, add
zones = 3to the module call inmain.tfand plan it; how many resources does a third zone add, and is anything replaced? Then addlifecycle { prevent_destroy = true }to the VPC in the module and plan thevpc_cidrchange again. Destroy and rundeletewhen you're done.