The moment the course has been putting off since the very first lesson has arrived. EcoMarket's network, data and app modules have an interface, locals, tagging and semantic versioning; all they ever did was write JSON files into output/. In this lesson you replace local_file with aws_vpc, aws_subnet, aws_db_instance and aws_s3_bucket, and you get to test the claim module 4 closed with: the modules' interface does not change. base_name, cidr, zones, create_nat, tags are still the same variables; private_subnets, network, endpoint, bucket_id are still the same outputs. What changes is the back room: instead of a jsonencode(), an AWS API call that takes time, costs money and can fail.
From here on, everything you apply bills. Each section states the approximate cost and what falls within the free tier, and the lesson ends with a guided destroy and the list of what survives that destroy and keeps charging. The identifiers are fictional: the account is 123456789012 and the domain ecomarket.example.com.
- The
aws provider: region, credentials, default_tags and assume_role
aws provider: region, credentials, default_tags and assume_roleThe starting point is the versions block, with the 5.x family constraint you know from Providers:
# infra/app/versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.60" # allows 5.61, 5.99; blocks the jump to 6.0
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
}And the provider configuration. Look at it carefully: it contains not a single secret.
# infra/app/providers.tf
provider "aws" {
region = var.region # eu-west-1
profile = var.aws_profile # resolved against ~/.aws/config, outside the repo
default_tags {
tags = local.common_tags
}
}default_tags deserves a careful explanation because it changes how modules are written. It applies that map to every taggable resource this provider creates, without any module having to do anything:
| Aspect | Behaviour |
|---|---|
| Scope | Every taggable resource created by this provider instance, modules included |
| Merging | Merged with the resource's tags; the resource wins when a key matches |
| Resulting attribute | It shows up in tags_all, which is the sum of both. tags still shows only the resource's own |
| Non-taggable resources | Some associations and rules do not accept tags; default_tags simply leaves them alone |
| Effect on the plan | Adding a key to default_tags produces a ~ on every taggable resource in the state |
That last row surprises everyone the first time: changing a common tag generates a plan with 200 modifications. They are harmless (tagging is an in-place operation), but it is worth applying them as a separate change so they do not hide anything.
EcoMarket's design decision, already hinted at in 04-02, is to use both routes and keep them out of each other's way:
default_tagson the provider for the cross-cutting ones:Project,Environment,ManagedBy,CostCenter,Owner.var.tags+merge()inside each module for the specific ones:Module,ModuleVersion,Tier,Name.
The Name tag is a special case in AWS: it is not just any tag, it is the one the console displays as the resource's name. It always goes on the resource, never in default_tags.
When EcoMarket goes from one account to three — one per environment, which is the recommended separation — assume_role comes in:
provider "aws" {
region = var.region
assume_role {
role_arn = "arn:aws:iam::${var.target_account}:role/ecomarket-terraform-${var.environment}"
session_name = "tf-${var.environment}-${var.operator}"
}
default_tags {
tags = local.common_tags
}
}Security warning. The
ecomarket-terraform-prodrole can create networks, databases and IAM roles: in practice, it is an account administrator. Its trust policy must allow only the pipeline's role (and, during the transition, a small group of people with MFA). Defining it is the security team's responsibility. It is detailed in Security Best Practices.
- Pre-flight checks: identity, region and quotas
Three minutes before your first apply that are worth an afternoon of debugging:
# 1. Who am I and in which account?
aws sts get-caller-identity --profile ecomarket-lab
# {
# "UserId": "AROAEXAMPLEID:tf-dev-jcosta",
# "Account": "123456789012",
# "Arn": "arn:aws:sts::123456789012:assumed-role/ecomarket-terraform-dev/tf-dev-jcosta"
# }
# 2. Which zones are available to me in eu-west-1?
aws ec2 describe-availability-zones --region eu-west-1 \
--query 'AvailabilityZones[].ZoneName' --output text
# eu-west-1a eu-west-1b eu-west-1c
# 3. How many VPCs and elastic IPs can I have? (the two most annoying quotas)
aws service-quotas get-service-quota --service-code vpc --quota-code L-F678F1CE \
--region eu-west-1 --query 'Quota.Value'
aws service-quotas get-service-quota --service-code ec2 --quota-code L-0263D0A3 \
--region eu-west-1 --query 'Quota.Value'The elastic IP address quota (5 by default) is the one that runs out first: every NAT gateway consumes one. With three environments and two zones each, they no longer fit.
And inside the code, the equivalent data sources, which also save you from writing the zone list by hand:
# infra/app/account-data.tf
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
data "aws_partition" "current" {} # "aws", or "aws-cn"/"aws-us-gov" in special partitions
data "aws_availability_zones" "available" {
state = "available"
filter {
name = "opt-in-status"
values = ["opt-in-not-required"] # excludes local zones and regions that need activation
}
}
locals {
# The first two available zones, sorted alphabetically and therefore stable.
zones = slice(sort(data.aws_availability_zones.available.names), 0, var.zone_count)
}Three reasons to obtain the zones with a data source instead of writing them out:
- Portability between regions. The same code works in
eu-west-1(three zones) and inus-east-1(six) without touching anything. - Resilience to differences between accounts. Not every account has the same zones enabled; names like
eu-west-1aare assigned per account and do not map to the same physical data centre in two different accounts. - The
sort()is mandatory. Without it, the list order can vary between runs and would shift thefor_eachkeys. Withsort(),eu-west-1ais always first.
- The
network module: VPC and subnets with for_each over real zones
network module: VPC and subnets with for_each over real zonesThis is where the promise is kept. This is the real modules/network/main.tf, and next to it you have what was there before, for comparison:
# modules/network/main.tf — NOW (real AWS)
resource "aws_vpc" "main" {
cidr_block = var.cidr
enable_dns_support = true
enable_dns_hostnames = true # essential for RDS to resolve by name
tags = merge(local.tags, { Name = local.vpc_name })
}# BEFORE (module 4, local provider)
# resource "local_file" "vpc" {
# filename = "${path.root}/output/${local.vpc_name}.json"
# content = templatefile("${path.module}/templates/vpc.json.tftpl", { ... })
# }The locals have not changed by a single line. local.vpc_name, local.tags and local.subnets are exactly the ones you wrote in module 4. That was the argument of that lesson and it is now a verifiable fact.
enable_dns_hostnames is the attribute whose omission causes the most incidents: without it, the RDS endpoint exists but does not resolve from inside the VPC, and the application fails with a DNS error that points nowhere.
The subnets, with module 4's computed local.subnets extended to two tiers:
# modules/network/locals.tf — extended for AWS
locals {
vpc_name = "${var.base_name}-vpc"
# Private subnets: /24 blocks starting at index 0.
private_subnets = {
for i, zone in var.zones : zone => {
index = i
cidr = cidrsubnet(var.cidr, var.subnet_bits, i)
name = "${var.base_name}-priv-${zone}"
}
}
# Public subnets: offset by 100 so they do not overlap
# and leave room for future private ones.
public_subnets = {
for i, zone in var.zones : zone => {
index = i
cidr = cidrsubnet(var.cidr, var.subnet_bits, i + 100)
name = "${var.base_name}-pub-${zone}"
}
}
}The offset of 100 is a convention with a concrete reason: adding an availability zone must not change the CIDR of any existing subnet. If public and private ones were consecutive, going from two zones to three would move the first public subnet, and moving a CIDR is a destruction.
resource "aws_subnet" "private" {
for_each = local.private_subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value.cidr
availability_zone = each.key
tags = merge(local.tags, {
Name = each.value.name
Tier = "private"
})
}
resource "aws_subnet" "public" {
for_each = local.public_subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value.cidr
availability_zone = each.key
# The load balancer needs its instances to have a public IP or, better,
# the subnet to be public. This does NOT give a public IP to the app
# instances, which live in the private ones.
map_public_ip_on_launch = false
tags = merge(local.tags, {
Name = each.value.name
Tier = "public"
# Conventional tag used by Kubernetes controllers
# to discover where to place public load balancers.
"kubernetes.io/role/elb" = "1"
})
}The for_each key is the zone name, not an index. That is the difference between aws_subnet.private["eu-west-1a"] and aws_subnet.private[0], and it means that removing zone b from the list does not shift c. You saw this in 02-03; in the cloud, shifting is not a rename, it is destroying and recreating a subnet with everything inside it.
Cost of this section: zero. VPCs, subnets and route tables are free in AWS. What costs money comes next.
- Internet egress: internet gateway, NAT and route tables
flowchart TB
INET(("Internet"))
subgraph VPC["VPC 10.20.0.0/16"]
IGW["Internet Gateway<br/><b>free</b>"]
subgraph PUB["Public subnets"]
NAT["NAT Gateway<br/><b>~$33/month + data</b>"]
ALB["Load balancer"]
end
subgraph PRIV["Private subnets"]
WEB["ecomarket-web<br/>(auto scaling group)"]
BD[("PostgreSQL")]
end
RTPUB["Public route table<br/>0.0.0.0/0 → IGW"]
RTPRIV["Private route table<br/>0.0.0.0/0 → NAT"]
end
INET <--> IGW
IGW <--> ALB
IGW <--> NAT
ALB --> WEB
WEB --> BD
WEB -->|"egress:<br/>packages, APIs"| NAT
RTPUB -.-> PUB
RTPRIV -.-> PRIV
style NAT fill:#fee2e2,stroke:#dc2626
style IGW fill:#dcfce7,stroke:#16a34a
The internet gateway is free and there is one per VPC:
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = merge(local.tags, { Name = "${var.base_name}-igw" })
}The NAT gateway is the first thing in this course that costs money, and it deserves the warning in big letters:
Cost warning. A NAT gateway costs roughly $0.045/hour (~$33/month) in
eu-west-1plus $0.045 per GB processed, and it bills even when not a single byte goes through. It has no free tier. It is, by a wide margin, the resource that generates the most surprise bills in development environments. Indev, EcoMarket switches it off withcreate_nat = false; inprodit uses one per zone for high availability, which triples the cost. Any decision about NAT must go through FinOps.
# Elastic IP address: free while associated with a resource in use,
# and ~$3.6/month if left dangling. It consumes quota (5 per region by default).
resource "aws_eip" "nat" {
for_each = var.create_nat ? local.public_subnets : {}
domain = "vpc" # replaces the deprecated vpc = true
tags = merge(local.tags, { Name = "${var.base_name}-eip-nat-${each.key}" })
# The elastic IP needs the internet gateway to exist before it can be
# associated: a real dependency that no reference implies.
depends_on = [aws_internet_gateway.main]
}
resource "aws_nat_gateway" "egress" {
for_each = var.create_nat ? local.public_subnets : {}
allocation_id = aws_eip.nat[each.key].id
subnet_id = aws_subnet.public[each.key].id # in the PUBLIC one!
tags = merge(local.tags, { Name = "${var.base_name}-nat-${each.key}" })
depends_on = [aws_internet_gateway.main]
}Two details that often go wrong:
- The NAT gateway lives in a public subnet, not in the private one. It is the most repeated conceptual mistake: NAT needs internet egress in order to give it to others.
for_eachover an empty map is the switch.var.create_nat ? local.public_subnets : {}creates one NAT per zone when it is on and none when it is off. It is cleaner thancountand keeps stable per-zone keys.
The public route table, a single one for all public subnets:
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
tags = merge(local.tags, { Name = "${var.base_name}-rt-pub" })
}
resource "aws_route" "public_internet" {
route_table_id = aws_route_table.public.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
resource "aws_route_table_association" "public" {
for_each = aws_subnet.public
subnet_id = each.value.id
route_table_id = aws_route_table.public.id
}The private ones need one table per zone, because each must point at the NAT in its own zone (if another zone's NAT goes down, you do not want it dragging the rest with it):
resource "aws_route_table" "private" {
for_each = local.private_subnets
vpc_id = aws_vpc.main.id
tags = merge(local.tags, { Name = "${var.base_name}-rt-priv-${each.key}" })
}
resource "aws_route" "private_internet" {
for_each = var.create_nat ? local.private_subnets : {}
route_table_id = aws_route_table.private[each.key].id
destination_cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.egress[each.key].id
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private[each.key].id
}And an alternative that genuinely saves money, mentioned here because it is the right answer to the NAT problem in many cases: VPC endpoints. If all the private instances need is to talk to S3, a gateway-type endpoint is free and avoids NAT altogether:
resource "aws_vpc_endpoint" "s3" {
vpc_id = aws_vpc.main.id
service_name = "com.amazonaws.${var.region}.s3"
vpc_endpoint_type = "Gateway" # Gateway = free. Interface = ~$7/month per AZ
route_table_ids = [for rt in aws_route_table.private : rt.id]
tags = merge(local.tags, { Name = "${var.base_name}-vpce-s3" })
}
- Security groups: rules as resources, not as inline blocks
A security group accepts two ways of writing its rules, and only one is correct in a serious module.
# OLD FORM — inline blocks. Avoid it.
resource "aws_security_group" "web" {
name = "${var.base_name}-sg-web"
vpc_id = var.vpc_id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}# MODERN FORM — rules as independent resources. Use this one.
resource "aws_security_group" "web" {
name = "${var.base_name}-sg-web"
description = "Traffic for the EcoMarket web tier"
vpc_id = var.vpc_id
tags = merge(local.tags, { Name = "${var.base_name}-sg-web" })
lifecycle {
create_before_destroy = true
}
}
resource "aws_vpc_security_group_ingress_rule" "web_from_load_balancer" {
security_group_id = aws_security_group.web.id
description = "HTTP from the load balancer"
referenced_security_group_id = aws_security_group.load_balancer.id
from_port = 8080
to_port = 8080
ip_protocol = "tcp"
tags = merge(local.tags, { Name = "${var.base_name}-web-from-lb" })
}
resource "aws_vpc_security_group_egress_rule" "web_egress" {
security_group_id = aws_security_group.web.id
description = "Unrestricted egress for packages and APIs"
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
}Why the second form is better, point by point:
| Criterion | Inline ingress/egress blocks |
aws_vpc_security_group_*_rule |
|---|---|---|
| A rule change | Rewrites the group's entire rule set | Only the affected rule |
| Rules added outside Terraform | Terraform deletes them silently on the next apply |
It ignores them: they are not in its state |
| Extending from another module | Impossible: the group is closed | Trivial: add a rule pointing at its security_group_id |
| Per-rule tags | Do not exist | Yes: every rule is tagged and audited |
| Plan readability | "The group changes" | "Rule X is added, rule Y is removed" |
| One rule, one CIDR | A block accepts several cidr_blocks |
One per resource: more verbose, more precise |
The third row is the one that hurts most in production: with inline blocks, if somebody from security adds an emergency rule from the console, the next apply removes it without a word in the plan. With rules as resources, they coexist.
The last row is the trade-off: aws_vpc_security_group_ingress_rule accepts exactly one source. Several CIDRs means several resources, and that is where for_each does the work:
variable "admin_cidrs" {
description = "Ranges from which emergency SSH is allowed."
type = map(string)
default = {} # in dev and prod, empty: access is via SSM, not SSH
}
resource "aws_vpc_security_group_ingress_rule" "ssh_admin" {
for_each = var.admin_cidrs
security_group_id = aws_security_group.web.id
description = "SSH from ${each.key}"
cidr_ipv4 = each.value
from_port = 22
to_port = 22
ip_protocol = "tcp"
}Security warning.
cidr_ipv4 = "0.0.0.0/0"on port 22 or 3389 is the rule that compromises more servers than any other in the world. EcoMarket does not open SSH: it uses Session Manager, which needs neither an open port nor a key. Any ingress rule from0.0.0.0/0to a port other than 80 or 443 must be reviewed by the security team and justified in writing.
And a warning about create_before_destroy on security groups: it is practically mandatory. A security group cannot be deleted while a network interface is using it, so without it, any change that requires replacement gets stuck. Since the name would be duplicated during the transition, use name_prefix:
resource "aws_security_group" "web" {
name_prefix = "${var.base_name}-sg-web-" # AWS appends a unique suffix
vpc_id = var.vpc_id
lifecycle {
create_before_destroy = true
}
}
- The
app module (I): the AMI with data and the instance
app module (I): the AMI with data and the instanceLooking the image up instead of writing its identifier is mandatory: AMI identifiers are different in every region and change with every release.
# modules/app/data.tf
data "aws_ami" "base" {
most_recent = true
owners = ["099720109477"] # Canonical. A real, public identifier.
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
filter {
name = "root-device-type"
values = ["ebs"]
}
}most_recent = true is convenient and has an important trap: the value changes when Canonical publishes a new image, and since an instance's AMI is immutable, the next plan will want to replace every instance. The three strategies:
| Strategy | Code | Advantage | Drawback |
|---|---|---|---|
most_recent = true |
As above | Always the latest, patched | Surprise replacements on any plan |
| AMI pinned by variable | ami = var.ami_id with the value in the .tfvars |
Fully deterministic | Has to be updated by hand; the .tfvars differs per region |
data + ignore_changes |
most_recent + lifecycle { ignore_changes = [ami] } |
No accidental replacement | The value in state quietly ages |
The recommendation for EcoMarket: your own AMI built with Packer and pinned by version, which is the path opened up in 05-05. In the meantime, most_recent in dev and a pinned variable in prod.
The standalone instance, which EcoMarket only uses in dev as a test bastion:
resource "aws_instance" "web" {
count = var.fixed_instances # 0 in prod: there the auto scaling group is in charge
ami = data.aws_ami.base.id
instance_type = var.web_class # t3.micro: free tier 750 h/month (12 months)
subnet_id = values(var.network.private_subnets)[count.index % length(var.network.private_subnets)]
vpc_security_group_ids = [aws_security_group.web.id]
iam_instance_profile = aws_iam_instance_profile.web.name
# Metadata: IMDSv2 required. It closes the SSRF escalation path.
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 1
}
root_block_device {
volume_size = 20 # GB. gp3: ~$0.088/GB/month
volume_type = "gp3"
encrypted = true
delete_on_termination = true
}
tags = merge(local.tags, { Name = "${var.base_name}-web-${count.index}" })
lifecycle {
ignore_changes = [ami] # avoids replacements caused by a new Canonical AMI
}
}Security warning.
http_tokens = "required"(IMDSv2) is not optional. Without it, a server-side request forgery vulnerability in the application lets an attacker read the instance role's credentials with a plain HTTP request. It is the vector of the 2019 Capital One incident. Always set it.
- The
app module (II): launch template and auto scaling
app module (II): launch template and auto scalingA standalone instance does not survive a zone failure. EcoMarket uses a launch template plus an auto scaling group:
resource "aws_launch_template" "web" {
name_prefix = "${var.base_name}-web-"
image_id = data.aws_ami.base.id
instance_type = var.web_class
iam_instance_profile {
arn = aws_iam_instance_profile.web.arn
}
vpc_security_group_ids = [aws_security_group.web.id]
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
}
block_device_mappings {
device_name = "/dev/sda1"
ebs {
volume_size = 20
volume_type = "gp3"
encrypted = true
delete_on_termination = true
}
}
# Startup script. Covered in detail in 05-05.
user_data = base64encode(templatefile("${path.module}/templates/startup.sh.tftpl", {
db_endpoint = var.db_endpoint
bucket = var.bucket_id
environment = var.environment
region = var.region
}))
# Launch template tags are NOT inherited: they have to be declared
# for each type of resource the template creates.
tag_specifications {
resource_type = "instance"
tags = merge(local.tags, { Name = "${var.base_name}-web" })
}
tag_specifications {
resource_type = "volume"
tags = merge(local.tags, { Name = "${var.base_name}-web-disk" })
}
lifecycle {
create_before_destroy = true
}
}resource "aws_autoscaling_group" "web" {
name_prefix = "${var.base_name}-asg-"
min_size = var.instances.min
max_size = var.instances.max
desired_capacity = var.instances.desired
vpc_zone_identifier = values(var.network.private_subnets)
target_group_arns = [aws_lb_target_group.web.arn]
# Make the group use the load balancer's health check, not just the EC2 one:
# an instance that is powered on with the application down must be replaced.
health_check_type = "ELB"
health_check_grace_period = 180 # seconds we allow for cloud-init to boot
launch_template {
id = aws_launch_template.web.id
version = aws_launch_template.web.latest_version
}
# Gradual renewal when the template changes: replaces instances
# in a controlled way instead of letting them age.
instance_refresh {
strategy = "Rolling"
preferences {
min_healthy_percentage = 50
instance_warmup = 180
}
}
dynamic "tag" {
for_each = merge(local.tags, { Name = "${var.base_name}-web" })
content {
key = tag.key
value = tag.value
propagate_at_launch = true
}
}
lifecycle {
create_before_destroy = true
ignore_changes = [desired_capacity] # auto scaling governs it, not Terraform
}
}Four decisions that explain half of all auto scaling problems:
ignore_changes = [desired_capacity]. If auto scaling ramps up to 6 instances and Terraform has 3 written down, the nextapplywould drop it back to 3 in the middle of a traffic peak. Terraform sets the limits; auto scaling governs the instantaneous value.health_check_type = "ELB". With the default (EC2), an instance whose application has crashed but whose operating system is still alive is considered healthy forever.latest_versionversus$Latest. Referencingaws_launch_template.web.latest_versionmakes the template change show up in the plan. Using the string"$Latest"delegates the resolution to AWS and the plan stops being informative.instance_refresh. Without it, changing the launch template does not touch the existing instances: it only affects the ones born afterwards. Theapplysays "applied" and nothing has changed.
The dynamic "tag" block is the course's first real use of dynamic blocks; they are studied in depth in Dynamic Blocks. It is necessary because the auto scaling group uses repeated tag blocks instead of a tags map, and the provider's default_tags does not reach this far: the tags on instances launched by the group come from the template and from these blocks.
- The
app module (III): load balancer, target group and listener
app module (III): load balancer, target group and listenerThe application load balancer is three resources working together:
flowchart LR
C(("Client")) -->|"HTTPS 443"| L["aws_lb_listener<br/>port + protocol<br/>+ certificate"]
L -->|"default_action<br/>forward"| TG["aws_lb_target_group<br/>port 8080<br/>+ health_check"]
TG -->|"automatic registration<br/>from the ASG"| I1["instance 1"]
TG --> I2["instance 2"]
LB["aws_lb<br/>public subnets<br/>+ security group"] -.->|"contains"| L
style LB fill:#dbeafe,stroke:#2563eb
resource "aws_lb" "web" {
name = "${var.base_name}-alb"
load_balancer_type = "application"
internal = false
subnets = values(var.network.public_subnets) # public: it is the front door
security_groups = [aws_security_group.load_balancer.id]
# In prod, stops an accidental destroy from taking the front door with it.
enable_deletion_protection = var.protect_deletion
# Access logs: essential for debugging and for auditing.
access_logs {
bucket = var.logs_bucket
prefix = "alb"
enabled = var.access_logs
}
tags = merge(local.tags, { Name = "${var.base_name}-alb" })
}
resource "aws_lb_target_group" "web" {
name_prefix = "emw-" # maximum 6 characters in a target group name_prefix
port = 8080
protocol = "HTTP"
vpc_id = var.network.vpc_id
target_type = "instance"
health_check {
enabled = true
path = "/health"
protocol = "HTTP"
matcher = "200"
interval = 30
timeout = 5
healthy_threshold = 2
unhealthy_threshold = 3
}
# Draining: how long we wait for in-flight requests to finish
# before taking an instance out.
deregistration_delay = 30
tags = merge(local.tags, { Name = "${var.base_name}-tg-web" })
lifecycle {
create_before_destroy = true
}
}
resource "aws_lb_listener" "https" {
load_balancer_arn = aws_lb.web.arn
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06"
certificate_arn = var.certificate_arn # from ACM, for ecomarket.example.com
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.web.arn
}
}
# HTTP to HTTPS redirect: it serves no content, it only redirects.
resource "aws_lb_listener" "http_to_https" {
load_balancer_arn = aws_lb.web.arn
port = 80
protocol = "HTTP"
default_action {
type = "redirect"
redirect {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
}Cost warning. An application load balancer costs roughly $0.0252/hour (~$18/month) plus consumption per capacity unit (LCU), typically between $2 and $8/month at low traffic. It has no free tier and bills from minute one even if it never receives a single request. In practice sessions, create it, check it and destroy it the same day.
And a warning about names: the name of a load balancer and of a target group has a maximum of 32 characters, alphanumerics and hyphens only. ecomarket-staging-alb-web-public already goes over. Hence name_prefix with a short prefix, and hence why EcoMarket's local.prefix should be kept brief.
- IAM: the instance role and
aws_iam_policy_document
aws_iam_policy_documentThis is the section that removes credentials from the system. The instance needs to read and write to the images bucket; instead of stuffing a key into it, you give it a role.
flowchart LR
R["aws_iam_role<br/>ecomarket-dev-web"]
P["aws_iam_policy<br/>bucket access"]
A["aws_iam_role_policy_attachment"]
IP["aws_iam_instance_profile<br/>the wrapper EC2 understands"]
EC2["Instance"]
R --> A
P --> A
R --> IP
IP --> EC2
EC2 -.->|"obtains temporary<br/>credentials from IMDSv2"| R
style IP fill:#fef3c7,stroke:#d97706
The instance profile exists for a historical reason and confuses everybody: EC2 does not accept a role directly, it accepts an instance profile that contains a role. It is a one-to-one wrapper that you have to create anyway.
# Trust policy: WHO can assume this role.
data "aws_iam_policy_document" "ec2_trust" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "web" {
name = "${var.base_name}-web"
assume_role_policy = data.aws_iam_policy_document.ec2_trust.json
tags = local.tags
}
# Permissions policy: WHAT it can do.
data "aws_iam_policy_document" "bucket_access" {
statement {
sid = "ReadAndWriteImages"
effect = "Allow"
actions = [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
]
# Scope: ONLY this environment's images prefix.
resources = ["${var.bucket_arn}/images/*"]
}
statement {
sid = "ListOnlyThatPrefix"
effect = "Allow"
actions = ["s3:ListBucket"]
resources = [var.bucket_arn]
condition {
test = "StringLike"
variable = "s3:prefix"
values = ["images/*"]
}
}
statement {
sid = "ReadTheDbPassword"
effect = "Allow"
actions = ["secretsmanager:GetSecretValue"]
resources = [var.db_secret_arn]
}
}
resource "aws_iam_policy" "bucket_access" {
name = "${var.base_name}-web-access"
policy = data.aws_iam_policy_document.bucket_access.json
tags = local.tags
}
resource "aws_iam_role_policy_attachment" "bucket_access" {
role = aws_iam_role.web.name
policy_arn = aws_iam_policy.bucket_access.arn
}
# AWS-managed policy for Session Manager: console access without SSH.
resource "aws_iam_role_policy_attachment" "ssm" {
role = aws_iam_role.web.name
policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_instance_profile" "web" {
name = "${var.base_name}-web"
role = aws_iam_role.web.name
tags = local.tags
}data "aws_iam_policy_document" versus JSON in a heredoc. Both produce the same thing; the difference is one of maintenance:
| Criterion | heredoc with JSON |
aws_iam_policy_document |
|---|---|---|
| Syntax errors | Discovered at apply, as an API error |
Discovered at plan: it is validated HCL |
| Interpolating values | "${var.bucket_arn}/*" inside JSON, with fragile quoting |
Ordinary HCL expressions |
| Composition | Concatenating strings | source_policy_documents and override_policy_documents |
| Conditions | Hand-nested JSON | A readable condition block |
| Diff readability | A block of text that changes wholesale | Line by line |
| Copying from the AWS documentation | Immediate | It has to be translated |
The heredoc's only real advantage is the last one, and you pay it off once. Always use aws_iam_policy_document except to quickly paste an example policy while experimenting.
Security warning. Notice that no action uses
"*"as a resource. Ans3:*on"*"in a web instance's role means any vulnerability in the application grants access to every bucket in the account. Scoping by prefix (/images/*) and the condition ons3:prefixare the professional minimum. IAM policies are the artefact the security team reviews in most detail; they never get approved on their own.
- The
data module (I): PostgreSQL in private subnets
data module (I): PostgreSQL in private subnetsPostgreSQL needs two prior resources: a subnet group telling it which zones it can live in, and a security group that only accepts traffic from the web tier.
resource "aws_db_subnet_group" "main" {
name = "${var.base_name}-db"
subnet_ids = values(var.subnets) # private, at least two zones
tags = merge(local.tags, { Name = "${var.base_name}-db" })
}
resource "aws_security_group" "db" {
name_prefix = "${var.base_name}-sg-db-"
description = "Access to EcoMarket's PostgreSQL"
vpc_id = var.vpc_id
tags = merge(local.tags, { Name = "${var.base_name}-sg-db" })
lifecycle { create_before_destroy = true }
}
# Only the web tier can talk to the database. By group, not by CIDR.
resource "aws_vpc_security_group_ingress_rule" "db_from_web" {
security_group_id = aws_security_group.db.id
referenced_security_group_id = var.web_sg_id
description = "PostgreSQL from the web tier"
from_port = 5432
to_port = 5432
ip_protocol = "tcp"
}Referencing the source security group instead of a CIDR is the correct practice: it keeps working if the subnets change range, and it expresses the intent ("the web can talk to the database") rather than an addressing detail.
And the database:
resource "aws_db_instance" "main" {
identifier = "${var.base_name}-postgres"
engine = "postgres"
engine_version = var.engine_version # "16.3"
instance_class = var.db_class # db.t3.micro: free tier 750 h/month (12 months)
allocated_storage = var.storage_gb # 20 GB in the free tier
max_allocated_storage = var.max_storage_gb # disk autoscaling
storage_type = "gp3"
storage_encrypted = true # ALWAYS. It costs nothing
kms_key_id = var.kms_key_arn # null uses the AWS-managed key
db_name = "ecomarket"
username = var.db_user
password = var.db_password # sensitive, from TF_VAR_db_password
db_subnet_group_name = aws_db_subnet_group.main.name
vpc_security_group_ids = [aws_security_group.db.id]
publicly_accessible = false # NEVER true. See the warning
multi_az = var.high_availability
backup_retention_period = var.retention_days # 0 = no backups. Never 0 in prod
backup_window = "02:00-03:00" # UTC, outside peak hours
maintenance_window = "sun:03:30-sun:04:30"
copy_tags_to_snapshot = true
# The two most dangerous attributes in the module. See the table below.
deletion_protection = var.protect_deletion
skip_final_snapshot = !var.protect_deletion
final_snapshot_identifier = var.protect_deletion ? "${var.base_name}-final-${formatdate("YYYYMMDDhhmmss", timestamp())}" : null
auto_minor_version_upgrade = true
apply_immediately = var.environment != "prod" # in prod, within the window
performance_insights_enabled = var.environment == "prod"
enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]
tags = merge(local.tags, { Name = "${var.base_name}-postgres" })
lifecycle {
ignore_changes = [
# The password can be rotated outside Terraform (see section 11).
password,
# The minor version updates itself through auto_minor_version_upgrade.
engine_version,
]
}
}The two dangerous attributes, with their truth table:
skip_final_snapshot |
deletion_protection |
What happens on terraform destroy |
|---|---|---|
true |
false |
The database is deleted with no backup. The data is lost forever |
false |
false |
A final snapshot is taken (it takes 5-20 min) and then it is deleted. The snapshot survives and bills |
| either | true |
The destroy fails, halfway, after destroying other things |
EcoMarket's configuration is deliberate: in dev, skip_final_snapshot = true and deletion_protection = false, because we want to be able to destroy quickly and the data is test data. In prod, exactly the opposite. The expression !var.protect_deletion ties them together so they cannot drift apart.
Cost and data warning.
db.t3.microwith 20 GB is in the free tier for the account's first 12 months (750 h/month, a single instance). Outside that tier, it runs at around $13/month;db.t3.smallaround $26/month; andmulti_az = truedoubles the price. Backups are free up to the size of the database and charged above it. And the serious warning:skip_final_snapshot = truein an environment with real data is an irreversible loss. The combination of the three deletion attributes must be reviewed by the security team and written into company policy, not decided by default.
Security warning.
publicly_accessible = trueputs your database on the Internet. There are thousands of PostgreSQL instances exposed that way right now, and scanners find them within minutes. EcoMarket keeps it in private subnets, reachable only from the web's security group, and human access goes through a Session Manager tunnel.
- The
data module (II): the password and Secrets Manager
data module (II): the password and Secrets ManagerSo far the password travels through TF_VAR_db_password, as decided in module 2:
export TF_VAR_db_password="$(pass ecomarket/dev/db)" # from a manager, never typed out
terraform apply -var-file=dev.tfvarsThat solves the problem of not having it in the code, but leaves two open: it is still in the tfstate in the clear (you have known that since 03-01) and somebody has to hand it to the application. The complete solution is for Terraform to generate the password, store it in Secrets Manager and have the application read it with its role:
resource "random_password" "db" {
length = 32
special = true
# Characters RDS rejects in the master password.
override_special = "!#$%&*()-_=+[]{}<>:?"
}
resource "aws_secretsmanager_secret" "db" {
name = "${var.base_name}/db/master"
description = "EcoMarket PostgreSQL credentials for ${var.environment}"
kms_key_id = var.kms_key_arn
# In dev, 0 allows recreating the secret with the same name immediately.
# In prod, a 30-day recovery window.
recovery_window_in_days = var.environment == "prod" ? 30 : 0
tags = local.tags
}
resource "aws_secretsmanager_secret_version" "db" {
secret_id = aws_secretsmanager_secret.db.id
secret_string = jsonencode({
username = var.db_user
password = random_password.db.result
host = aws_db_instance.main.address
port = aws_db_instance.main.port
dbname = aws_db_instance.main.db_name
engine = "postgres"
})
}And the database uses random_password.db.result instead of var.db_password.
An honest comparison of the three options, because none of them is perfect:
| Option | The secret in state | Who knows it | Rotation | Complexity |
|---|---|---|---|---|
TF_VAR_db_password |
Yes, in the clear | Whoever applies, the password manager, the state | Manual | Minimal |
random_password + Secrets Manager |
Yes, in the clear (the generated value) | Nobody: no human ever sees it | By recreating the random_password |
Medium |
RDS-managed (manage_master_user_password) |
No | Nobody. AWS manages it | Automatic, by AWS | Low |
The third deserves attention because it is the one that genuinely solves the state problem:
resource "aws_db_instance" "main" {
# ...
manage_master_user_password = true
master_user_secret_kms_key_id = var.kms_key_arn
# And username-password are OMITTED: there is no password attribute.
}
output "db_secret_arn" {
description = "ARN of the RDS-managed secret holding the master password."
value = aws_db_instance.main.master_user_secret[0].secret_arn
}With this, the password never exists in the state nor in any file: RDS generates it, stores it in Secrets Manager and rotates it. It is the recommended option for prod at EcoMarket, and the course's var.db_password is kept in dev because it illustrates how sensitive variables are handled.
Cost warning. Secrets Manager costs $0.40 per secret per month plus $0.05 per 10,000 API calls. With five secrets that is $2/month: not much, but not zero, and there is no permanent free tier (there is a 30-day trial). The cheap alternative for non-critical values is Parameter Store, whose standard tier is free.
- The
data module (III): the images bucket and its satellite resources
data module (III): the images bucket and its satellite resourcesThere is a design change in the AWS provider here that is worth understanding before writing anything. Up to version 4, aws_s3_bucket contained blocks for versioning, encryption, lifecycle and everything else. Since version 4, each aspect is a separate resource.
| Before (provider ≤ 3.x) | Now (4.x and 5.x) |
|---|---|
versioning { enabled = true } |
aws_s3_bucket_versioning |
server_side_encryption_configuration { ... } |
aws_s3_bucket_server_side_encryption_configuration |
lifecycle_rule { ... } |
aws_s3_bucket_lifecycle_configuration |
acl = "private" |
aws_s3_bucket_acl (and, better still, do not use ACLs) |
logging { ... } |
aws_s3_bucket_logging |
policy = "..." |
aws_s3_bucket_policy |
| — (did not exist) | aws_s3_bucket_public_access_block |
The reason for the change is a good one: with everything inside a single resource, two teams could not manage different aspects of the same bucket, and any change rewrote the entire configuration. The practical consequence is that a well-configured bucket is six or seven resources, and anybody arriving from an old tutorial finds their code does not work.
resource "aws_s3_bucket" "images" {
# The name is GLOBALLY unique across all of AWS: hence the random suffix.
bucket = "${var.base_name}-images-${var.suffix}"
# Last safety net: stops a bucket with contents from being destroyed.
force_destroy = var.environment == "dev"
tags = merge(local.tags, { Name = "${var.base_name}-images" })
}
# 1. Public access block. FIRST, ALWAYS.
resource "aws_s3_bucket_public_access_block" "images" {
bucket = aws_s3_bucket.images.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# 2. Versioning: protects against deletions and malicious encryption.
resource "aws_s3_bucket_versioning" "images" {
bucket = aws_s3_bucket.images.id
versioning_configuration {
status = "Enabled"
}
}
# 3. Encryption at rest.
resource "aws_s3_bucket_server_side_encryption_configuration" "images" {
bucket = aws_s3_bucket.images.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = var.kms_key_arn != null ? "aws:kms" : "AES256"
kms_master_key_id = var.kms_key_arn
}
# Dramatically reduces the cost of KMS calls by reusing the data key.
bucket_key_enabled = var.kms_key_arn != null
}
}
# 4. Object ownership: disables ACLs entirely.
resource "aws_s3_bucket_ownership_controls" "images" {
bucket = aws_s3_bucket.images.id
rule {
object_ownership = "BucketOwnerEnforced"
}
}
# 5. Lifecycle: moves old data to cheaper classes and cleans up versions.
resource "aws_s3_bucket_lifecycle_configuration" "images" {
bucket = aws_s3_bucket.images.id
rule {
id = "transition-old-images"
status = "Enabled"
filter {
prefix = "images/"
}
transition {
days = 90
storage_class = "STANDARD_IA" # ~45 % cheaper, with a retrieval cost
}
transition {
days = 365
storage_class = "GLACIER_IR"
}
}
rule {
id = "clean-old-versions"
status = "Enabled"
filter {}
noncurrent_version_expiration {
noncurrent_days = 30
}
# Cleans up aborted multipart uploads: a very common invisible cost.
abort_incomplete_multipart_upload {
days_after_initiation = 7
}
}
}That last rule deserves a comment: incomplete multipart uploads take up space and bill indefinitely, and they are invisible when you list the bucket. It is one of the most common sources of phantom spend; seven lines eliminate it.
And the bucket policy, which enforces encryption in transit:
data "aws_iam_policy_document" "images" {
statement {
sid = "DenyWithoutTLS"
effect = "Deny"
principals {
type = "*"
identifiers = ["*"]
}
actions = ["s3:*"]
resources = [
aws_s3_bucket.images.arn,
"${aws_s3_bucket.images.arn}/*",
]
condition {
test = "Bool"
variable = "aws:SecureTransport"
values = ["false"]
}
}
}
resource "aws_s3_bucket_policy" "images" {
bucket = aws_s3_bucket.images.id
policy = data.aws_iam_policy_document.images.json
# The public access block must exist BEFORE the policy, or the API rejects it.
depends_on = [aws_s3_bucket_public_access_block.images]
}That depends_on is a perfect example of a real dependency that no reference implies: the policy does not mention the public access block, but S3 rejects policies on buckets without it configured if its analysis decides they could open up public access.
Cost warning. S3 Standard costs ~$0.023/GB/month in
eu-west-1, plus ~$0.005 per 1,000 PUT requests and ~$0.0004 per 1,000 GETs. The free tier gives you 5 GB, 20,000 GETs and 2,000 PUTs for 12 months. An empty bucket costs nothing, so it is the safest resource to practise with. What does cost money and surprises people: outbound transfer to the Internet (~$0.09/GB) and accumulated old versions.
- The complete root and the
endpoints output
endpoints outputThis is how infra/app/main.tf ends up. Compare it with module 4's: it is the same file. The module calls have not changed.
# infra/app/main.tf
locals {
prefix = "${var.project}-${var.environment}"
current = var.environments[var.environment]
common_tags = merge(
{
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
},
local.current.extra_tags,
)
}
resource "random_pet" "suffix" {
length = 2
}
module "network" {
source = "ecomarket/ecomarket-network/aws"
version = "~> 3.0" # 3.0.0: the MAJOR that swapped local_file for AWS
base_name = local.prefix
cidr = local.current.cidr
zones = local.zones # from data.aws_availability_zones
create_nat = local.current.create_nat
tags = local.common_tags
}
module "data" {
source = "ecomarket/ecomarket-data/aws"
version = "~> 3.0"
base_name = local.prefix
suffix = random_pet.suffix.id
vpc_id = module.network.vpc_id
subnets = module.network.private_subnets
web_sg_id = module.app.web_sg_id
db_class = local.current.db_class
high_availability = local.current.multi_az
retention_days = local.current.retention_days
protect_deletion = local.current.protect_deletion
db_password = var.db_password
tags = local.common_tags
}
module "app" {
source = "ecomarket/ecomarket-app/aws"
version = "~> 3.0"
base_name = local.prefix
suffix = random_pet.suffix.id
network = module.network.network
db_endpoint = module.data.endpoint
bucket_id = module.data.bucket_id
bucket_arn = module.data.bucket_arn
db_secret_arn = module.data.db_secret_arn
instances = local.current.web_instances
web_class = local.current.web_class
certificate_arn = var.certificate_arn
tags = local.common_tags
}
output "endpoints" {
description = "The platform's entry points, for the application team."
value = {
web = "https://${module.app.load_balancer_dns}"
db = module.data.endpoint
bucket = module.data.bucket_name
vpc = module.network.vpc_id
environment = var.environment
region = var.region
}
}The only thing that has changed compared with module 4 is three items, and none of them affects the shape of the code:
- The
sourcepoints at the registry and the version is~> 3.0, because changing a module's underlying provider is a MAJOR: it destroys everything that came before. That is exactly what the semantic versioning table in 04-05 dictated. - There are two new variables (
certificate_arn,web_sg_id) and two new outputs. Adding optional variables and outputs is MINOR. local.zonescomes from adatasource instead of a variable.
And the endpoints output, run for real:
{
"bucket": "ecomarket-dev-images-brave-otter",
"db": "ecomarket-dev-postgres.abc123xyz.eu-west-1.rds.amazonaws.com:5432",
"environment": "dev",
"region": "eu-west-1",
"vpc": "vpc-0a1b2c3d4e5f67890",
"web": "https://ecomarket-dev-alb-1234567890.eu-west-1.elb.amazonaws.com"
}That last line is the difference between four modules of simulation and a platform: it is a URL that responds.
- Cost of what was deployed and the free tier
A monthly estimate for an EcoMarket dev environment exactly as described, in eu-west-1, with test traffic. Indicative figures from the time of writing; always verify with the official calculator.
| Resource | Quantity | Approx. monthly cost | Free tier? |
|---|---|---|---|
| VPC, subnets, route tables, IGW | 1 set | $0 | Always free |
| Security groups and rules | ~10 | $0 | Always free |
| S3 VPC endpoint (Gateway) | 1 | $0 | Always free |
| NAT gateway | 1 | ~$33 + $0.045/GB | No. Can be switched off with create_nat = false |
| Associated elastic IP address | 1 | $0 (associated) / ~$3.6 (dangling) | Consumes quota |
| Application load balancer | 1 | ~$18 + LCU (~$2-8) | No |
t3.micro instance |
1-2 | ~$8 each | Yes: 750 h/month, 12 months |
| 20 GB gp3 disk | 1-2 | ~$1.8 each | Yes: 30 GB, 12 months |
RDS db.t3.micro, 20 GB |
1 | ~$13 | Yes: 750 h/month, 12 months, single-AZ |
| RDS backups | 20 GB | $0 up to the size of the DB | Included |
| S3 bucket (2 GB, low traffic) | 1 | ~$0.05 | Yes: 5 GB, 12 months |
| Secrets Manager secret | 1 | $0.40 | 30-day trial only |
| CloudWatch logs | ~1 GB | ~$0.55 | Yes: 5 GB |
Estimated dev TOTAL with NAT |
~$55-70/month | ||
Estimated dev TOTAL without NAT or ALB |
~$1-3/month (with the free tier) |
The final two rows are this section's entire lesson. The difference between practising for one euro and practising for seventy is two resources: the NAT gateway and the load balancer. For learning, both are expendable: one instance in a public subnet with an assigned IP is enough to verify that everything else works.
The recommended practice configuration, in dev.tfvars:
# dev.tfvars — minimum-cost configuration for practising
environment = "dev"
environments = {
dev = {
cidr = "10.20.0.0/16"
create_nat = false # ← saves ~$33/month
web_instances = { min = 0, max = 1, desired = 1 }
web_class = "t3.micro" # free tier
db_class = "db.t3.micro" # free tier
multi_az = false # would double the price
retention_days = 0 # no backups: it is a lab
protect_deletion = false # we want to be able to destroy
extra_tags = { CostCenter = "CC-LAB" }
}
}FinOps warning. These figures are for one environment. EcoMarket has three, and
prodwith per-zone NAT, Multi-AZ anddb.t3.mediumcomfortably exceeds $400/month. Production sizing is a conversation with FinOps before it is written into a.tfvars, not after the bill arrives. And a budget alert on the account is mandatory before the firstapply.
- A guided
terraform destroy and what survives it
terraform destroy and what survives itdestroy runs in the reverse order of apply and has problems of its own:
# 1. See what is going to be destroyed, without destroying anything
terraform plan -destroy -var-file=dev.tfvars -out=destroy.tfplan
terraform show destroy.tfplan | grep -c "will be destroyed"
# 2. Run it
terraform apply destroy.tfplanExpected timings: between 8 and 20 minutes, dominated by the database (3-8 min) and the load balancer (2-5 min).
The four classic destroy failures and how to fix them:
| Failure | Typical message | Cause | Fix |
|---|---|---|---|
| Protected database | Cannot delete protected DB Instance |
deletion_protection = true |
A prior apply setting it to false |
| Bucket with contents | BucketNotEmpty |
S3 does not delete buckets with objects | force_destroy = true + apply, or empty it by hand |
| VPC that will not go | DependencyViolation |
Something created outside Terraform is using it | Find orphaned network interfaces and delete them |
| Blocked security group | DependencyViolation |
A network interface that still exists is using it | Wait; it usually resolves once the load balancer is gone |
The third deserves detail because it is the most baffling: a VPC will not be deleted if it has anything inside it, whether Terraform created it or not. A Lambda function attached to the VPC, an endpoint created by hand or an instance launched from the console all block the destroy indefinitely. To find the culprit:
VPC=vpc-0a1b2c3d4e5f67890
# Network interfaces still in the VPC: almost always the culprit
aws ec2 describe-network-interfaces \
--filters Name=vpc-id,Values=$VPC \
--query 'NetworkInterfaces[].{ID:NetworkInterfaceId,Desc:Description,State:Status}' \
--output tableAnd the most important thing in this lesson: what survives the destroy and keeps costing money.
| Survives | Why | Cost | How to check it |
|---|---|---|---|
| RDS final snapshot | Created on purpose if skip_final_snapshot = false |
~$0.095/GB/month | aws rds describe-db-snapshots --snapshot-type manual |
| Manual snapshots | Terraform never manages them | ~$0.095/GB/month | The same |
| Buckets with contents | destroy fails without force_destroy; if it was removed from state, it is orphaned |
~$0.023/GB/month | aws s3 ls |
| Old object versions | Versioning keeps them even when you delete the object | Same as the object | aws s3api list-object-versions --bucket X |
| CloudWatch logs | Log groups outlive the resource that generated them | ~$0.55/GB/month stored | aws logs describe-log-groups |
| Secrets Manager secrets | With recovery_window_in_days > 0 they sit in scheduled deletion |
$0.40/month each | aws secretsmanager list-secrets --include-planned-deletion |
| Dangling elastic IP addresses | If they were disassociated and left outside the state | ~$3.6/month | aws ec2 describe-addresses |
| EBS snapshots | Never managed if they were created by hand | ~$0.05/GB/month | aws ec2 describe-snapshots --owner-ids self |
The complete cleanup script, to run after every practice session:
#!/usr/bin/env bash
# scripts/practice-cleanup.sh
set -euo pipefail
REGION=eu-west-1
echo "== 1. Terraform state =="
terraform state list || echo " (empty)"
echo "== 2. Resources tagged as ecomarket =="
aws resourcegroupstaggingapi get-resources --region $REGION \
--tag-filters Key=Project,Values=ecomarket \
--query 'ResourceTagMappingList[].ResourceARN' --output table
echo "== 3. What carries NO tag and does bill =="
aws ec2 describe-addresses --region $REGION \
--query 'Addresses[?AssociationId==null].PublicIp' --output table
aws rds describe-db-snapshots --region $REGION --snapshot-type manual \
--query 'DBSnapshots[].{ID:DBSnapshotIdentifier,GB:AllocatedStorage}' --output table
aws ec2 describe-snapshots --region $REGION --owner-ids self \
--query 'Snapshots[].{ID:SnapshotId,GB:VolumeSize}' --output table
aws secretsmanager list-secrets --region $REGION --include-planned-deletion \
--query 'SecretList[].Name' --output table
aws s3 lsSave it, run it and read it in full after every destroy. It is the difference between learning AWS for two euros a month and discovering a bill for forty.
Common Mistakes and Tips
Putting the NAT gateway in a private subnet. It does not work and the error does not say so clearly: NAT needs internet egress in order to provide it. It always goes in a public subnet.
Forgetting enable_dns_hostnames = true on the VPC. The RDS endpoint exists but does not resolve from inside. The application fails with a DNS error that points nowhere near the VPC.
Using inline ingress/egress blocks. Any rule added from the console disappears on the next apply, without showing up in the plan. Use aws_vpc_security_group_ingress_rule.
A security group without create_before_destroy or name_prefix. Any change requiring replacement gets stuck because a group in use cannot be deleted. Always both together.
Referencing CIDRs instead of security groups. It works until the subnets change. Referencing the source group expresses the intent and survives addressing changes.
most_recent = true on the AMI without ignore_changes. The day Canonical publishes an image, the plan wants to replace every instance. In prod, pin the AMI by variable or build it with Packer.
Not setting http_tokens = "required". It leaves the escalation path open from an SSRF vulnerability to the instance role's credentials. It is the default setting that has caused the most incidents.
Leaving desired_capacity without ignore_changes. The next apply undoes auto scaling, typically at the worst possible moment.
Changing the launch template and expecting the instances to change. They do not change without instance_refresh. The apply says "done" and everything stays the same.
skip_final_snapshot = true in an environment with data. Irreversible loss. Tie it to the same variable as deletion_protection so they cannot drift apart.
publicly_accessible = true on RDS. A database on the Internet. Scanners take minutes to find it.
Writing IAM policies as JSON in a heredoc. The errors surface at apply, not at plan, and the interpolations are fragile. aws_iam_policy_document, always.
Expecting aws_s3_bucket to configure versioning. Since provider version 4 they are separate resources. A well-configured bucket is six or seven resources.
Forgetting abort_incomplete_multipart_upload. Invisible space that bills forever.
Tip: start with the network, in dev, with create_nat = false. It is free, it takes less than a minute and it validates half the code. The load balancer and the database come afterwards.
Tip: enable IAM Access Analyzer and security checks in the pipeline. tfsec, checkov or trivy catch an unencrypted bucket or an open port 22 before it exists. It is integrated in 08-01.
Tip: any change to IAM, to ingress rules or to encryption is reviewed with security; any change that adds an hourly-cost resource is reviewed with FinOps. Write it into the pull request template so it does not depend on somebody remembering.
Exercises
Exercise 1: deploy EcoMarket's network (cost ~$0)
Create a minimal configuration that deploys only the network, without NAT, and verify it:
- Write
versions.tfandproviders.tfwith theawsprovider constrained to~> 5.60, regioneu-west-1, profile by variable anddefault_tagswithProject,EnvironmentandManagedBy. - Obtain the zones with
data "aws_availability_zones"and keep the first two, sorted. - Create the
10.20.0.0/16VPC with DNS enabled, one private and one public subnet per zone (use the offset of 100 for the public ones), the internet gateway and the route tables with their associations. No NAT gateway. - Add a Gateway-type VPC endpoint for S3 associated with the private tables.
- Publish the outputs
vpc_id,private_subnets,public_subnetsand the composite objectnetwork. - Apply, check with the CLI that the subnets are in the right zones, and destroy.
Note how long the apply takes and how long the destroy takes.
Exercise 2: auditing a production plan
The following extract from EcoMarket's prod plan arrives for your review:
# module.data.aws_db_instance.main must be replaced
-/+ resource "aws_db_instance" "main" {
~ availability_zone = "eu-west-1a" -> (known after apply)
~ db_subnet_group_name = "ecomarket-prod-db" -> "ecomarket-prod-db-v2" # forces replacement
~ endpoint = "ecomarket-prod-postgres.abc.eu-west-1.rds.amazonaws.com" -> (known after apply)
skip_final_snapshot = true
~ id = "ecomarket-prod-postgres" -> (known after apply)
# (28 unchanged attributes hidden)
}
# module.app.aws_security_group.web will be updated in-place
~ resource "aws_security_group" "web" {
id = "sg-0abc123"
~ tags = { ... }
}
Plan: 1 to add, 1 to change, 1 to destroy.- Which attribute triggers the replacement, and why can it not be changed in place?
- Identify the critical finding in this extract that has nothing to do with the replacement.
- Write your review verdict: approved, approved with conditions, or rejected? Justify it with three points.
- Propose the alternative that achieves the same goal without replacing the database.
- Write the
jqcheck that would have stopped this plan reaching human review.
Exercise 3: designing the web's access to the bucket without credentials
The ecomarket-web application has to upload and read images from the bucket, and read the PostgreSQL password. Write, without deploying:
- The trust policy and the instance role, with
aws_iam_policy_document. - The permissions policy with the least privilege possible: only the
images/prefix, only the necessary actions, and thes3:prefixcondition on the listing. - The instance profile and its association with the
aws_launch_template. - The instance metadata configuration that prevents SSRF escalation.
- A table comparing this solution with the two bad alternatives: an access key in
user_dataand an access key in an application environment variable. Compare on four axes: where the secret lives, rotation, blast radius if the application is vulnerable, and auditability.
Solution 1
The complete configuration, in four files:
# versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
}
}
# providers.tf
provider "aws" {
region = var.region
profile = var.aws_profile
default_tags {
tags = {
Project = "ecomarket"
Environment = var.environment
ManagedBy = "terraform"
}
}
}# main.tf
data "aws_availability_zones" "available" {
state = "available"
filter {
name = "opt-in-status"
values = ["opt-in-not-required"]
}
}
locals {
prefix = "ecomarket-${var.environment}"
zones = slice(sort(data.aws_availability_zones.available.names), 0, 2)
private = { for i, z in local.zones : z => cidrsubnet(var.cidr, 8, i) }
public = { for i, z in local.zones : z => cidrsubnet(var.cidr, 8, i + 100) }
}
resource "aws_vpc" "main" {
cidr_block = var.cidr
enable_dns_support = true
enable_dns_hostnames = true
tags = { Name = "${local.prefix}-vpc" }
}
resource "aws_subnet" "private" {
for_each = local.private
vpc_id = aws_vpc.main.id
cidr_block = each.value
availability_zone = each.key
tags = { Name = "${local.prefix}-priv-${each.key}", Tier = "private" }
}
resource "aws_subnet" "public" {
for_each = local.public
vpc_id = aws_vpc.main.id
cidr_block = each.value
availability_zone = each.key
tags = { Name = "${local.prefix}-pub-${each.key}", Tier = "public" }
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = { Name = "${local.prefix}-igw" }
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
tags = { Name = "${local.prefix}-rt-pub" }
}
resource "aws_route" "public_internet" {
route_table_id = aws_route_table.public.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
resource "aws_route_table_association" "public" {
for_each = aws_subnet.public
subnet_id = each.value.id
route_table_id = aws_route_table.public.id
}
resource "aws_route_table" "private" {
for_each = local.private
vpc_id = aws_vpc.main.id
tags = { Name = "${local.prefix}-rt-priv-${each.key}" }
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private[each.key].id
}
resource "aws_vpc_endpoint" "s3" {
vpc_id = aws_vpc.main.id
service_name = "com.amazonaws.${var.region}.s3"
vpc_endpoint_type = "Gateway"
route_table_ids = [for rt in aws_route_table.private : rt.id]
tags = { Name = "${local.prefix}-vpce-s3" }
}# outputs.tf
output "vpc_id" { value = aws_vpc.main.id }
output "private_subnets" { value = { for z, s in aws_subnet.private : z => s.id } }
output "public_subnets" { value = { for z, s in aws_subnet.public : z => s.id } }
output "network" {
value = {
vpc_id = aws_vpc.main.id
cidr = aws_vpc.main.cidr_block
private_subnets = { for z, s in aws_subnet.private : z => s.id }
public_subnets = { for z, s in aws_subnet.public : z => s.id }
zones = local.zones
}
}Verification and cleanup:
terraform init && terraform apply -auto-approve
# The subnets are where they should be
aws ec2 describe-subnets --region eu-west-1 \
--filters Name=vpc-id,Values=$(terraform output -raw vpc_id) \
--query 'Subnets[].{CIDR:CidrBlock,AZ:AvailabilityZone,Name:Tags[?Key==`Name`]|[0].Value}' \
--output table
terraform destroy -auto-approveExpected timings: apply between 30 and 60 seconds (the VPC and the endpoint are the slowest parts); destroy between 40 and 90 seconds. Cost: $0. Everything in this exercise is free in AWS, which is why it is the right exercise to start with.
Solution 2
1. The attribute that triggers the replacement is db_subnet_group_name. Changing the subnet group of an existing RDS instance is not an in-place operation because it determines which subnets and zones the database physically lives in: moving it means recreating it. It is analogous to changing a subnet's availability zone.
2. The critical finding is skip_final_snapshot = true in production. Combined with the replacement on the line above, it means this plan destroys the production database with no final snapshot. The data is lost irreversibly. It is a maximum-severity finding that takes priority over everything else in the plan. A secondary finding: deletion_protection does not appear among the visible attributes, which suggests it is false in production, when it should be true.
3. Verdict: rejected. Three reasons:
- It destroys production data with no backup (
skip_final_snapshot = truealongside a replacement in the plan). That alone is enough to reject it. - Replacing the database means 10-25 minutes of downtime that has not been announced and has no agreed window.
- The production configuration is wrong regardless of this change:
skip_final_snapshotmust befalseanddeletion_protectiontrueinprod, both tied tovar.protect_deletion. That fix belongs in a prior, separate change.
4. The alternative without replacement. The real goal was almost certainly to add subnets to the group (for a third zone, for instance). That does not require a new group: aws_db_subnet_group allows its subnet_ids list to be modified in place. Adding the subnet to the existing group would have been enough. If the change genuinely were a rename, the right instrument is a moved block, which changes the address in the state without touching the infrastructure:
And if the resource's name in AWS really must change, the safe path is: an apply that sets deletion_protection = true and skip_final_snapshot = false, a verified manual snapshot, an announced maintenance window, and a restore from the snapshot. Not a -/+ in some routine plan.
5. The jq check that would have stopped it before human review:
# Fails if the plan destroys anything in prod, or if any DB has skip_final_snapshot.
terraform show -json plan.tfplan > plan.json
destroyed=$(jq '[.resource_changes[] | select(.change.actions | index("delete"))] | length' plan.json)
no_snapshot=$(jq '[.resource_changes[]
| select(.type == "aws_db_instance")
| select(.change.after.skip_final_snapshot == true)] | length' plan.json)
if [[ "$destroyed" -gt 0 ]]; then
echo "BLOCKED: $destroyed resource(s) destroyed in prod"; exit 1
fi
if [[ "$no_snapshot" -gt 0 ]]; then
echo "BLOCKED: there are RDS instances with skip_final_snapshot=true"; exit 1
fiThe second check is more valuable than the first because it detects the dangerous configuration even when today's plan destroys nothing. The day somebody changes an immutable attribute, the bomb will already have been defused.
Solution 3
1 and 2. Role and policy with least privilege:
data "aws_iam_policy_document" "ec2_trust" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "web" {
name = "${local.prefix}-web"
assume_role_policy = data.aws_iam_policy_document.ec2_trust.json
tags = local.tags
}
data "aws_iam_policy_document" "web" {
statement {
sid = "ImageObjects"
effect = "Allow"
actions = [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
]
resources = ["${aws_s3_bucket.images.arn}/images/*"]
}
statement {
sid = "ListOnlyImages"
effect = "Allow"
actions = ["s3:ListBucket"]
resources = [aws_s3_bucket.images.arn]
condition {
test = "StringLike"
variable = "s3:prefix"
values = ["images/*"]
}
}
statement {
sid = "DbPassword"
effect = "Allow"
actions = ["secretsmanager:GetSecretValue"]
resources = [aws_secretsmanager_secret.db.arn]
}
# If the bucket uses KMS, permission on the key is needed, and only for S3.
statement {
sid = "DecryptS3Objects"
effect = "Allow"
actions = ["kms:Decrypt", "kms:GenerateDataKey"]
resources = [var.kms_key_arn]
condition {
test = "StringEquals"
variable = "kms:ViaService"
values = ["s3.${var.region}.amazonaws.com"]
}
}
}
resource "aws_iam_policy" "web" {
name = "${local.prefix}-web"
policy = data.aws_iam_policy_document.web.json
}
resource "aws_iam_role_policy_attachment" "web" {
role = aws_iam_role.web.name
policy_arn = aws_iam_policy.web.arn
}The fourth statement is the one almost everybody forgets: with KMS encryption, reading an object from S3 requires permission on the key, not just on the bucket. The kms:ViaService condition limits that permission to operations that go through S3, so the role cannot decrypt anything else with that key.
3. Instance profile and association:
resource "aws_iam_instance_profile" "web" {
name = "${local.prefix}-web"
role = aws_iam_role.web.name
}
resource "aws_launch_template" "web" {
# ...
iam_instance_profile {
arn = aws_iam_instance_profile.web.arn
}
}4. Metadata against SSRF:
metadata_options {
http_endpoint = "enabled"
http_tokens = "required" # IMDSv2: requires a prior PUT to obtain a token
http_put_response_hop_limit = 1 # the token does not survive a network hop
}http_tokens = "required" forces a PUT request with a special header to obtain a token before anything can be read. A typical SSRF vulnerability only lets an attacker trigger plain GET requests, so it cannot complete the exchange. http_put_response_hop_limit = 1 additionally stops a container on the instance from reaching the metadata.
5. Comparison of the three solutions:
| Axis | Instance role (correct) | Key in user_data |
Key in an environment variable |
|---|---|---|---|
| Where the secret lives | There is no secret: temporary credentials generated on the fly by IMDSv2 | In the instance metadata, in the clear and readable by anybody on the machine, and in the tfstate |
In the instance's file system or process manager; probably also in the deployment repository |
| Rotation | Automatic every few hours, with no intervention | Manual: requires recreating the instance | Manual: requires redeploying the application |
| Blast radius if the app is vulnerable | Limited to images/* in one bucket and to one secret, and only for the duration of the session |
A permanent key with the associated user's permissions, valid until somebody rotates it | The same as the previous one, and it usually has broader permissions "just in case" |
| Auditability | CloudTrail records the session name and the role: you know which instance did what | CloudTrail sees the IAM user: you cannot tell which machine or which process | Equally opaque |
One additional nuance about user_data that is developed in the next lesson: instance metadata is accessible to any process on the machine, including a poorly isolated container or a compromised application process. Putting a secret there is equivalent to writing it into a world-readable text file. That is why in 05-05 the rule will be blunt: user_data carries references to secrets, never secrets.
Conclusion
EcoMarket is on AWS, and module 4's promise has been kept literally: the network, data and app modules keep their interface, their locals, their tagging and their versioning; the only things that changed were the inside, from local_file to real resources, and the version number, from 2.x to 3.0.0, because changing the underlying provider is a MAJOR that destroys everything that came before.
- The
awsprovider contains no secrets: region and profile by variable,default_tagsfor the cross-cutting ones,assume_rolewhen there is one account per environment. TheNametag always goes on the resource, never indefault_tags. - Zones are discovered with
data "aws_availability_zones"and sorted withsort(), because an unstable order would shift thefor_eachkeys and destroy subnets. - The network is free; internet egress is not. The internet gateway and Gateway-type endpoints are free; the NAT gateway costs ~$33/month per zone even if not a byte goes through, and it is the number one cost trap in development environments.
- Security group rules are resources, not inline blocks. Inline blocks silently delete whatever others add, prevent extension from another module and turn any change into a full rewrite. And the group needs
name_prefixpluscreate_before_destroyor it gets stuck when replaced. - You reference the source security group, not a CIDR: it expresses the intent and survives addressing changes.
- The AMI is looked up with
data, never written down, andmost_recent = truewithoutignore_changescauses surprise replacements the day Canonical publishes an image. - IMDSv2 (
http_tokens = "required") is not optional: without it, an SSRF in the application hands over the instance role's credentials. - Auto scaling has four decisions that make it work:
ignore_changes = [desired_capacity],health_check_type = "ELB", referencinglatest_versioninstead of$Latest, andinstance_refreshso that a template change reaches the existing instances. - The load balancer is three resources — load balancer, target group and listener — plus the HTTP redirect, costs ~$18/month with no free tier, and its names have a 32-character limit that forces short prefixes.
- The instance role removes credentials from the system: EC2 does not accept a role but an instance profile that wraps it, and
aws_iam_policy_documentis preferred over JSON in a heredoc because it validates atplan, composes and produces readable diffs. Never"*"as a resource. - PostgreSQL lives in private subnets, with
publicly_accessible = false, always encrypted, and three deletion attributes that form a truth table:skip_final_snapshot,deletion_protectionand the bucket'sforce_destroydecide whether adestroyis reversible, expensive or catastrophic. - The password has three levels:
TF_VAR_(still in state),random_password+ Secrets Manager (nobody sees it, still in state) andmanage_master_user_password(not in state, AWS rotates it). The third is the destination forprod. - A well-configured bucket is six or seven resources since provider version 4: the public access block first, versioning, encryption, object ownership, lifecycle with cleanup of aborted multipart uploads, and a policy that requires TLS.
- The cost of
devis ~$55-70/month with NAT and a load balancer, and ~$1-3/month without them. That difference is all that separates cheap practice from an unpleasant surprise. terraform destroydoes not delete everything. Backups, buckets with contents, object versions, logs, secrets in scheduled deletion, dangling elastic IPs and snapshots all survive. The tag-based cleanup script is mandatory after every practice session.
What you have just deployed has a deliberate gap: the instances boot, the load balancer declares them healthy or not, but nobody has installed EcoMarket's application on them yet. That is resolved at the end of the module, in Configuring Servers. First, in the next lesson, it is time to check that what you have learned is not AWS knowledge but infrastructure knowledge: in Provisioning Azure Resources the same platform is deployed with azurerm_virtual_network, azurerm_linux_virtual_machine_scale_set, azurerm_postgresql_flexible_server and azurerm_storage_account, teaching by equivalence: which concept is the same under another name, what is genuinely different — the resource group, which has no AWS equivalent and reorganises the entire codebase — and what surprises Azure has in store, such as the key vault's soft delete that shows up exactly when you thought you had destroyed everything.
