Choose the Account, Region and Cost Boundary
Think of this deployment as three nested decisions. First choose the AWS account and identity (who is allowed to create things and who receives the bill). Then choose a region and network (where the service runs and how traffic can reach it). Inside that boundary, create the web service. The traffic path will be browser → load balancer → healthy server. A region is a geographic AWS location, a subnet is a smaller network inside a VPC, and a load balancer shares requests among servers. The safety checks below come before any resource is created.
Hiring a workshop bay teaches the habit: confirm the key, the city, the meter and who may enter before switching on the lathe. AWS asks the same four questions before the first resource block.
Identity. Terraform borrows a credential; it does not own an account. Run aws sts get-caller-identity and read Account, Arn and UserId; a role session's ARN names both role and session, while UserId repeats the session id after a colon. Record the account and ARN with digits redacted, never the secret or token. Environment variables outrank a profile, so clear stale AWS_PROFILE, AWS_ACCESS_KEY_ID and AWS_SESSION_TOKEN values, then confirm again. allowed_account_ids = [var.allowed_account_id] makes the provider refuse any other account before a resource is read; the AWS provider article covers the credential chain.
Region and quota. A region has its own prices, quotas and AMI IDs. Choose one near you with two Availability Zones and keep it in var.region; a us-east-1 AMI id does not exist in eu-west-1, which is why the next section resolves it per region. Availability Zone names are per-account aliases, so us-east-1a in your account need not be the same physical zone as us-east-1a in a teammate's; never hard-code a zone name to co-locate resources. Two t3.micro instances consume four vCPUs; newer accounts often start with an On-Demand quota of five, but check Service Quotas. Confirm a default VPC with two subnets. Verify with aws ec2 describe-availability-zones --state available and aws ec2 describe-subnets --filters Name=default-for-az,Values=true rather than trusting memory; a sandbox where someone deleted the default VPC will fail later for a reason unrelated to Terraform. Quota failures appear at apply as VcpuLimitExceeded, because plan cannot see remaining capacity.
Exposure. Allow port 80 to the balancer only from your address in var.allowed_cidr, and to the instances only from the balancer's security group. No SSH, no 443, no database. A security group is a stateful allow-list on an elastic network interface: no deny rules, and return traffic is automatic. Referencing the group, rather than copying addresses, keeps the rule correct as those addresses change.
The meter. Instances bill per second while running; EBS volumes per GB-month; public IPv4 addresses per address-hour; the balancer hourly plus capacity units; data transfer out beyond the allowance. Capacity units combine new connections, active connections, processed bytes and rule evaluations, so a page that many people reload can cost more than its size suggests. VPCs, subnets, routes, groups and target groups have no separate charge. The balancer bills even with zero traffic and is not covered by the EC2 free tier. Expect a few US dollars for an afternoon, verify current regional prices, set a budget alarm, and tag everything with lab = "p07-web-service".
Figure 1 orders the checks; both stop nodes are cheaper now than after an apply.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Sign in with the sandbox profile"] --> B["aws sts get-caller-identity"]
B --> C{"Account and role match?"}
C -->|"no"| X1["Stop: wrong account or stale session"]
C -->|"yes"| D["Choose a region with two AZs"]
D --> E{"vCPU and ALB quota available?"}
E -->|"no"| X2["Stop: request quota or shrink"]
E -->|"yes"| F["Allow port 80 from your address only"]
F --> G["Record each billed dimension"]
G --> H["Write variables and plan"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class C,E primary;
class A,B,D,F,G secondary;
class H ok;
class X1,X2 danger;
Figure 2 nests the boundaries: account, region, default VPC, service.
Deploy One Server with a Repeatable Bootstrap
One instance that answers HTTP needs a current image, a bootstrap script and a network path to a checker. Terraform owns the first two; the next section owns the third.
An Amazon Machine Image templates the root disk. AMI IDs are regional and change as Amazon patches, so hard-coding one schedules a break. The aws_ami data source asks the region at plan time for the newest image matching a filter and records the result in state and the plan. The filter should constrain owners to amazon and match architecture and virtualization type as well as a name prefix; without an owner constraint, a public image from another account could satisfy a loose name filter. most_recent = true is a moving target: a new release can make the next plan replace the instance, because ami forces replacement. For a lab that is instructive; for a long-lived service, constrain the filter or pin the id. Read the -/+ line.
Pin hashicorp/aws 6.72.0 and Terraform CLI 1.17.1, verified 5 November 2026. The schema is the contract; terraform providers schema -json shows what the lock file selected, not what a blog remembered. Version 6 permits a top-level region argument on many resources, but this lab keeps one provider and one region. Commit the lock file and run terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 if CI and laptops differ, so the first Linux init does not fail on a missing checksum.
user_data is a script cloud-init runs once on first boot as root. It is not configuration management: no retries, no drift correction, and output goes to /var/log/cloud-init-output.log. Never put a secret in it, because it is stored in state and readable from the instance metadata service. user_data_replace_on_change = true replaces the instance when the script changes; without it, a stop and start does not rerun cloud-init. The script starts with set -euo pipefail so a failed dnf stops the run instead of leaving a half-installed server that the health check will reject.
No key pair and no Session Manager role are created; var.key_name defaults to null, so port 22 stays closed. For debugging, the better answer is an instance profile with AmazonSSMManagedInstanceCore, which needs no inbound port; the faster lab answer is a temporary key and rule. Verification here is HTTP only. The instance type is also a decision: t3.micro is eligible for the free tier in many accounts, but eligibility varies by account age and region, and burst credits are throttled under sustained load. For this page the CPU credit is irrelevant; for a real service, benchmark before choosing.
The panel below is the finished service: it already includes the second instance, the balancer and the health check from later sections, so the whole chain can be reviewed and applied once. For the literal one-server step, keep web_a and the web group and comment out web_b, its attachment, the balancer, target group and listener.
slice(..., 0, 2) takes two default subnets, normally in different zones; if there is no default VPC or fewer than two subnets, stop and use another sandbox. associate_public_ip_address gives a route to package mirrors, not an inbound path. deregistration_delay = 30 speeds up destroy. restorecon fixes SELinux labels so httpd does not return 403 for a file that exists.
Names have scope: security group names are unique per VPC, while load balancer and target group names are unique per account and region. A failed apply that left a group or balancer behind makes the next apply fail with InvalidGroup.Duplicate or DuplicateLoadBalancerName; remove the orphan rather than renaming around it. Figure 3 follows the launch and its failure branches.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["terraform apply"] --> B["RunInstances: AMI, subnet, group, user_data"]
B --> C{"Quota and capacity?"}
C -->|"no"| X1["VcpuLimitExceeded"]
C -->|"yes"| D["Instance running"]
D --> E["cloud-init runs user_data"]
E --> F{"httpd installed and started?"}
F -->|"no"| X2["Target unhealthy: refused"]
F -->|"yes"| G["/healthz returns 200"]
G --> H{"Web group allows ALB on 80?"}
H -->|"no"| X3["Health check times out"]
H -->|"yes"| I["Target healthy"]
I --> J["Listener forwards"]
B -.->|"AMI filter empty"| X4["Stops before launch"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,C,E,H primary;
class B,D,F,G secondary;
class I,J ok;
class X1,X2,X3,X4 danger;
Open Only the Network Paths the Service Needs
A security group attaches to an elastic network interface and is evaluated there, not on the instance. Most "the rule is right but traffic is blocked" incidents are a rule on the wrong interface, or a packet that never arrives because the subnet has no route.
A subnet is an address range in one Availability Zone with a route table; the table decides where traffic leaves. An internet gateway attaches the VPC to the public internet. In a default VPC the main route sends 0.0.0.0/0 to that gateway, and the default subnets are public. A subnet is public because of its route and its public-IP setting, not because of its name or CIDR. A custom VPC needs a gateway, a route, an association and map_public_ip_on_launch.
Trace one request in Figure 4.
The operator's packet is checked at the ALB interface, then the listener picks a target. The ALB opens a separate connection to the instance, and the web group checks that new connection. Because the rule names the group, it follows the ALB nodes as addresses change. The instance sees the balancer as its client unless you forward the client address in a header. Health checks originate from the balancer's nodes in the enabled subnets, so the web group must admit the balancer's group on the target port; allowing the checker's public address instead would be both brittle and broader than necessary. Each rule is evaluated on the interface that owns it, in the direction of travel: an inbound rule on the web group does not authorize the instance's outbound package fetch, and an outbound rule on the ALB group does not authorize the client's request.
Security groups are stateful: return traffic needs no rule, which is why a missing egress rule can let a request arrive while the instance cannot reach package mirrors. This lab allows all egress because dnf needs DNS and HTTPS to several mirrors.
Network ACLs are stateless. If you add one that allows port 80 inbound, also allow the ephemeral ports used for responses. A subnet with no internet route still accepts the ALB's health check, because that traffic stays inside the VPC, while the instance cannot download packages: reachable but permanently unhealthy. VPC Flow Logs are the cheapest way to prove which of those two cases you are in, because they record accepted and rejected packets at the interface without changing the rules.
The public IPv4 on each instance is for outbound installation, not inbound access. A NAT gateway keeps inbound closed but adds hourly and data-processing charges. For a lab, the public address plus a tight group is cheaper; for production, a NAT gateway or VPC endpoints are cleaner.
Add Multiple Instances and a Load Balancer
One instance is a server; two behind a load balancer are a service. The difference is the target group, listener and health check that decide membership.
A target group is a pool with a health check. A listener accepts a protocol and port and forwards to a target group. The health check is the membership test: path, matcher, interval, timeout and thresholds. An Application Load Balancer works at HTTP level, so it terminates client connections and opens separate ones to targets. It does not pin a client to one instance unless stickiness is enabled, which is why two requests can show two hostnames. Cross-zone load balancing is on by default for an Application Load Balancer, so a node in one zone can forward to a healthy target in the other; that is what keeps the service up when one target, rather than one zone, fails.
The two instances are written by hand on purpose. A loop would hide the three things that must vary: subnet, Name tag and attachment target. Seeing the repetition first makes the later count or for_each refactor legible. Names have limits, too: a target group name is capped at 32 characters and cannot begin or end with a hyphen, which matters when a module prefixes an environment name. The listener's default action is the only action here; a real service adds host or path rules and a fixed response for unmatched requests. The attachment is separate because a target can join a group without being created by it, which is how a scheduler registers targets later.
With interval = 15, healthy_threshold = 2 and unhealthy_threshold = 3, a new target takes about 30 seconds to enter and a failing one about 45 seconds to leave. timeout = 5 must be shorter than the interval. A static /healthz proves httpd serves files, not that a database is reachable. deregistration_delay = 30 speeds the lab; production should exceed the longest in-flight request, or clients see reset connections during a deploy.
The listener is HTTP only: no certificate, no 443, no redirect. That is fine for a hello page and unacceptable for cookies, passwords or personal data; TLS needs an ACM certificate, validation, a 443 listener and a redirect. Two zones matter too: the balancer places a node in each enabled subnet, so one zone can fail while the other serves. Two instances in one zone survive an instance failure but not a zone failure. Attachments do not wait for health; Terraform records the target and moves on.
Terraform Finished; Is the Application Ready?
Apply complete! Resources: 9 added describes API calls. It means nine objects exist and their identifiers are in state. It does not mean the instance finished booting, httpd is running, the health check passes or a browser can load the page.
The graph knows an attachment depends on an instance and a listener depends on a target group. It does not know cloud-init is still installing packages or that httpd has not bound port 80. RunInstances returns while the instance is pending; the provider waits for running, which still precedes a finished boot. Attachments have no readiness wait. A load balancer with no healthy targets returns 503, so the first request after a green apply is often a 503 with nothing wrong. Figure 5 shows the two clocks.
The independent check is not terraform output. It is a request to the endpoint plus the target group's view of health. The bash panel polls describe-target-health until both targets are healthy, requests /healthz, then requests / with Connection: close. Closing the connection avoids keep-alive sending all six requests to one instance and looking like a broken balancer. Two hostnames prove the pool works; one repeated name means the other target is unhealthy, the client is reusing a connection, or stickiness is on.
A 200 from a static file proves the web server is up, not that a dependency is reachable or a migration ran. Add a separate readiness signal for dependencies that truly gate traffic, and keep its thresholds distinct: a check that fails on a slow non-critical dependency turns a partial outage into a full one.
A common failure looks like this: the demo starts immediately after apply, the first three requests return 503, and the fourth succeeds. Nothing was fixed; the targets simply crossed the threshold. A worse version is an instance that never becomes healthy because it has no route to the package mirror, so dnf exits and httpd never starts. The security group is correct, the subnet accepts the health check, and the console shows a running instance — three true observations that add up to the wrong conclusion. That is why the instance's route and its outbound access belong in the same checklist as its inbound rules.
Status codes narrow the cause. 503 means no healthy target: check describe-target-health and the path. 502 means a target was chosen but closed the connection or answered badly. A timeout means the packet did not arrive: check the web group, subnet route and network ACL. /var/log/cloud-init-output.log shows whether dnf ran, but without SSH or Session Manager you cannot read it. Add the SSM role before you need it. If you enable ALB access logs, each request records the target address, status and latency, which turns "sometimes it fails" into a timestamp and a target id; the bucket is an extra resource to delete later.
The distinction generalises: creation, configuration, liveness and readiness are four states, and each needs its own evidence. Terraform reports the first; the provider reports the second only when it can observe it; the health check reports the third; the application reports the fourth. A green apply is necessary and never sufficient.
Destroy the Service and Audit for Leftovers
Destroy is apply with the goal reversed. Terraform reads state, plans to remove every managed object and executes in dependency order: listener, balancer, attachments, target group, instances, groups. The balancer often takes a minute or two, and Terraform waits.
Plan the destroy and read it. It should name exactly what the apply created; if it wants to remove something else, stop and find out why. terraform plan -destroy -out=p07-destroy.tfplan then terraform apply p07-destroy.tfplan gives the same reviewable artifact as creation. Dependencies decide the order: the listener goes before the balancer, the attachments before the target group, and the instances before their security groups. create_before_destroy can reverse part of that order for zero-downtime replacement, which is why it belongs on a real service and not on a lab whose goal is to disappear.
What survives a correct destroy is what people forget:
- EBS volumes. Root volumes are deleted on termination by default. A volume with
delete_on_termination = false, or one orphaned by a failed launch, remains and bills. - Elastic IPs. This configuration creates none; the balancer's addresses are not Elastic IPs. A manually allocated, unassociated address bills, and is the classic post-lab charge.
- Logs. No log group or access-log bucket is created here. If you enable ALB access logs, the bucket, policy and objects remain after the balancer. The bucket policy that lets the load balancer write usually prevents Terraform from deleting a non-empty bucket, so empty it deliberately or keep it and record why.
- Security groups. Both created groups are deleted; the VPC's default group remains and cannot be deleted.
- Keys, AMIs and snapshots. A key pair remains until deleted. A baked AMI and its snapshots remain and bill.
- State and plans. The plans and local state contain identifiers and the
user_datatext. Delete the plans, keep state out of Git, and remove the directory when finished.
Audit by tag: Cost Explorer filtered to lab = p07-web-service shows what billed and whether anything still runs. The API queries in the bash panel cover the balancer, instances, volumes, addresses and both security groups. Add log groups and key pairs if you created them. The goal is not an empty console; it is a console where every remaining object has a reason.
Verify and clean up the web service
Status: design-only. No AWS account or credential was used to produce this article, and these commands were not executed here. Run them in a disposable sandbox and record the evidence. Redact account identifiers before publishing.
Prerequisites. Terraform CLI 1.17.1, hashicorp/aws 6.72.0, AWS CLI v2, an SSO profile for the sandbox, permission to create EC2, ELBv2 and security group resources, and a default VPC with two subnets in two zones. Set a budget alarm first; expect a few US dollars for an afternoon.
Minimal setup. One directory with main.tf from the HCL panel. Pass the account id through the environment, not a committed terraform.tfvars. Run terraform init and keep the lock file.
aws sso login --profile aw01-sandbox, setAWS_PROFILE, clear inherited access keys, and runaws sts get-caller-identity --output json. CompareAccountand the role inArnwith your record. ExportTF_VAR_allowed_account_id,TF_VAR_regionandTF_VAR_allowed_cidr(your address with/32).- Capture
terraform version -json,terraform providersand the lock diff. Runterraform fmt -checkandterraform validate. terraform plan -out=p07.tfplan. Expect nine resources: two groups, two instances, one balancer, one target group, two attachments, one listener. Confirm the AMI is Amazon Linux 2023 in your region and the CIDR is your address.terraform apply p07.tfplan. Record the summary and outputs.- Run the target-health loop. Expect
initialorunhealthyat first; cloud-init is working. Poll up to five minutes for twohealthytargets. - Request
/healthzand expect200. Request/six times withConnection: closeand record the hostnames. Both should appear. - Optional: set
health_check.pathto/missing, apply, and watch targets gounhealthyand the endpoint return503. Revert and wait for recovery. terraform plan -destroy -out=p07-destroy.tfplan, inspect it, then apply it. Expect nine destroyed.- Audit with the five API queries, and repeat them in the region you used; a console or CLI default may point elsewhere. Add
aws logs describe-log-groupsandaws ec2 describe-key-pairsif you created them. Check Cost Explorer by tag, delete both plans, remove the directory, and runaws sso logouton a shared machine.
Expected observation. Plan and apply both name nine resources. Both targets reach healthy, /healthz returns 200, and repeated requests show two hostnames. Destroy names nine, and every audit query is empty. Evidence: a sanitized caller ARN, the plan summary, target-health output, endpoint transcripts and the post-destroy inventory.
Failure checks. VcpuLimitExceeded means the regional quota is too small. An AMI filter with no match fails during plan. InvalidGroup.Duplicate means an earlier apply left a group; find it by tag. A 404 means the path is wrong; a timeout means the web group or subnet route. 503 with no healthy targets is the balancer working. DependencyViolation during destroy usually clears on a retry.
Cost dimensions. Two instances, two root volumes, two public IPv4 addresses, one balancer with hourly and capacity charges, and a little data transfer. The VPC, subnets, routes, groups and target group have no separate charge. The balancer bills until deleted.
Cleanup. Destroy removes what this configuration created. Check for an unassociated Elastic IP, an available volume, a log group or access-log bucket, a key pair, and an AMI or snapshot from debugging. Release an unassociated address with aws ec2 release-address; do not merely leave it in the console. Delete plans, keep state out of Git, and confirm with the API rather than the console's default view.
References (verified 5 November 2026):
aws sts get-caller-identity: https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.htmlaws_ami: https://registry.terraform.io/providers/hashicorp/aws/6.72.0/docs/data-sources/amiaws_instance: https://registry.terraform.io/providers/hashicorp/aws/6.72.0/docs/resources/instance- ALB health checks: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html
- Load balancer pricing: https://aws.amazon.com/elasticloadbalancing/pricing/
Next in the Series
In Meet the State File Before You Need to Repair It, we'll explore Read Terraform addresses and inspect state safely while protecting plans and snapshots.