Terraform Hour 4: Moving to a Cloud Platform (AWS)
- Use IAM Identity Center (SSO) profile,
assume_role, and OIDC three ways to give the aws provider short-term credentials, explain the AWS SDK credential chain lookup order, and usedefault_tagsto apply consistent tags, and to use the resource-level (new in aws provider 6.x)regionargument instead of multiple provider aliases. - Build production-grade S3 backend: bucket versioning, SSE-KMS encryption, blocking public access,
use_lockfile = truenative locking (DynamoDB locking is deprecated), and design cross-account state access. - Use
terraform-aws-modules/vpcand native resources to build a two-AZ VPC, and calculate NAT gateway cost (including the Regional NAT Gateway added in 2025), and use security group references instead of CIDR rules to allow traffic. - Use EC2 + user_data and ECS on Fargate + ALB + ECR separately to run myapp, understand the awsvpc network mode and the target group
target_type = "ip", health checks, and deployment circuit breakers. - Distinguish the ECS task execution role and task role, write policies following least privilege; inject secrets with Secrets Manager, and use ephemeral resources + write-only arguments (
secret_string_wo) so that secrets do not enter state. - Read and use
terraform-aws-modules/eksv21 (including EKS Auto Mode), independently troubleshoot AccessDenied, DependencyViolation, eventual consistency, throttling and quota issues, and complete the checklist for destroy and residual cleanup.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (AWS ca-central-1) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AWS setup | AWS CLI v2, SSO login, lab account and budget alerts, comparison with lesson 3 | Environment self-check | aws sts get-caller-identity |
| 1 | 00–06 | AWS Provider and authentication | credential chain, SSO profile, assume_role, OIDC, default_tags, 6.x resource-level region | Core animation: Terraform → provider → SigV4 → AWS API (retry/throttling) → waiter → state | SSO profile + cross-region resources |
| 2 | 06–13 | S3 Backend and native locking | bootstrap bucket, versioning, SSE-KMS,use_lockfile, migrating from DynamoDB, cross-account | lock contention when two people apply at the same time (conditional writes) | Create the state bucket and migrate |
| 3 | 13–21 | Networking: VPC, subnets, security groups | CIDR planning, public/private subnets, IGW, route tables, NAT (zonal / regional), security group references, VPC endpoints | VPC builder + NAT cost calculation + packet path | Build a two-AZ network with the vpc module |
| 4 | 21–30 | Compute: EC2 and ECS Fargate | AMI data source, user_data, ECR, task definitions, services, ALB/target groups, circuit breaker | ECS rolling deployment and ALB health checks | myapp on Fargate |
| 5 | 30–37 | IAM and secrets | trust policy vs permissions policy, execution role/task role, least privilege, Secrets Manager, ephemeral + write-only | Secret flow: which values end up in state | Secret injection + state check |
| 6 | 37–45 | Community modules and EKS | module selection and version constraints, eks module v21, Auto Mode, access entries, helm/kubernetes provider pitfalls | EKS creation dependency graph and timing | (optional) Auto Mode cluster |
| 7 | 45–53 | Cloud troubleshooting in practice | credential chain, AccessDenied decoding, DependencyViolation, eventual consistency, throttling, quotas | destroy failure replayer + interactive troubleshooting tree | Deliberately trigger 3 faults |
| 8 | 53–60 | Cost, cleanup and self-check | cost structure, tags and budgets, Infracost, destroy order, leftover scan | Lab cost calculator | destroy + leftover check |
| — | After class | Cheat sheet · Capstone lab | Deliver myapp with VPC + ECS Fargate + ALB + ECR + Secrets Manager, then destroy | Final quiz (12 questions) | Capstone lab (about 0.3 USD) |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / resources | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Authenticate the aws provider with short-term credentials | ✓ | ✓ | · | · | ✓ | · | ✓ | · | aws sso login,assume_role | M1 |
| remote state and locking | · | ✓ | · | · | · | · | ✓ | ✓ | backend "s3",use_lockfile,force-unlock | M2 |
| VPC network design | · | · | ✓ | ✓ | · | ✓ | ✓ | ✓ | module "vpc",aws_security_group | M3 |
| Containers on the cloud: ECR + ECS Fargate + ALB | · | · | · | ✓ | ✓ | · | ✓ | · | aws_ecs_service,aws_lb_target_group | M4 / capstone |
| virtual machines and user_data | · | · | · | ✓ | · | · | · | · | aws_instance,data "aws_ssm_parameter" | M4 |
| IAM least privilege | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | · | aws_iam_policy_document | M5 |
| secrets not in state | · | · | · | · | ✓ | · | · | · | ephemeral,secret_string_wo | M5 |
| community modules / EKS | · | · | ✓ | · | · | ✓ | · | · | module "eks",compute_config | M6 (optional) |
| cloud fault diagnosis | ✓ | ✓ | · | ✓ | ✓ | · | ✓ | ✓ | TF_LOG,decode-authorization-message | M7 |
| cost control and cleanup | ✓ | · | ✓ | · | · | ✓ | · | ✓ | terraform destroy, Resource Groups Tagging API | M8 |
Topics not covered in this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| The full CI/CD pipeline with GitHub Actions + OIDC, plan approval, drift detection | This lesson only configures the OIDC trust relationship and provider authentication | Lesson 5: Automated operations |
| Multi-account landing zones (Control Tower, AFT), Organizations SCP design | Belongs to platform architecture, beyond 1 hour | Lesson 6 (architecture practice) overview;AFT official docs |
| RDS / Aurora, ElastiCache and other managed data layers | Expensive and slow to create; this lesson runs Redis as a sidecar container | Lesson 6 (multi-tier architecture) |
terraform test, Policy (-policies), Checkov/tflint and other quality gates | Belongs to the automation and quality topics | Lessons 5 and 7 |
| Application delivery on EKS (Helm, Argo CD) and Kubernetes in depth | This lesson only uses Terraform to create the cluster itself | Kubernetes 8 + 1-hour lesson |
| Azure equivalents (azurerm, Container Apps) | Covered in the previous lesson | Lesson 3: Moving to a Cloud Platform (Azure) |
How to use this courseware
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. Read “Principles” and “Animation” first to understand the mechanism, then do the “Lab”. All labs are in the same directory
~/tf-lab/aws and build up step by step.A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress. It is saved in this browser's localStorage (cleared on refresh in private mode or when storage is blocked).
This lesson creates real billable resources. Each lab is labeled with estimated costs and cleanup commands. NAT gateways, ALBs and the EKS control plane are billed by the hour, so run destroy as soon as you finish and don't leave them running overnight.
~> 6.0. Community modules: terraform-aws-modules/vpc/aws 6.7.3,terraform-aws-modules/eks/aws 21.29.0 (requires aws provider ≥ 6.59),terraform-aws-modules/ecs/aws 7.6.1. Since aws provider 6.0 (2025-06), most resources have added region arguments; the DynamoDB lock for the S3 backend is deprecated, and use_lockfile the recommended option is . EKS currently supports standard versions 1.34–1.37. Prices are approximate for ca-central-1;.Module 0 · Warm-up and AWS setup (complete before class)
- CompletedLesson 1toLesson 3: familiar with
init/plan/apply, variables and outputs, modules, remote state (lesson 2 simulated the S3 backend with MinIO),for_each,moved/importblocks. - Workstation: Ubuntu 24.04 LTS (local machine or Azure VM), with Docker Engine 29 installed (from the Docker course), and Terraform v1.17.x.
- An AWS account dedicated to the lab (a sandbox account under AWS Organizations is strongly recommended; do not use a production account), plus a user who can sign in to IAM Identity Center. The permission set needs at least the ability to manage VPC, EC2, ECS, ECR, ELB, IAM roles, Secrets Manager, S3, KMS and CloudWatch Logs (for the lab you can use the
AdministratorAccesspermission set; tighten it for production, see module 5). - The image built in the Docker course myapp (Flask + gunicorn, listening on
0.0.0.0:8000,/healthzhealth check, passingREDIS_HOSTto connect to the Redis counter). If you don't have it, rebuild it using the first hour of the Docker course.
Step 1: Install and check the tools
terraform version
docker version --format '{{.Server.Version}}'
# AWS CLI v2 (official install method)
curl -sSL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o awscliv2.zip
unzip -q awscliv2.zip && sudo ./aws/install --update
aws --version
Terraform v1.17.2 on linux_amd64 29.9.3 aws-cli/2.x.x Python/3.x Linux/6.8.0 exe/x86_64.ubuntu.24
Step 2: Configure the IAM Identity Center (SSO) profile
This lesson does not use long-term Access Keys. aws configure sso It will interactively ask for the SSO start URL, region, account and permission set, and write them to ~/.aws/config:
aws configure sso --profile tf-lab # SSO session name: lab # SSO start URL: https://d-xxxxxxxxxx.awsapps.com/start # SSO region: ca-central-1 # choose the lab account and permission set; set the CLI default region to ca-central-1 aws sso login --profile tf-lab export AWS_PROFILE=tf-lab aws sts get-caller-identity
[profile tf-lab] sso_session = lab sso_account_id = 111122223333 sso_role_name = AdministratorAccess region = ca-central-1 [sso-session lab] sso_start_url = https://d-xxxxxxxxxx.awsapps.com/start sso_region = ca-central-1 sso_registration_scopes = sso:account:access
{
"UserId": "AROAEXAMPLEID:andy",
"Account": "111122223333",
"Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_0123456789abcdef/andy"
}
failed to refresh cached credentials ... the SSO session has expired or is invalid, then re-run aws sso login --profile tf-lab is enough. On headless servers you can add --use-device-code.Step 3: Set up budget alerts (strongly recommended)
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
aws budgets create-budget --account-id "$ACCOUNT" \
--budget '{"BudgetName":"tf-lab-10usd","BudgetLimit":{"Amount":"10","Unit":"USD"},"TimeUnit":"MONTHLY","BudgetType":"COST"}' \
--notifications-with-subscribers '[{"Notification":{"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":80,"ThresholdType":"PERCENTAGE"},"Subscribers":[{"SubscriptionType":"EMAIL","Address":"you@example.com"}]}]'
Budget alerts are delayed (billing data is usually updated several times a day) and are only a last line of defense; the real protection is to run destroy as soon as you finish (module 8).
Step 4: Create the lab directory
mkdir -p ~/tf-lab/aws/{bootstrap,app} && cd ~/tf-lab/aws
git init -q 2>/dev/null || true
cat > .gitignore <<'EOF'
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log
EOF
This lesson has two root modules: bootstrap/ (module 2: state bucket, using local state) and app/ (modules 1, 3, 4 and 5: all of myapp's infrastructure, using the S3 backend). The EKS in module 6 goes in a separate directory eks/.
Comparison with lesson 3 (Azure)
| Concept | Lesson 3 Azure | This lesson's AWS |
|---|---|---|
| provider | hashicorp/azurerm 5.x (5.14.0) | hashicorp/aws 6.x |
| Human sign-in | az login (Entra ID) | aws sso login (IAM Identity Center) |
| CI without passwords | Entra workload identity federated credentials | IAM OIDC provider + AssumeRoleWithWebIdentity |
| Remote state | azurerm backend (Blob lease lock) | s3 backend (use_lockfile conditional-write lock) |
| Resource groups | Resource group rg-tf-lab | No resource group concept → rely on tags + Resource Groups / Tag Editor |
| Networking | VNet / Subnet / NSG | VPC / Subnet / Security Group (+ NACL) |
| Container platform | Container Apps (+ ACR) | ECS on Fargate + ALB (+ ECR) |
| Secrets | Key Vault | Secrets Manager / SSM Parameter Store |
| Cleanup | az group delete One-step delete | terraform destroy + scan for leftovers by tag (there is no “delete the resource group in one step”) |
default_tags to tag all resources with Project=myapp-tf-lab, and module 8 uses those tags to scan for leftovers.Warm-up: answer from memory (30 seconds)
What protocol does Terraform core use to talk to the provider plugin? Which RPC do plan and apply each call?
gRPC (Terraform Plugin Protocol v5/v6). plan calls PlanResourceChange (first ReadResource refreshing state), and apply calls ApplyResourceChange. The core animation in this lesson extends this path to the AWS API.
Why must state be stored remotely and locked?
Multiple people or CI share one mapping to the real world; the lock stops two applies from writing state at once, which would cause overwrites or duplicate resource creation. Module 2 explains how S3's native locking works.
Module 1 · AWS Provider and authentication
- Describe the order in which the aws provider looks up credentials (provider arguments → environment variables → shared credentials/config files, including SSO → container credentials → EC2 instance profile), and explain why “it runs locally but not in CI” is often a credential-chain problem.
- Use an SSO profile (for people),
assume_role(cross-account),assume_role_with_web_identityor OIDC (CI): configure short-term credentials in three ways. - Use
default_tags,allowed_account_idsto add guardrails to the provider; use the 6.x resource-levelregionargument to manage multi-region resources in a single provider.
What: what the aws provider is
hashicorp/aws It is a standalone Go binary plugin, and Terraform core calls it over gRPC. Internally it uses AWS SDK for Go v2: responsible for looking up credentials and using SigV4 to sign each HTTP request, sending requests to service endpoints, retrying on throttling or transient errors, and polling after resource creation until it is ready (waiter). Terraform core knows no AWS details; it only sees the new state the provider returns.
Why: why authentication needs its own treatment
- Security: a long-term Access Key, once leaked (committed to Git, left in CI variables), stays valid for a long time. SSO, AssumeRole and OIDC all yield temporary credentials that expire after about 1 hour by default.
- Correctness: the credential chain has a priority order, and a leftover
AWS_ACCESS_KEY_IDenvironment variable silently overrides your profile and creates resources in the wrong account. - Multiple accounts: production usually uses an AWS Organizations multi-account structure, and Terraform assumes roles in each target account from a single "deployment/tooling account".
How: the credential chain and three recommended approaches
| Priority | Source | Typical scenario | Notes |
|---|---|---|---|
| 1 | provider block arguments access_key/secret_key/token | almost never should be used | written into code or variables,forbidden |
| 2 | environment variables AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN | Short-term credentials injected by configure-aws-credentials in CI | when present take precedence over the profile |
| 3 | shared credentials/config files (profile argument or AWS_PROFILE), including SSO,credential_process,role_arn+source_profile | engineer's local machine | SSO token cached in ~/.aws/sso/cache |
| 4 | container credentials (AWS_CONTAINER_CREDENTIALS_*) | Running Terraform in ECS tasks / CodeBuild | from the task role |
| 5 | EC2 instance profile (IMDSv2) | Running Terraform on a self-hosted EC2 runner | from the instance role |
On top of any kind of “base credentials”, the provider can also do one more assume_role (STS AssumeRole, which can be chained across multiple levels) or assume_role_with_web_identity (STS AssumeRoleWithWebIdentity, which exchanges an OIDC token for temporary credentials; the basis of passwordless CI, expanded in lesson 5).
Important changes in aws provider 6.x (verified)
- Resource-level
region(since 6.0.0): most resources, data sources and ephemeral resources have gained an optional top-levelregionargument that defaults to the provider's region; changing it forces resource replacement. Resources for global services such as IAM, Route 53, CloudFront and Organizations do not have this argument. When importing, you can append@region. The multi-provider alias style still works and is not deprecated. - Steps to move aliases to
regionthe official steps: upgrade to 6.x →terraform apply -refresh-only→ change theprovider = aws.xxxtoregion = "…". - For other breaking changes (some data source arguments renamed, resources for discontinued services removed, etc.), see Version 6 Upgrade Guide and check each one; this lesson does not list them individually.
Provider-level guardrails
default_tags: apply unified tags to all taggable resources created by this provider; a resource's owntagsis merged with these, and on key conflicts the resource wins; the merged result appears in thetags_allattribute.allowed_account_ids/forbidden_account_ids: errors out immediately if the credentials' account is not in the list, preventing “creating resources in the wrong account”.ignore_tags: ignores tags added by external systems (such as cost tools), to avoid permanent drift.max_retries(default 25),retry_mode(standard/adaptive): control the SDK's retry behavior.
When: which approach to use for which scenario
| Scenario | Recommended approach | Avoid |
|---|---|---|
| Local development/debugging on an engineer's machine | SSO profile (AWS_PROFILE=tf-lab) | IAM user long-term keys |
| Deploying from a tooling account to multiple target accounts | base credentials + assume_role { role_arn = target account role } | one set of keys per account |
| GitHub Actions / GitLab CI | OIDC → AssumeRoleWithWebIdentity | Storing Access Keys in CI Secrets |
| HCP Terraform | Dynamic Provider Credentials (also based on OIDC; follow the official docs) | Long-term keys stored in workspace variables |
Comparison with Azure in lesson 3
| azurerm | aws | |
|---|---|---|
| Human sign-in | Azure CLI token (az login) | SSO profile (aws sso login) |
| Target scope | subscription_id (required since 4.0; for 5.x follow the azurerm docs) | the credentials determine the account; region determines the region |
| Cross-scope | multiple provider aliases, different subscriptions | assume_role go into different accounts; since 6.x the region can be set at the resource level |
| CI without passwords | federated credentials (use_oidc = true) | assume_role_with_web_identity |
profile means the profile is always used” — if the environment has AWS_ACCESS_KEY_ID, the provider argument profile still takes effect (provider arguments take precedence over environment variables), but if is not written, profile and only AWS_PROFILE is set, the Access Key in environment variables takes precedence, which is the most common cause of “wrong account” deployments. ② “region changing it moves resources to another region” — this destroys and recreates them. ③ “default_tags applies to all resources” — it only applies to taggable resources; ASG instances propagate tags, and EBS root volumes and so on need separate configuration (such as volume_tags,tag_specifications).Architecture diagram: the authentication and call chain of one terraform apply
Flowchart: credential chain lookup order (stop at first match)
Core animation: one resource from HCL to AWS and back to state
Using aws_vpc.main as an example, step through the real calls: core builds the dependency graph → gRPC PlanResourceChange/ApplyResourceChange → SDK resolves credentials (SSO → STS) → SigV4 signing → EC2 Query API CreateVpc → throttling retry → waiter polling DescribeVpcs → write state. Tick the options to inject throttling or eventual-consistency errors.
Core commands and configuration
| Command / configuration | Purpose | Key arguments / notes |
|---|---|---|
aws configure sso / aws sso login | Create SSO profile / refresh SSO token | --profile,--use-device-code |
aws sts get-caller-identity | Confirm "who am I right now and in which account" | First command to run when troubleshooting |
aws configure export-credentials | Resolve a profile into temporary credentials (see what the SDK actually received) | --profile tf-lab --format env |
provider "aws" { assume_role { … } } | Cross-account role assumption | role_arn,session_name,external_id,duration |
assume_role_with_web_identity { … } | Exchange OIDC token for credentials | role_arn,web_identity_token_file |
TF_LOG_PROVIDER=DEBUG | Enable only the provider's debug logs | Shows every AWS API request (may contain sensitive information; do not share externally) |
Recommended provider configuration (app/providers.tf)
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = var.region # ca-central-1
allowed_account_ids = [var.account_id] # prevent creating resources in the wrong account
default_tags {
tags = {
Project = "myapp-tf-lab"
Environment = var.env
ManagedBy = "terraform"
Repo = "terraform"
}
}
# Don't put a profile in code; specify it with AWS_PROFILE so CI can reuse the same code
}
Cross-account: assume the target account role from the tooling account
provider "aws" {
alias = "prod"
region = "ca-central-1"
assume_role {
role_arn = "arn:aws:iam::444455556666:role/TerraformDeploy"
session_name = "tf-${var.env}"
# external_id = "..." # for third-party/vendor scenarios, guards against the “confused deputy”
}
}
CI: OIDC (lesson 5 covers the GitHub Actions side in detail)
provider "aws" {
region = "ca-central-1"
assume_role_with_web_identity {
role_arn = "arn:aws:iam::111122223333:role/gha-terraform"
web_identity_token_file = "/tmp/web-identity-token"
session_name = "gha"
}
}
# A more common approach: use aws-actions/configure-aws-credentials to obtain short-term credentials and export them as environment variables,
# leave no authentication arguments in the provider block (matched at level 2 of the credential chain).
6.x resource-level region: one provider managing two regions
# Old syntax (still works): provider "aws" { alias = "use1" region = "us-east-1" }
# 6.x new syntax: specify the region directly on the resource
resource "aws_s3_bucket" "logs_dr" {
region = "us-east-1" # changing this value forces replacement
bucket = "myapp-tf-lab-logs-dr-${var.account_id}"
}
data "aws_region" "current" {}
output "default_region" { value = data.aws_region.current.region }
cd ~/tf-lab/aws/app export AWS_PROFILE=tf-lab aws sts get-caller-identity --query '[Account,Arn]' --output text aws configure export-credentials --profile tf-lab --format env | sed 's/=.*/=***/'
111122223333 arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_0123456789abcdef/andy export AWS_ACCESS_KEY_ID=*** export AWS_SECRET_ACCESS_KEY=*** export AWS_SESSION_TOKEN=*** export AWS_CREDENTIAL_EXPIRATION=***
How to verify: Account ID and allowed_account_ids match; the ARN should show assumed-role (temporary credentials), not user/ (long-term keys). Common errors: forgetting aws sso login, profile name misspelled (failed to get shared config profile). Production use: In CI, always run get-caller-identity as the first step and print the account ID for auditing.
data "aws_region" In 6.x, this data source returns the region name in the region attribute, and the old name attribute is deprecated (see the v6 upgrade guide). If you are upgrading from 5.x, deprecation warnings in the plan are normal.Lab 1: SSO profile + default_tags + cross-region resources (about 5 min, cost ≈ 0)
~/tf-lab/aws/app):
variable "region" {
type = string
default = "ca-central-1"
}
variable "env" {
type = string
default = "lab"
}
variable "account_id" {
type = string # pass in via terraform.tfvars or TF_VAR_account_id
}
variable "prefix" {
type = string
default = "myapp"
}
export AWS_PROFILE=tf-lab export TF_VAR_account_id=$(aws sts get-caller-identity --query Account --output text) # Save the providers.tf from the “Commands” tab above to app/providers.tf terraform init
Initializing provider plugins... - Finding hashicorp/aws versions matching "~> 6.0"... - Installing hashicorp/aws v6.73.0... Terraform has been successfully initialized!
resource "aws_cloudwatch_log_group" "probe" {
name = "/${var.prefix}/m1-probe"
retention_in_days = 1
tags = { Owner = "andy" }
}
resource "aws_cloudwatch_log_group" "probe_use1" {
region = "us-east-1"
name = "/${var.prefix}/m1-probe"
retention_in_days = 1
}
output "probe_tags_all" { value = aws_cloudwatch_log_group.probe.tags_all }
terraform apply -auto-approve aws logs describe-log-groups --log-group-name-prefix /myapp/m1 --region us-east-1 --query 'logGroups[].arn'
aws_cloudwatch_log_group.probe: Creation complete after 1s [id=/myapp/m1-probe]
aws_cloudwatch_log_group.probe_use1: Creation complete after 2s [id=/myapp/m1-probe]
Outputs:
probe_tags_all = tomap({
"Environment" = "lab"
"ManagedBy" = "terraform"
"Owner" = "andy"
"Project" = "myapp-tf-lab"
"Repo" = "terraform"
})
[ "arn:aws:logs:us-east-1:111122223333:log-group:/myapp/m1-probe:*" ]TF_VAR_account_id=000000000000 terraform plan
Error: AWS account ID not allowed: 111122223333
AWS_ACCESS_KEY_ID=AKIAFAKEFAKEFAKE AWS_SECRET_ACCESS_KEY=fake terraform plan 2>&1 | grep -m1 -i error unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
Error: Retrieving AWS account details: validating provider credentials: retrieving caller identity from STS: operation error STS: GetCallerIdentity, https response error StatusCode: 403, RequestID: …, api error InvalidClientTokenId: The security token included in the request is invalid.
Even when AWS_PROFILE is set, static keys in environment variables are still used first. In production CI, these “ghost keys” are exactly what sends deployments to the wrong account or causes failures.
terraform destroy -auto-approve -target=aws_cloudwatch_log_group.probe -target=aws_cloudwatch_log_group.probe_use1 rm m1_tags.tf
Keep providers.tf,variables.tf for use in later modules. At this point state is still local; module 2 migrates it to S3.
Case 1: CI created resources in the sandbox account
Problem: The pipeline runner is an EC2 instance, and the team had set AWS_PROFILE=prod, but the runner image still contained AWS_ACCESS_KEY_ID (pointing to the sandbox account). apply succeeded, but “nothing exists in production”. Approach: Add allowed_account_ids to the provider; print the identity in the first pipeline step with get-caller-identity; switch the runner to an instance role plus assume_role, and delete all static keys. Limitations:allowed_account_ids It can only intercept at provider initialization; it cannot replace organization-level guardrails such as SCPs.
Case 2: unified deployment across 40 accounts
Problem: The platform team needs to deploy baseline resources (CloudTrail, Config, IAM roles) across 40 member accounts under Organizations. Approach: Pre-create a role TerraformDeploy (which trusts the CI role in the tooling account); each account gets its own root module/workspace, and the provider uses assume_role { role_arn = "arn:aws:iam::${var.account_id}:role/TerraformDeploy" }. Since Terraform 1.17, variables and locals can be used in provider requirements (verified from the CHANGELOG), and provider blocks have always been able to reference variables. Limitations: Writing 40 provider aliases in one root module makes plan slow and the blast radius large; splitting state by account is recommended (or use Terraform Stacks, per the official docs).
Case 3: migrating multi-region disaster recovery from aliases to resource-level region
Problem: The S3 cross-region replication configuration has 6 provider = aws.dr. Approach: After upgrading to aws 6.x, run terraform apply -refresh-only, then replace provider = aws.dr with region = "us-east-1", and the plan shows 0 changes. Limitations: If the code is changed before refresh-only runs, state has no region value and an unexpected replacement may occur; follow the official order strictly.
Common errors and fixes
Error: No valid credential sources found ... failed to refresh cached credentials, no EC2 IMDS role found
Cause: All five levels of the credential chain found no credentials: not signed in to SSO,AWS_PROFILE not exported (in a newly opened terminal), or Terraform running in a container without mounting ~/.aws.
env | grep ^AWS_ aws configure list aws sts get-caller-identity
Fix:aws sso login --profile tf-lab && export AWS_PROFILE=tf-lab; when running in a container, mount -v ~/.aws:/root/.aws:ro or pass temporary credentials as environment variables.
Error: ... operation error STS: GetCallerIdentity ... failed to refresh cached credentials, the SSO session has expired or is invalid
Cause: SSO access token expired (the session duration is configured by the Identity Center administrator).
Fix:aws sso login --profile tf-lab. A long-running apply (such as EKS) that expires midway can leave some resources created and state only half-written, so refresh the login before starting a large operation.
Error: Cannot assume IAM Role ... api error AccessDenied: User: arn:aws:sts::111122223333:assumed-role/... is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::444455556666:role/TerraformDeploy
Cause: Both sides must allow it: the target role's trust policy must trust the caller; the caller's own permissions policy must allow sts:AssumeRole; it may also be blocked by an SCP, or external_id does not match.
aws iam get-role --role-name TerraformDeploy --query Role.AssumeRolePolicyDocument # run in the target account aws sts assume-role --role-arn arn:aws:iam::444455556666:role/TerraformDeploy --role-session-name test
Fix: Add the caller role ARN to the trust policy Principal (note that SSO role names carry a random suffix, so you can use aws:PrincipalArn condition with a wildcard); check external_id.
Error: AWS account ID not allowed: 111122223333
Cause:allowed_account_ids The guardrail is in effect: the current credentials are not for the target account. Fix: switch to the correct profile,do not touch to make it pass.
Error: invalid AWS Region: ca-centrall-1 / no such host: ec2.ca-centrall-1.amazonaws.com
Cause: A region name typo, or a resource-level region was set to an opt-in region that is not enabled. Fix:aws account list-regions --region-opt-status-contains ENABLED ENABLED_BY_DEFAULT check the enabled regions.
1. Without running Terraform, how do you confirm which account and role the SDK will actually use in the current shell?
aws sts get-caller-identity aws configure list # shows whether access_key / region come from env, shared-credentials-file or sso
2. Turn on only the aws provider's debug logs and write the AWS API requests to a file, to troubleshoot a 403.
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=./tf-provider.log terraform plan grep -E "http.response.status|aws.operation" tf-provider.log | head
Logs may contain signature headers and resource attributes; delete them after troubleshooting and do not upload them to the ticketing system.
The same code applies fine from an engineer's local machine, but GitHub Actions reports No valid credential sources found. List your troubleshooting order.
① does the workflow have permissions: id-token: write (otherwise no OIDC token can be obtained); ② did the configure-aws-credentials step succeed and is the role ARN correct; ③ in the role's trust policy, the token.actions.githubusercontent.com:sub condition matches the repository/branch/environment; ④ are the later steps in the same job (environment variables do not cross jobs); ⑤ does the provider block hardcode a profile profile that only exists on the local machine (it does not exist in CI)? Fix: don't set a profile in the provider; in CI, use OIDC to inject credentials as environment variables.
Verified teaching videos
Official docs
- AWS Provider: authentication and configuration
- Enhanced Region Support (6.0)
- Version 6 Upgrade Guide
- AWS CLI: configuring IAM Identity Center authentication
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided and can be handed to a video tool.
Scene: a terminal runs terraform apply; the camera pulls back to show two boxes, core and provider, joined by a pipe labeled gRPC.
Narration: Terraform does not know AWS by itself. It hands the work to the aws provider over gRPC, and inside the provider is the AWS SDK.
Scene: five steps light up in turn: provider arguments, environment variables, config file, container credentials, instance role; the second step flashes red with “ghost key”.
Narration: the SDK looks for credentials in order and stops at the first one it finds. A leftover environment-variable key quietly overrides your profile.
Scene: the request envelope is stamped with a SigV4 seal and flies to an EC2 endpoint; partway it is blocked by a “throttling” barrier, backs off, and the resend succeeds.
Narration: every request is signed with temporary credentials. When throttled, the SDK automatically retries with exponential backoff, up to 25 times by default.
Scene: the waiter polls DescribeVpcs with a stopwatch; the status changes from pending to available, and the final line is written to the state file.
Narration: a create request returning does not mean the resource is usable. The provider polls until the resource is ready, and only then writes the result to state.
Module 2 · S3 Backend and native locking
- Use a standalone bootstrap root module to create the state bucket: versioning, SSE-KMS, blocking public access, TLS-only access, and protection against accidental deletion.
- Configure
backend "s3"in theuse_lockfile = truebackend, and explain that it relies on S3 conditional writes (If-None-Match) for mutual exclusion, and the IAM permissions needed (.tflockon the lock object: Get/Put/Delete). - Migrate local state to S3 (
init -migrate-state), smoothly move the old DynamoDB lock to lockfile, and design cross-account state access.
terraform_remote_state, and the S3 backend simulated with MinIO at the time. Importance:★★★★★What: S3 backend
The S3 backend stores state as an object in the bucket (key, for example myapp/lab/terraform.tfstate From Terraform 1.11, locking can also be done with S3 alone: after setting use_lockfile = true , Terraform creates a <key>.tflock object next to the state as the lock. The official docs state: “DynamoDB-based locking is deprecated”, and it will be removed in a future minor release.
Why: why configure the bucket this way
| Bucket configuration | What it prevents |
|---|---|
| Versioning | state can be rolled back to any earlier version if it is overwritten incorrectly or corrupted (lesson 7 uses this for state recovery) |
| SSE-KMS (customer-managed key) | state contains sensitive data (database passwords, private keys, etc.); the KMS key policy adds a second layer of access control, and CloudTrail audits it |
| Block Public Access + bucket policy denying non-TLS | misconfiguration that makes state public; plaintext transmission |
prevent_destroy + keeping the bucket out of the same state it manages | the self-destructive act of “using Terraform to delete the bucket that stores the Terraform state” |
| lifecycle rule cleaning up noncurrent versions (e.g., after 90 days) | every apply creates new versions, so storage costs accumulate over time |
How: how the lockfile lock works
- Terraform computes the lock object key:
key + ".tflock"; with a workspace it isenv:/<workspace>/<key>.tflock(the prefix can be changed withworkspace_key_prefix). - Use conditional write
PutObject+If-None-Match: *to create the lock object, whose content is JSON lock information (ID, operation, executor, version, time). If the object already exists, S3 returns 412 PreconditionFailed— this is the mutual exclusion, guaranteed atomically by S3. - After acquiring the lock, read the state (
GetObject), run plan/apply, and write the state back (PutObject, versioning automatically keeps the old versions). - At the end,
DeleteObjectdeletes the lock object. If the process is killed, the lock object is left behind and needsterraform force-unlock <LOCK_ID>.
Required permissions (key points from the official docs): The state object needs s3:GetObject,s3:PutObject; the bucket needs s3:ListBucket; when enabling use_lockfile , the lock file needs s3:GetObject,s3:PutObject, and s3:DeleteObject (the state object itself does not need Delete). When using kms_key_id , that key needs kms:Encrypt,kms:Decrypt, and kms:GenerateDataKey.
When: choosing an option
| Option | Applies to | Notes |
|---|---|---|
S3 + use_lockfile | Default for new projects | One bucket, no extra service; needs Terraform ≥ 1.11 |
S3 + DynamoDB (dynamodb_table) | Transition period for existing projects | Deprecated; can be enabled together with use_lockfile for the transition. After confirming all users are ≥ 1.11, remove the DynamoDB configuration |
HCP Terraform (cloud block) | Need for a UI, remote execution, policies, team permissions | Lesson 5 |
| S3-compatible storage (MinIO etc.) | Local labs (lesson 2) | Requires use_path_style, skips some AWS validations; conditional-write support depends on the implementation |
Comparison with similar technologies
| S3 backend | azurerm backend (lesson 3) | OpenTofu 1.13.x s3 backend | |
|---|---|---|---|
| Locking mechanism | S3 conditional writes .tflock | Blob lease | also supported use_lockfile (check the OpenTofu docs) |
| Encryption at rest | SSE-S3 default / SSE-KMS | storage-service encryption / CMK | client-side state encryption is also available (specific to OpenTofu) |
| Version history | bucket versioning | Blob versioning / soft delete | Same as S3 |
encrypt = true makes it secure” — it only stores objects encrypted on the server side; anyone who can read the bucket can still read plaintext state. The real boundary is IAM, the bucket policy and the KMS key policy. ② “Versioning = backup” — deleting the bucket within the same account still loses everything; production should consider cross-account replication or AWS Backup. ③ “The lockfile lock and the DynamoDB lock can be mixed” — if different Terraform processes look only at DynamoDB on one side and only at the lockfile on the other, they will not exclude each other; during the transition, enable both.Architecture diagram: layering of bootstrap and application state
Sequence diagram: two applies starting at the same time
Interactive demo: lock contention, process crash and force-unlock
Two executors running at the same time terraform apply. Step through to watch the changes on S3 to the .tflock object and state versions. Tick “A is killed midway through apply” to see the leftover lock and the correct recovery method.
Core commands and configuration
| Command / configuration | Purpose | Key arguments / notes |
|---|---|---|
terraform init -migrate-state | Migrate existing state to the new backend | prompts for confirmation; -force-copy skip confirmation (CI) |
terraform init -reconfigure | re-initialize ignoring the old backend configuration (no migration) | use when backend arguments change but the state location stays the same |
terraform init -backend-config=FILE | partial configuration | same code, different bucket/key per environment |
-lock-timeout=5m | wait for the lock instead of failing immediately | recommended in CI |
terraform force-unlock LOCK_ID | delete a leftover lock | first confirm no process is running |
aws s3api list-object-versions | view state version history | --prefix myapp/lab/ |
bootstrap/main.tf: state bucket (local state)
terraform {
required_providers { aws = { source = "hashicorp/aws", version = "~> 6.0" } }
}
provider "aws" {
region = "ca-central-1"
default_tags { tags = { Project = "myapp-tf-lab", ManagedBy = "terraform", Layer = "bootstrap" } }
}
data "aws_caller_identity" "me" {}
resource "aws_kms_key" "state" {
description = "Terraform state for myapp"
enable_key_rotation = true
deletion_window_in_days = 7 # shortest, 7 days, for the lab; production should use 30
}
resource "aws_kms_alias" "state" {
name = "alias/myapp-tf-state"
target_key_id = aws_kms_key.state.key_id
}
resource "aws_s3_bucket" "state" {
bucket = "myapp-tf-state-${data.aws_caller_identity.me.account_id}-ca-central-1"
# the bucket must be deleted at the end of the lab, so force_destroy is allowed here; for production set it to false and add prevent_destroy
force_destroy = true
}
resource "aws_s3_bucket_versioning" "state" {
bucket = aws_s3_bucket.state.id
versioning_configuration { status = "Enabled" }
}
resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
bucket = aws_s3_bucket.state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.state.arn
}
bucket_key_enabled = true # reduces KMS request costs
}
}
resource "aws_s3_bucket_public_access_block" "state" {
bucket = aws_s3_bucket.state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_ownership_controls" "state" {
bucket = aws_s3_bucket.state.id
rule { object_ownership = "BucketOwnerEnforced" }
}
resource "aws_s3_bucket_lifecycle_configuration" "state" {
bucket = aws_s3_bucket.state.id
rule {
id = "expire-noncurrent"
status = "Enabled"
filter {}
noncurrent_version_expiration { noncurrent_days = 90 }
}
}
data "aws_iam_policy_document" "tls_only" {
statement {
sid = "DenyInsecureTransport"
effect = "Deny"
actions = ["s3:*"]
resources = [aws_s3_bucket.state.arn, "${aws_s3_bucket.state.arn}/*"]
principals {
type = "*"
identifiers = ["*"]
}
condition {
test = "Bool"
variable = "aws:SecureTransport"
values = ["false"]
}
}
}
resource "aws_s3_bucket_policy" "state" {
bucket = aws_s3_bucket.state.id
policy = data.aws_iam_policy_document.tls_only.json
depends_on = [aws_s3_bucket_public_access_block.state]
}
output "bucket" { value = aws_s3_bucket.state.bucket }
output "kms_arn" { value = aws_kms_key.state.arn }
app/backend.tf: use native locking
terraform {
backend "s3" {
bucket = "myapp-tf-state-111122223333-ca-central-1" # replace with the bootstrap output
key = "myapp/lab/terraform.tfstate"
region = "ca-central-1"
encrypt = true
kms_key_id = "alias/myapp-tf-state"
use_lockfile = true
}
}
backend block cannot reference variables (it is initialized before variables are evaluated). For multiple environments, use partial configuration: keep only common items such as use_lockfile = true in the backend block and put the rest in backend-lab.hcl and pass it with terraform init -backend-config=backend-lab.hcl.
Transition from DynamoDB locking
backend "s3" {
# ...
use_lockfile = true # step 1: enable both so that old and new clients exclude each other
dynamodb_table = "tf-locks" # step 2: after confirming everyone/CI is ≥ 1.11, delete this line and run init -reconfigure
}
Cross-account access (state bucket in the tooling account)
backend "s3" {
bucket = "org-tf-state-999988887777"
key = "workloads/myapp/prod.tfstate"
region = "ca-central-1"
use_lockfile = true
encrypt = true
assume_role = { # note: the backend uses object assignment syntax
role_arn = "arn:aws:iam::999988887777:role/TerraformStateAccess"
}
}
# the provider then enters the workload account via its own assume_role: state access and resource permissions are kept separate
How to verify:terraform init Output Successfully configured the backend "s3"!; during apply, aws s3 ls s3://BUCKET/myapp/lab/ you can see .tflock. Common errors: backend region does not match the bucket region (301 Moved Permanently/PermanentRedirect), missing KMS permissions. Production use: split keys by account/environment/component; a single state should not be too large.
Lab 2: create the state bucket and migrate the app's state into it (about 6 min; cost ≈ KMS key at 1 USD/month, prorated by day)
bootstrap/main.tf from the “Commands” tab, then run:
cd ~/tf-lab/aws/bootstrap terraform init && terraform apply -auto-approve terraform output
Apply complete! Resources: 10 added, 0 changed, 0 destroyed. bucket = "myapp-tf-state-111122223333-ca-central-1" kms_arn = "arn:aws:kms:ca-central-1:111122223333:key/1a2b3c4d-…"
cd ~/tf-lab/aws/app
cat > backend.tf <<'EOF'
terraform {
backend "s3" {
use_lockfile = true
encrypt = true
}
}
EOF
cat > backend-lab.hcl <<EOF
bucket = "$(terraform -chdir=../bootstrap output -raw bucket)"
key = "myapp/lab/terraform.tfstate"
region = "ca-central-1"
kms_key_id = "alias/myapp-tf-state"
EOF
terraform init -backend-config=backend-lab.hcl -migrate-state
Initializing the backend... Do you want to copy existing state to the new backend? Enter a value: yes Successfully configured the backend "s3"! Terraform will automatically use this backend unless the backend configuration changes.
# terminal 1 terraform apply # stops at "Enter a value:"; do not answer # terminal 2 aws s3 ls s3://$(terraform -chdir=../bootstrap output -raw bucket)/myapp/lab/ terraform plan -lock-timeout=10s
2026-11-15 10:21:03 2187 terraform.tfstate 2026-11-15 10:22:41 241 terraform.tfstate.tflock ╷ │ Error: Error acquiring the state lock │ │ Error message: operation error S3: PutObject, https response error StatusCode: 412, RequestID: …, │ api error PreconditionFailed: At least one of the pre-conditions you specified did not hold │ Lock Info: │ ID: 6f1c2a7e-3b9d-… │ Path: myapp-tf-state-111122223333-ca-central-1/myapp/lab/terraform.tfstate │ Operation: OperationTypeApply │ Who: andy@lab-vm │ Version: 1.17.2
In terminal 1, type no to exit; the lock object is deleted immediately.
aws s3api list-object-versions --bucket $(terraform -chdir=../bootstrap output -raw bucket) \ --prefix myapp/lab/terraform.tfstate --query 'Versions[].[VersionId,LastModified,IsLatest]' --output table
------------------------------------------------------------------- | ListObjectVersions | +----------------------------------+----------------------------+--------+ | 3HL4kqtJlcpXroDTDmJ.rmSpXd3dIbrHY | 2026-11-15T10:20:11+00:00 | True | +----------------------------------+----------------------------+--------+
force_destroy = true in this lab is only there for easier cleanup; do not use it in production.Case 1: state overwritten by an old branch
Problem: Someone ran terraform state push on an old branch, rolling state back so the next plan has to recreate 30 resources. Approach: Because the bucket has versioning enabled, use list-object-versions to find the version from before the overwrite,aws s3api get-object --version-id … old.tfstate download it and check serial/lineage, then restore it with terraform state push (see lesson 7 for a detailed walkthrough). Configuration: In the deployment role's policy, remove manual s3:PutObject permissions; only allow CI to write. Limitations: Versioning can only restore objects; it cannot undo changes already applied in the cloud.
Case 2: migrating the DynamoDB lock table
Problem: 120 existing root modules use dynamodb_table; after upgrading Terraform, deprecation warnings appear. Approach: First standardize the CI images on ≥ 1.11; in batch, change the backend to enable both use_lockfile and dynamodb_table,init -reconfigure; after two weeks of observation, remove dynamodb_table, and finally delete the lock table. Limitations: The deployment role needs new .tflock object Put/Delete permissions; a common oversight is allowing only *.tfstate.
Case 3: centralized state account
Problem: The security team requires all state to be centralized in one "infrastructure tooling account"; people in workload accounts cannot read state directly. Approach: The backend uses assume_role to enter the tooling account's TerraformStateAccess role, with policies granting access by key prefix (workloads/myapp/*); the KMS key policy allows only that role. The provider uses another assume_role to enter the workload account. Limitations: Cross-account KMS requires both the key policy and the caller's IAM policy to allow access.
Common errors and fixes
Error: Error acquiring the state lock ... api error PreconditionFailed: At least one of the pre-conditions you specified did not hold
Cause: Another process holds the lock, or a previous run was forcibly interrupted and left .tflock behind.
aws s3 cp s3://BUCKET/myapp/lab/terraform.tfstate.tflock - | jq . # see who holds it, when, and what operation
Fix: After confirming the other process has really ended (ask a colleague or check the CI run history), run terraform force-unlock 6f1c2a7e-…. In CI, add -lock-timeout=5m to avoid concurrent pipelines failing outright.
Error: ... operation error S3: PutObject, https response error StatusCode: 403 ... AccessDenied (key: myapp/lab/terraform.tfstate.tflock)
Cause: After enabling use_lockfile , the .tflock object needs Put/Delete permissions, but the policy only grants *.tfstate.
Fix: Add to the resource ARN arn:aws:s3:::BUCKET/myapp/lab/terraform.tfstate.tflock (or myapp/*), and include the actions s3:GetObject,s3:PutObject, and s3:DeleteObject.
Error: Failed to get existing workspaces: ... api error AccessDenied: User ... is not authorized to perform: kms:Decrypt
Cause: state uses SSE-KMS encryption, the caller lacks KMS permissions, or the key policy does not grant access (common in cross-account setups).
aws kms get-key-policy --key-id alias/myapp-tf-state --policy-name default --output text
Fix: Grant the deployment role kms:Decrypt,kms:Encrypt, and kms:GenerateDataKey; for cross-account use, the key policy must also allow access.
Error: Backend configuration changed ... A change in the backend configuration has been detected, which may require migrating existing state.
Cause: backend arguments were changed (for example, use_lockfile was added).
Fix: if the state location did not change: terraform init -reconfigure; if the location changed: terraform init -migrate-state.
Warning: Deprecated Parameter ... The parameter "dynamodb_table" is deprecated. Use parameter "use_lockfile" instead.
Cause: The DynamoDB lock is deprecated. Fix: Migrate using the two-step transition method in the “Commands” tab.
1. Without opening any files, view the holder information of the current lock.
aws s3 cp s3://myapp-tf-state-111122223333-ca-central-1/myapp/lab/terraform.tfstate.tflock - | jq '{ID,Operation,Who,Created}'2. Download the previous version of the state to compare.
B=myapp-tf-state-111122223333-ca-central-1; K=myapp/lab/terraform.tfstate V=$(aws s3api list-object-versions --bucket $B --prefix $K --query 'Versions[1].VersionId' --output text) aws s3api get-object --bucket $B --key $K --version-id "$V" prev.tfstate && jq '.serial,.lineage' prev.tfstate
Half the team uses Terraform 1.10 (configured only dynamodb_table) and half uses 1.17 (configured only use_lockfile). What happens? How do you fix it?
The two groups check different locks: 1.10 only looks at the DynamoDB table, and 1.17 only looks at the .tflock object, so the two do not mutually exclude each other, and may write state at the same time and overwrite each other. Fix: configure both locks in the backend first and upgrade everyone to ≥ 1.11 (using required_version ) to enforce it, then remove DynamoDB once things are stable.
Verified teaching videos
No verified video specifically explaining use_lockfile native locking was found; a storyboard script is provided instead.
Official docs
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: an S3 bucket icon, with the labels “Versioning”, “KMS”, “Block public access” and “TLS only” stuck on it in turn.
Narration: the state bucket is the foundation of the whole infrastructure; first build it in a standalone bootstrap root module.
Scene: two people deliver cards named tflock to the bucket at the same time; the first one lands, and the second is bounced back with a 412.
Narration: since Terraform 1.11, the lock is simply a tflock object. S3's conditional write guarantees that only one person can create it; the latecomer gets a 412.
Scene: the DynamoDB table icon fades out with “Deprecated” beside it; the terminal shows force-unlock and a lock ID.
Narration: the DynamoDB lock table is deprecated. For a lock left behind by a crashed process, once you've confirmed nobody is running, delete it with force-unlock and the lock ID.
Module 3 · Networking: VPC, subnets, routes, NAT, security groups
- Plan VPC and subnet CIDRs, explain the roles of the IGW, route tables and NAT gateways, and understand that “a public subnet = has a default route pointing to the IGW”.
- Use
terraform-aws-modules/vpcCreate a two-AZ network in one go, write the equivalent configuration with native resources, and compare the cost and availability of zonal vs regional NAT, a single NAT vs one NAT per AZ, and VPC endpoints. - Use a standalone
aws_vpc_security_group_ingress_ruleresource and security group references (rather than CIDRs) to implement the minimum-privilege allow from the ALB to the application.
What: components of a VPC
| Component | Terraform resource | Purpose |
|---|---|---|
| VPC | aws_vpc | A regional private network with one primary CIDR (secondary CIDRs can be added); enable enable_dns_hostnames/enable_dns_support |
| Subnet | aws_subnet | belongs to a single AZ; each subnet reserves 5 addresses (network, VPC router, DNS, reserved, broadcast) |
| Internet Gateway | aws_internet_gateway | Two-way entry and exit between the VPC and the internet; scales horizontally and has no hourly fee |
| Route table | aws_route_table / aws_route / aws_route_table_association | determines where subnet traffic goes; 0.0.0.0/0 → igw i.e., a public subnet |
| NAT gateway | aws_nat_gateway + aws_eip | Lets private subnets egress only access the internet (pull images, call external APIs); billed by the hour plus data processed |
| Security group | aws_security_group + aws_vpc_security_group_ingress_rule/egress_rule | attached to an ENI; stateful firewall with allow rules only; can reference other security groups |
| Network ACL | aws_network_acl | subnet-level stateless rules with allow/deny, matched in numeric order; usually keep the defaults |
| VPC endpoint | aws_vpc_endpoint | Gateway type (S3, DynamoDB, free) uses the route table; Interface type (ECR, Logs, Secrets Manager, etc.) is an ENI in the subnet, billed by the hour plus traffic |
Why: why use private subnets + NAT
ECS tasks and databases should not have public IPs. Put them in private subnets; inbound traffic comes only through the ALB (in public subnets), and outbound traffic (pulling ECR images, reading Secrets Manager, writing CloudWatch Logs) goes through the NAT gateway or VPC endpoints. This leaves the only attack surface as the ALB's 80/443.
How: NAT options and costs (approximate ca-central-1 prices; refer to the AWS pricing page)
| Option | Terraform | Availability | Fixed monthly cost (≈730 hours) |
|---|---|---|---|
| No NAT; tasks in public subnets + public IP | assign_public_ip = true | — | Each public IPv4 is about 0.005 USD/hour ≈ 3.6 USD; poor security, lab only |
| Single zonal NAT | vpc module single_nat_gateway = true | If that AZ fails, all private subnets lose connectivity | NAT ≈ 0.05 USD/hour ≈ 36 USD + EIP + per-GB processing fee |
| One zonal NAT per AZ | one_nat_gateway_per_az = true | AZ isolation (the classic production-recommended approach) | × number of AZs (2 AZs ≈ 72 USD) |
| Regional NAT Gateway | Native aws_nat_gateway { availability_mode = "regional", vpc_id = … } | One gateway auto-scales across multiple AZs (auto mode), with no need for one route target per AZ | Billing follows the AWS pricing page |
| VPC endpoints only (no NAT) | S3 Gateway + ECR api/dkr, Logs, and Secrets Manager Interface endpoints | No public internet access; the most secure | Interface endpoints are billed per "endpoint × AZ × hour"; 4 endpoints × 2 AZs usually cost more than 1 NAT |
Verification note: aws_nat_gateway In the docs, availability_mode takes the values zonal (default) /regional; regional mode must provide vpc_id, and subnet_id/allocation_id must not be set,connectivity_type must be public; omitting availability_zone_address gives automatic mode. As of vpc module 6.7.3, the module does not yet expose input variables for regional NAT, so it must be implemented with native resources.
When: CIDR planning principles
- Must not overlap with other company VPCs, on-premises networks, or the lesson 3 Azure VNet (for future peering, Transit Gateway or VPN). This lesson uses
10.20.0.0/16(the Azure lesson uses a different range). - At least two AZs (the ALB requires subnets in at least two different AZs). The AZ names in ca-central-1 are
ca-central-1a,ca-central-1b,ca-central-1d—usedata "aws_availability_zones"to obtain them; do not hardcode them. - Give private subnets enough addresses: Fargate uses one ENI/IP per task, and EKS (VPC CNI) uses one IP per Pod.
Comparison with lesson 3 Azure
| Azure | AWS | |
|---|---|---|
| Subnet scope | regional (spans AZs) | single AZ |
| Default outbound | New VNets no longer provide implicit outbound by default (see the Microsoft docs); NAT Gateway is recommended | Private subnets have no outbound at all; NAT or endpoints are required |
| Firewall | NSG (can attach to subnets or NICs; has priorities and deny rules) | Security group (attached to ENIs, allow only) + NACL (subnet-level, stateless) |
| Reference | Application Security Group | Security groups reference security groups |
ingress {} blocks and standalone rule resources can be mixed” — they overwrite each other and cause a change on every plan; the aws provider docs recommend using aws_vpc_security_group_ingress_rule/egress_rule,do not mix with inline rules or the old aws_security_group_rule resource. ④ “Deleting a NAT gateway stops the charges” — if its EIP is not released, it is still billed as a public IPv4.Architecture diagram: two-AZ VPC for myapp in this lesson
Data flow: user requests and task outbound traffic
Interactive demo: VPC builder + NAT cost + packet path
Choose an outbound option to see which resources would be created, the fixed monthly cost, and each hop a packet takes (route table lookup → target) when a task in a ca-central-1b private subnet accesses ECR.
Core resources and commands
| Resource / command | Purpose | Key arguments |
|---|---|---|
module "vpc" | Create VPC, subnets, IGW, NAT and route tables in one go | azs,public_subnets,private_subnets,single_nat_gateway |
cidrsubnet(prefix, newbits, netnum) | Compute subnet CIDRs | cidrsubnet("10.20.0.0/16", 8, 10) = 10.20.10.0/24 |
data "aws_availability_zones" | Get available AZs | state = "available" |
aws_vpc_security_group_ingress_rule | A single inbound rule | referenced_security_group_id or cidr_ipv4,ip_protocol |
aws ec2 describe-route-tables | Verify routes | --filters Name=vpc-id,Values=… |
terraform console | Interactively verify the CIDR functions | No apply needed |
app/network.tf (using the community module)
data "aws_availability_zones" "available" {
state = "available"
}
locals {
vpc_cidr = "10.20.0.0/16"
azs = slice(data.aws_availability_zones.available.names, 0, 2)
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 6.7"
name = "${var.prefix}-${var.env}"
cidr = local.vpc_cidr
azs = local.azs
public_subnets = [for i, az in local.azs : cidrsubnet(local.vpc_cidr, 8, i)] # 10.20.0.0/24, 10.20.1.0/24
private_subnets = [for i, az in local.azs : cidrsubnet(local.vpc_cidr, 8, i + 10)] # 10.20.10.0/24, 10.20.11.0/24
enable_nat_gateway = true
single_nat_gateway = true # saves money in the lab; in production change to one_nat_gateway_per_az = true
enable_dns_hostnames = true
enable_dns_support = true
}
# Free S3 Gateway endpoint: ECR image layers are pulled from S3, bypassing NAT
resource "aws_vpc_endpoint" "s3" {
vpc_id = module.vpc.vpc_id
service_name = "com.amazonaws.${var.region}.s3"
vpc_endpoint_type = "Gateway"
route_table_ids = module.vpc.private_route_table_ids
}
app/security.tf: security group references
resource "aws_security_group" "alb" {
name = "${var.prefix}-alb"
description = "ALB public HTTP"
vpc_id = module.vpc.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "alb_http" {
security_group_id = aws_security_group.alb.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "tcp"
from_port = 80
to_port = 80
}
resource "aws_vpc_security_group_egress_rule" "alb_to_app" {
security_group_id = aws_security_group.alb.id
referenced_security_group_id = aws_security_group.app.id
ip_protocol = "tcp"
from_port = 8000
to_port = 8000
}
resource "aws_security_group" "app" {
name = "${var.prefix}-app"
description = "myapp tasks"
vpc_id = module.vpc.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "app_from_alb" {
security_group_id = aws_security_group.app.id
referenced_security_group_id = aws_security_group.alb.id # only trust the ALB; do not write CIDRs
ip_protocol = "tcp"
from_port = 8000
to_port = 8000
}
resource "aws_vpc_security_group_egress_rule" "app_all" {
security_group_id = aws_security_group.app.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1" # pull images, read secrets, write logs
}
Note: a security group created by Terraform removes AWS's default "allow all outbound" rule, so outbound must be declared explicitly.
Regional NAT (native resource syntax, replacing the NAT in the module)
# set enable_nat_gateway = false in module "vpc", then:
resource "aws_nat_gateway" "regional" {
availability_mode = "regional" # default is zonal
vpc_id = module.vpc.vpc_id # required for regional; subnet_id / allocation_id must not be set
# omitting availability_zone_address = automatic mode: auto-scales in AZs with ENIs and allocates EIPs
}
resource "aws_route" "private_default" {
count = length(module.vpc.private_route_table_ids)
route_table_id = module.vpc.private_route_table_ids[count.index]
destination_cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.regional.id
}
Regional NAT is a capability launched in 2025; for routing syntax, billing and regional availability, refer to the AWS NAT gateway docsand verify in a lab account before adopting it in production.
terraform console
> [for i in range(2) : cidrsubnet("10.20.0.0/16", 8, i + 10)]
[ "10.20.10.0/24", "10.20.11.0/24", ]
Lab 3: build a two-AZ network with the vpc module (about 6 min; NAT starts billing at ≈ 0.05 USD/hour)
output "vpc_id" { value = module.vpc.vpc_id }
output "private_subnets" { value = module.vpc.private_subnets }
output "public_subnets" { value = module.vpc.public_subnets }
output "app_sg_id" { value = aws_security_group.app.id }
cd ~/tf-lab/aws/app terraform init -upgrade # download the vpc module terraform plan -out=net.tfplan | tail -5
Plan: 27 to add, 0 to change, 0 destroy. Saved the plan to: net.tfplan
time terraform apply net.tfplan
module.vpc.aws_nat_gateway.this[0]: Still creating... [01m30s elapsed] module.vpc.aws_nat_gateway.this[0]: Creation complete after 1m44s [id=nat-0a1b2c3d4e5f60718] Apply complete! Resources: 27 added, 0 changed, 0 destroyed. real 2m11s
VPC=$(terraform output -raw vpc_id)
aws ec2 describe-route-tables --filters Name=vpc-id,Values=$VPC \
--query 'RouteTables[].{Name:Tags[?Key==`Name`]|[0].Value,Default:Routes[?DestinationCidrBlock==`0.0.0.0/0`]|[0].[GatewayId,NatGatewayId]}' --output table
------------------------------------------------------------------- | DescribeRouteTables | +---------------------------------+-------------------------------+ | Name | Default | +---------------------------------+-------------------------------+ | myapp-lab-public | igw-0f1e2d3c4b5a69788 None | | myapp-lab-private-ca-central-1a| None nat-0a1b2c3d4e5f60718 | | myapp-lab-private-ca-central-1b| None nat-0a1b2c3d4e5f60718 | | None | None | +---------------------------------+-------------------------------+
The last line is the VPC's main route table (no default route, not associated with any subnet).
aws ec2 describe-security-group-rules --filters Name=group-id,Values=$(terraform output -raw app_sg_id) \ --query 'SecurityGroupRules[].[IsEgress,IpProtocol,FromPort,ReferencedGroupInfo.GroupId,CidrIpv4]' --output text
False tcp 8000 sg-0123456789abcdef0 None True -1 -1 None 0.0.0.0/0
terraform destroy, otherwise the NAT gateway costs about 1.2 USD per day plus EIP fees. Risk: If Lambda/ECS leaves ENIs behind during destroy, deleting subnets/security groups may fail with DependencyViolation; see module 7.Case 1: NAT processing fees exceed compute fees
Problem: In one team's monthly bill, the NAT gateway's “data processing” charges were higher than Fargate's. VPC Flow Logs showed the main traffic was tasks in private subnets pulling images from ECR (40 tasks × 800 MB per deployment) and writing to S3. Approach: Add the free S3 Gateway endpoint (ECR image layers are stored in S3), add Interface endpoints for the frequently used ECR API, and slim down images (multi-stage builds from the Docker course). Limitations: Interface endpoints are billed per AZ × hour, so at low traffic they can actually cost more; measure against your traffic.
Case 2: a single NAT caused a full service outage
Problem: Production was set up with single_nat_gateway = true to save money. When that AZ failed, tasks in the other AZ were healthy but could not reach the external payment API. Approach: Change to one_nat_gateway_per_az = true (each private route table points to the NAT in its own AZ), or evaluate Regional NAT. Limitations: The switch replaces routes; run it in a maintenance window and watch for replace in the plan.
Case 3: overlapping CIDRs blocked cross-cloud connectivity
Problem: The AWS VPC and Azure VNet both used 10.0.0.0/16, and later a site-to-site VPN could not route. Approach: Establish an org-level IPAM (AWS VPC IPAM, or a spreadsheet plus Terraform variable validation validation blocks); new VPCs are allocated from the IPAM pool; existing overlapping networks can only be migrated or handled with NAT translation. Limitations: A VPC's primary CIDR cannot be changed; you can only create a new one.
Common errors and fixes
Error: creating EC2 Subnet: InvalidSubnet.Conflict: The CIDR '10.20.1.0/24' conflicts with another subnet
Cause: Subnet CIDRs overlap (cidrsubnet netnum duplicated, or subnets were created by hand).
aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC --query 'Subnets[].[CidrBlock,AvailabilityZone,SubnetId]' --output table
Fix: In terraform console , print all CIDRs first to check; public and private subnets use different netnum ranges (0–9 and 10–19 in this lesson).
Error: creating EC2 VPC: VpcLimitExceeded: The maximum number of VPCs has been reached.
Cause: The default quota is 5 VPCs per region; similar limits include AddressLimitExceeded (EIP default 5),NatGatewayLimitExceeded.
aws service-quotas get-service-quota --service-code vpc --quota-code L-F678F1CE --query 'Quota.Value'
Fix: Clean up leftover VPCs or request an increase via Service Quotas (module 7).
Tasks in private subnets stay PENDING and then stop: ResourceInitializationError: unable to pull secrets or registry auth ... dial tcp ...: i/o timeout
Cause: Private subnets have no outbound path: NAT not created, route table not associated, or the security group has no outbound rule (Terraform-created security groups have no outbound by default).
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=SUBNET_ID --query 'RouteTables[].Routes'
Fix: Confirm 0.0.0.0/0 → nat-…; confirm sg-app has an outbound rule; or add ECR/Logs/Secrets Manager endpoints.
Every plan shows security group rules being deleted and re-added (perpetual diff)
Cause: The same security group has inline ingress {}, plus separate rule resources (or the old aws_security_group_rule).
Fix: Keep only one approach; it is recommended to convert everything to aws_vpc_security_group_ingress_rule/egress_rule, and use import blocks to import existing rules (rule IDs look like sgr-…).
Error: creating ELBv2 application Load Balancer: ValidationError: At least two subnets in two different Availability Zones must be specified
Cause: The ALB needs subnets in at least two different AZs. Fix: Pass module.vpc.public_subnets (two AZs).
1. List all NAT gateways in the current VPC, with their status, subnets and public IPs.
aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=$VPC \ --query 'NatGateways[].[NatGatewayId,State,SubnetId,NatGatewayAddresses[0].PublicIp]' --output table
2. Find unassociated Elastic IPs in the account (they are still billed).
aws ec2 describe-addresses --query 'Addresses[?AssociationId==null].[PublicIp,AllocationId,Tags]' --output table
Your boss asks for the lowest possible lab network cost, but tasks must not have public IPs. What options do you have, and what does each cost?
① A single NAT (about 36 USD/month plus processing fees) is the simplest; ② VPC endpoints only: S3 Gateway (free) + ECR api, ECR dkr, Logs and Secrets Manager Interface endpoints, deployed in one AZ to reduce cost but losing high availability, and tasks cannot reach other public addresses; ③ turn the NAT off with Terraform after work (enable_nat_gateway = var.nat_enabled), but tasks cannot pull images or read secrets; ④ the fundamental answer: destroy as soon as the lab is done. Conclusion: use a single NAT + S3 endpoint for the lab, and delete it when done.
Verified teaching videos
No verified video dedicated to Regional NAT Gateway was found.
Official docs
- terraform-aws-modules/vpc
- aws_nat_gateway (including regional mode)
- aws_vpc_security_group_ingress_rule
- Amazon VPC pricing (NAT, endpoints, public IPv4)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: a large VPC box, split vertically into two AZs, each AZ split horizontally into a public layer and a private layer.
Narration: a VPC is a regional network, and a subnet belongs to only one AZ. A load balancer can only be created with at least two AZs.
Scene: two route tables side by side; one has 0.0.0.0/0 pointing to the IGW, the other to the NAT; the subnet colors turn green or gray accordingly.
Narration: public or private depends only on the route table. A default route pointing to the internet gateway makes a public subnet.
Scene: a meter pops up next to the NAT gateway, with per-hour and per-GB numbers rolling; when the S3 endpoint appears, the GB number drops.
Narration: the NAT gateway charges by the hour plus by traffic, and is the number one killer of the lab bill. Adding a free S3 gateway endpoint saves the traffic fees for pulling images.
Scene: two security group icons, with an arrow from sg-alb to sg-app labeled 8000.
Narration: security groups can reference each other. The application only trusts the load balancer and does not need any IP addresses written down.
Module 4 · Compute: EC2 (user_data) and ECS on Fargate
- Use
data "aws_ssm_parameter"to get the latest AMI, and useaws_instance+user_data+ IMDSv2 to launch an EC2 instance running myapp, and understanduser_data_replace_on_change. - Create an ECR repository and push the myapp image; write the Fargate task definition (
awsvpc, CPU/memory combinations, container definition JSON, logs, health checks). - Publish myapp with an ALB + target group (
target_type = "ip") + ECS service (deployment circuit breaker,wait_for_steady_state), and explain how task and target states change during a rolling deployment.
What: three common ways to run containers on AWS
| EC2 + Docker (user_data) | ECS on Fargate | EKS (module 6) | |
|---|---|---|---|
| You manage | OS, patches, Docker, process supervision, scaling | Task definitions and services | Kubernetes manifests + (under Auto Mode) minimal node configuration |
| Billing | Instance hours | Task vCPU/GB per second | Control plane 0.10 USD/hour + compute |
| Networking | Instance ENI, port mapping | awsvpc: one ENI and private IP per task | VPC CNI: one IP per Pod |
| Suited for | legacy applications, cases needing host-level control | the default choice for stateless services | existing K8s ecosystem / multi-team platforms |
Why: ECS core objects
- ECR repository (
aws_ecr_repository): a private image registry. Recommended:image_tag_mutability = "IMMUTABLE", scan on push, and lifecycle policies to clean up old images. - Task definition (
aws_ecs_task_definition): like a "Pod spec". Each change creates a new revision (family:N); the old revision is only marked INACTIVE. - Cluster (
aws_ecs_cluster): a logical grouping; with Fargate there are no instances for you to manage. - Service (
aws_ecs_service): keepsdesired_counttasks running; handles rolling deployments, registering/deregistering target groups, and circuit breaker rollback. - ALB + target group + listener: Fargate tasks must use
target_type = "ip"(tasks have no EC2 instance ID).
How: a real deployment, step by step
- Terraform registers a new revision (
RegisterTaskDefinition), thenUpdateServicepoints to it. - The ECS scheduler starts new tasks according to
deployment_maximum_percent(default 200): PROVISIONING (creates and attaches an ENI in the subnet) → PENDING (the execution role pulls images, fetches secrets, creates log streams) → RUNNING. - The service registers task IP:8000 with the target group, and ALB health checks must consecutively succeed
healthy_thresholdtimes, after which the target becomeshealthy(health_check_grace_period_seconds— failures within this window are ignored). - Stop old tasks according to
deployment_minimum_healthy_percent(default 100): deregister the target first → draining (deregistration_delay, default 300 seconds, set to 30 in the lab) → SIGTERM →stopTimeoutthen SIGKILL. - When
deployment_circuit_breaker { enable = true, rollback = true }is enabled, if new tasks repeatedly fail to start the deployment fails and automatically rolls back to the last successful revision. wait_for_steady_state = trueMake Terraform wait until the service is stable before returning (otherwise apply may succeed while the service is still failing).
Fargate CPU/memory combinations (excerpt)
| cpu (units) | allowed memory (MiB) |
|---|---|
| 256 (0.25 vCPU) | 512, 1024, 2048 |
| 512 (0.5 vCPU) | 1024 – 4096 (1 GB steps) |
| 1024 (1 vCPU) | 2048 – 8192 |
For the full combinations (up to 16 vCPU/120 GB) see the ECS docs; invalid combinations report errors at RegisterTaskDefinition time.
When: EC2 or Fargate
- This lesson's capstone lab uses Fargate: no hosts to manage, closest to the "just deliver the container" need, and corresponds to Container Apps in lesson 3.
- When you need GPUs, special kernel parameters, or long-term stable high load (Reserved/Savings Plans are cheaper), consider ECS on EC2 or EKS.
- EC2 + user_data is good for understanding the "bootstrap at launch" mechanism, and for the managed nodes in lesson 4 of the Ansible course.
Comparison with lesson 3 Azure
| Azure Container Apps | ECS Fargate | |
|---|---|---|
| Entry point | built-in ingress (Envoy) | requires building your own ALB/target group/listener |
| Versioning | revision | task definition revisions + service deployment |
| Multi-container | multi-container / sidecar within the same Container App | multiple containers in the same task share the network namespace (localhost communicate) |
| Scale to 0 | supported | desired_count 0 can be set, but there is no built-in "wake on request" |
wait_for_steady_state is not set, Terraform only confirms the API call succeeded. ② “The Docker course says containers cannot use localhost to talk to each other” — that is because different containers each have their own network namespace; containers in the same ECS task (awsvpc) share one network namespace, so for myapp to reach the Redis in the same task, use localhost:6379 is correct. ③ “Terraform should be responsible for docker build/push” — using null_resource/local-exec to build images makes plans unpredictable; image builds belong to CI (lesson 5), and Terraform only references image tags or digests. ④ In this lesson Redis runs as a sidecar,each task has its own independent counter; use ElastiCache when shared state is needed (lesson 6).Architecture diagram: myapp on ECS Fargate
State machine: lifecycle of tasks and targets
Interactive demo: ECS rolling deployment + ALB health checks + circuit breaker
desired 2,minimum_healthy_percent=100,maximum_percent=200. Click play to watch the revision 1 → 2 deployment; tick “new version /healthz returns 500” to watch the circuit breaker roll back. The log below corresponds to aws ecs describe-services events and ALB target health status.
Core resources and commands
| Resource / command | Purpose | Key arguments |
|---|---|---|
aws_ecr_repository | private image repository | image_tag_mutability,image_scanning_configuration,force_delete |
aws ecr get-login-password | docker login | Log in to ECR with Docker (token valid for 12 hours) | --password-stdin |
aws_ecs_task_definition | Task spec | network_mode = "awsvpc",cpu/memory,execution_role_arn,container_definitions |
aws_lb_target_group | backend set and health checks | target_type = "ip",health_check.path,deregistration_delay |
aws_ecs_service | maintain task count, rolling deployments | deployment_circuit_breaker,wait_for_steady_state,load_balancer |
aws ecs describe-services | view deployments and events | --query 'services[0].events[:5]' |
aws elbv2 describe-target-health | target health status and reasons | TargetHealth.Reason |
aws ecs execute-command | enter a running container (requires enable_execute_command + SSM plugin) | --interactive --command "/bin/sh" |
app/ecr.tf
resource "aws_ecr_repository" "myapp" {
name = "${var.prefix}"
image_tag_mutability = "IMMUTABLE"
force_delete = true # lab: delete images along with the repo on destroy; remove in production
image_scanning_configuration {
scan_on_push = true
}
}
resource "aws_ecr_lifecycle_policy" "myapp" {
repository = aws_ecr_repository.myapp.name
policy = jsonencode({
rules = [{
rulePriority = 1
description = "keep last 10 images"
selection = { tagStatus = "any", countType = "imageCountMoreThan", countNumber = 10 }
action = { type = "expire" }
}]
})
}
output "ecr_url" { value = aws_ecr_repository.myapp.repository_url }
app/ecs.tf (the execution role uses a managed policy first; module 5 tightens it and adds secrets)
variable "image_tag" {
type = string
default = "1.0"
}
resource "aws_cloudwatch_log_group" "myapp" {
name = "/ecs/${var.prefix}"
retention_in_days = 7
}
resource "aws_ecs_cluster" "main" {
name = "${var.prefix}-${var.env}"
setting {
name = "containerInsights"
value = "disabled" # saves money in the lab; use enabled or enhanced in production
}
}
data "aws_iam_policy_document" "ecs_tasks_trust" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "exec" {
name = "${var.prefix}-ecs-exec"
assume_role_policy = data.aws_iam_policy_document.ecs_tasks_trust.json
}
resource "aws_iam_role_policy_attachment" "exec_managed" {
role = aws_iam_role.exec.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
resource "aws_ecs_task_definition" "myapp" {
family = var.prefix
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = 256
memory = 512
execution_role_arn = aws_iam_role.exec.arn
runtime_platform {
operating_system_family = "LINUX"
cpu_architecture = "X86_64" # must match the image architecture; Graviton with ARM64 is cheaper
}
container_definitions = jsonencode([
{
name = "app"
image = "${aws_ecr_repository.myapp.repository_url}:${var.image_tag}"
essential = true
portMappings = [{ containerPort = 8000, protocol = "tcp" }]
environment = [{ name = "REDIS_HOST", value = "localhost" }]
dependsOn = [{ containerName = "redis", condition = "START" }]
healthCheck = {
command = ["CMD-SHELL", "python -c \"import urllib.request;urllib.request.urlopen('http://127.0.0.1:8000/healthz',timeout=2)\""]
interval = 15
timeout = 5
retries = 3
startPeriod = 10
}
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = aws_cloudwatch_log_group.myapp.name
awslogs-region = var.region
awslogs-stream-prefix = "app"
}
}
},
{
name = "redis"
image = "public.ecr.aws/docker/library/redis:7-alpine" # avoids Docker Hub anonymous pull rate limits
essential = true
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = aws_cloudwatch_log_group.myapp.name
awslogs-region = var.region
awslogs-stream-prefix = "redis"
}
}
}
])
}
app/alb.tf and the service
resource "aws_lb" "myapp" {
name = "${var.prefix}-${var.env}"
load_balancer_type = "application"
security_groups = [aws_security_group.alb.id]
subnets = module.vpc.public_subnets
}
resource "aws_lb_target_group" "myapp" {
name = "${var.prefix}-tg"
port = 8000
protocol = "HTTP"
target_type = "ip" # must be ip for Fargate
vpc_id = module.vpc.vpc_id
deregistration_delay = 30 # default 300 seconds; shortened for the lab
health_check {
path = "/healthz"
matcher = "200"
interval = 10
healthy_threshold = 2
unhealthy_threshold = 3
}
}
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.myapp.arn
port = 80
protocol = "HTTP" # production: 443 + ACM certificate, redirect 80 to 443
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.myapp.arn
}
}
resource "aws_ecs_service" "myapp" {
name = var.prefix
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.myapp.arn
desired_count = 2
launch_type = "FARGATE"
network_configuration {
subnets = module.vpc.private_subnets
security_groups = [aws_security_group.app.id]
assign_public_ip = false
}
load_balancer {
target_group_arn = aws_lb_target_group.myapp.arn
container_name = "app"
container_port = 8000
}
deployment_circuit_breaker {
enable = true
rollback = true
}
health_check_grace_period_seconds = 30
wait_for_steady_state = true
enable_execute_command = false
depends_on = [aws_lb_listener.http] # the target group must be attached to the ALB first, otherwise CreateService errors
}
output "url" { value = "http://${aws_lb.myapp.dns_name}" }
output "tg_arn" { value = aws_lb_target_group.myapp.arn }
EC2 + user_data (optional alternative for comparison)
data "aws_ssm_parameter" "al2023" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}
resource "aws_instance" "demo" {
ami = data.aws_ssm_parameter.al2023.value
instance_type = "t3.micro"
subnet_id = module.vpc.private_subnets[0]
vpc_security_group_ids = [aws_security_group.app.id]
iam_instance_profile = aws_iam_instance_profile.ec2.name # includes SSM and ECR read-only policy
user_data_replace_on_change = true # replace the instance when user_data changes (otherwise only attributes update and the script will not re-run)
metadata_options {
http_tokens = "required" # enforce IMDSv2
}
user_data = <<-EOF
#!/bin/bash
set -euxo pipefail
dnf install -y docker
systemctl enable --now docker
REG=${split("/", aws_ecr_repository.myapp.repository_url)[0]}
aws ecr get-login-password --region ${var.region} | docker login --username AWS --password-stdin $REG
docker network create mynet
docker run -d --restart=always --name redis --network mynet public.ecr.aws/docker/library/redis:7-alpine
docker run -d --restart=always --name app --network mynet -p 8000:8000 -e REDIS_HOST=redis \
${aws_ecr_repository.myapp.repository_url}:${var.image_tag}
EOF
lifecycle {
ignore_changes = [ami] # avoid replacing the instance on every new AMI release
}
}
user_data only runs on the first boot via cloud-init; to troubleshoot, check /var/log/cloud-init-output.log (log in via SSM Session Manager; no need to open port 22). In the heredoc, ${…} is interpolated by Terraform, and $REG is expanded by bash. For the instance profile and policy syntax, see module 5.
Lab 4: Fargate with myapp (about 9 min; ALB ≈ 0.025 USD/hour, 2 × 0.25 vCPU tasks ≈ 0.025 USD/hour)
cd ~/tf-lab/aws/app terraform apply -target=aws_ecr_repository.myapp -target=aws_ecr_lifecycle_policy.myapp -auto-approve ECR=$(terraform output -raw ecr_url); echo $ECR
111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp
-target Use this only for this kind of "chicken-and-egg" bootstrap; do not rely on it in day-to-day workflows.
aws ecr get-login-password --region ca-central-1 | docker login --username AWS --password-stdin ${ECR%%/*}
docker tag myapp:1.0 $ECR:1.0
docker push $ECR:1.0
aws ecr describe-images --repository-name myapp --query 'imageDetails[].[imageTags[0],imageSizeInBytes,imageScanStatus.status]' --output text
Login Succeeded 1.0: digest: sha256:7d9e…c41a size: 1993 1.0 52731210 COMPLETE
If you build on an Apple Silicon/ARM machine, the image will be arm64: either docker buildx build --platform linux/amd64, or change the task definition's cpu_architecture to ARM64, otherwise the task reports exec format error.
ecs.tf,alb.tf, then:
time terraform apply -auto-approve
aws_lb.myapp: Still creating... [2m10s elapsed] aws_lb.myapp: Creation complete after 2m42s [id=arn:aws:elasticloadbalancing:ca-central-1:111122223333:loadbalancer/app/myapp-lab/5f3c…] aws_ecs_service.myapp: Still creating... [1m00s elapsed] aws_ecs_service.myapp: Creation complete after 1m31s [id=arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp] Outputs: url = "http://myapp-lab-1234567890.ca-central-1.elb.amazonaws.com"
URL=$(terraform output -raw url)
for i in 1 2 3 4; do curl -s $URL/; echo; done
curl -s -o /dev/null -w "%{http_code}\n" $URL/healthz
aws elbv2 describe-target-health --target-group-arn $(terraform output -raw tg_arn) \
--query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State]' --output text
Hello from myapp! Visit count: 1 Hello from myapp! Visit count: 1 Hello from myapp! Visit count: 2 Hello from myapp! Visit count: 2 200 10.20.10.37 healthy 10.20.11.84 healthy
The count grows alternately across the two tasks — each task has its own Redis sidecar, which is the limitation mentioned in Principles. The output wording depends on your myapp version.
image_tag to a nonexistent 9.9:
terraform apply -var image_tag=9.9 -auto-approve 2>&1 | tail -4 aws ecs describe-services --cluster myapp-lab --services myapp --query 'services[0].events[:4].message' --output text
Error: waiting for ECS Service (…myapp) create/update: ... deployment failed: tasks failed to start. (service myapp) rolling back to deployment ecs-svc/9871234567890123456. (service myapp) (deployment ecs-svc/…) deployment failed: tasks failed to start. (service myapp) ... CannotPullContainerError: ... myapp:9.9: not found
The circuit breaker rolls the service back to revision 1,but the Terraform state records the failed revision 2. Run terraform apply again (without -var) so that the code, state and reality are consistent again.
terraform destroy -auto-approve (about 5 min, mostly waiting for the ALB and NAT to be deleted).Case 1: wanting to replace the task definition on every apply
Problem: CI publishes new images using aws ecs update-service --force-new-deployment and revisions it registers itself, so Terraform's next plan keeps changing the service back to the old revision. Approach: Be clear about “who owns the image version”: either CI passes the image tag in as a Terraform variable (-var image_tag=$GIT_SHA, recommended), or Terraform only creates the skeleton and, for task_definition uses lifecycle { ignore_changes = [task_definition] }, with deployment handed to CodeDeploy/CI. Limitations: The latter means Terraform no longer reflects the actual running version, which must be documented clearly.
Case 2: 502 errors during deployment
Problem: Each release causes ALB 502s for a few seconds. Approach: The application handles SIGTERM correctly (gunicorn exits gracefully); deregistration_delay should be longer than the longest request time; the container stopTimeout should be increased as appropriate; health checks should use a path that truly reflects readiness. Configuration: This is the same class of problem as the preStop sleep in the K8s course: leave time for propagation between deregistering the target and stopping the container. Limitations:deregistration_delay The larger it is, the slower the deployment.
Case 3: service creation failed — target group not attached to a load balancer
Problem: On the first apply, The target group ... does not have an associated load balancer occasionally appears. Approach: In Terraform's dependency graph, the service only references the target group and does not know it must wait for the listener to be created; add depends_on = [aws_lb_listener.http]. Limitations: This is a typical case of insufficient implicit dependencies; module 7 classifies it under dependency and eventual-consistency problems.
Common errors and fixes
CannotPullContainerError: pull image manifest has been retried 1 time(s): failed to resolve ref ...myapp:1.0: not found
Cause: The image tag does not exist, the repository name or region is wrong, or the architecture does not match (the multi-arch manifest has no matching platform).
aws ecr describe-images --repository-name myapp --query 'imageDetails[].imageTags' aws ecs describe-tasks --cluster myapp-lab --tasks $(aws ecs list-tasks --cluster myapp-lab --desired-status STOPPED --query 'taskArns[0]' --output text) --query 'tasks[0].stoppedReason'
Fix: Push the correct tag; in production, pin the version with an image digest (@sha256:…).
ResourceInitializationError: unable to pull secrets or registry auth: ... AccessDeniedException ... is not authorized to perform: secretsmanager:GetSecretValue
Cause: Image pulls and secret retrieval use the execution role, not the task role; the execution role may lack permissions, or the secret uses a customer-managed KMS key and is missing kms:Decrypt.
Fix: See module 5: add to the execution role secretsmanager:GetSecretValue on the secret's ARN.
Target.FailedHealthChecks / Health checks failed with these codes: [404] or Target.Timeout
Cause: Wrong health check path (404); the app only listens on 127.0.0.1; sg-app does not allow 8000 from sg-alb; or the app starts more slowly than the grace period.
aws elbv2 describe-target-health --target-group-arn TG_ARN --query 'TargetHealthDescriptions[].TargetHealth' aws logs tail /ecs/myapp --since 10m --follow
Fix: Confirm gunicorn --bind 0.0.0.0:8000, the path /healthz, and the security group references; increase health_check_grace_period_seconds.
Error: creating ECS Service: InvalidParameterException: The target group with targetGroupArn ... does not have an associated load balancer.
Cause: The service was created before the listener. Fix:depends_on = [aws_lb_listener.http].
Error: creating ECS Task Definition: ClientException: No Fargate configuration exists for given values: 256 CPU, 4096 memory.
Cause: The CPU/memory combination is invalid. Fix: Choose according to the Fargate combination table; for example, 256 CPU can only pair with 512/1024/2048 MiB.
exec /usr/local/bin/gunicorn: exec format error
Cause: The image architecture (arm64) does not match runtime_platform.cpu_architecture (X86_64). Fix:docker buildx build --platform linux/amd64 or change it to ARM64.
1. Check why the most recently stopped task stopped (including each container's exit code and reason).
T=$(aws ecs list-tasks --cluster myapp-lab --service-name myapp --desired-status STOPPED --query 'taskArns[0]' --output text)
aws ecs describe-tasks --cluster myapp-lab --tasks $T \
--query 'tasks[0].{stop:stoppedReason,containers:containers[].[name,exitCode,reason]}'2. Without changing code, temporarily scale the service to 0 tasks (to save money), then let Terraform restore it.
aws ecs update-service --cluster myapp-lab --service myapp --desired-count 0 terraform plan # will show drift from desired_count 0 → 2 terraform apply -auto-approve
apply succeeds and all targets are healthy, but users time out when accessing the ALB domain. What are the possible causes?
The requests never reach the targets: ① sg-alb does not allow inbound 80 (or only allows the company IP); ② the ALB is placed in private subnets (internal = true or subnets set to private_subnets); ③ the public subnet's route table does not point to the IGW; ④ the client network or proxy blocks it; ⑤ the listener port does not match the access port (accessing 443 with only an 80 listener). Use aws elbv2 describe-load-balancers --query 'LoadBalancers[0].[Scheme,AvailabilityZones[].SubnetId]' and the security group rules to check each item.
Verified teaching videos
No verified "Terraform + ECS Fargate + ALB" video was found (the tutorials found could not be confirmed via oEmbed); a storyboard script is provided.
Official docs
- aws_ecs_service
- aws_ecs_task_definition
- Amazon ECS on AWS Fargate
- Deployment circuit breaker
- terraform-aws-modules/ecs (7.x; can replace the native syntax used in this lesson)
Video storyboard (about 100 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: a developer machine runs docker push; the image flies into the ECR repository, and tag 1.0 is locked (IMMUTABLE).
Narration: first push the image to ECR. Make the tag immutable, so the same tag always points to the same image.
Scene: a task definition card unfolds, showing two containers, app and redis, with a localhost link between them; the card is stamped revision 1.
Narration: a task definition is like a Pod spec. Containers in the same task share a network, so myapp uses localhost to reach Redis.
Scene: the service launches new tasks; the status tags flip in turn to PROVISIONING, PENDING and RUNNING; the matching light in the target group turns from gray to green.
Narration: new tasks run first and pass the load balancer's health checks; only then are the old tasks deregistered, drained and stopped.
Scene: the image tag is written wrong, new tasks fail repeatedly, the circuit breaker trips, and the service returns to revision 1; the Terraform terminal shows the error.
Narration: the deployment circuit breaker rolls back automatically. Remember to run apply once more so that code, state and reality match again.
Module 5 · IAM and secrets: roles, least privilege, Secrets Manager
- Distinguish the IAM role's trust policy (who can assume it) and permissions policy (what it can do), and write policies with
aws_iam_policy_documentdata sources. - Distinguish the ECS task execution role (pulls images, fetches secrets, writes logs) and task role (application code calling AWS APIs); scope least privilege to resource ARNs.
- Inject secrets with Secrets Manager, and use ephemeral resources
aws_secretsmanager_random_password+ write-only argumentssecret_string_woso that secret values do not appear in plan and state.
sensitive. Importance:★★★★★What: the two policies of a role
| trust policy (assume_role_policy) | permissions policy (identity-based policy) | |
|---|---|---|
| answers the question | Who can assume me? | What can the people who assume me do? |
| Key elements | Principal Principal (such as ecs-tasks.amazonaws.com),sts:AssumeRole, conditions (aws:SourceAccount) | Action,Resource,Condition |
| Terraform | aws_iam_role.assume_role_policy | aws_iam_role_policy (inline) / aws_iam_policy + attachment |
The two ECS roles
Task execution role execution_role_arn | Task role task_role_arn | |
|---|---|---|
| Who uses it | ECS agent / Fargate platform (before the container starts) | The application code inside the container (the SDK obtains credentials via the container credentials endpoint) |
| Typical permissions | ecr:GetAuthorizationToken,ecr:BatchGetImage,logs:CreateLogStream/PutLogEvents,secretsmanager:GetSecretValue (only secrets referenced by the task definition) | What the application needs: e.g., s3:PutObject on a bucket,sqs:SendMessage |
| myapp | needed (ECR + Logs + 1 secret) | myapp does not call AWS APIs → can be left unset, or set to an empty-permissions role (easy to extend later and convenient for ECS Exec) |
Why: least privilege and secrets not in state
- Managed policy
AmazonECSTaskExecutionRolePolicyallows reading any ECR repositories (Resource: "*"), production should switch to a custom policy scoped to repository ARNs. - state is plain JSON. Any value passed to a resource as a regular argument (
secret_string,password,random_password.result) is written to state,sensitive = trueit is only hidden in CLI output,and it is not removed from state.
How: three ways to hand secrets to myapp
| Approach | Secrets in state? | Notes |
|---|---|---|
A. random_password resource + secret_string | yes (in two places) | the traditional approach; protected by state encryption and access control |
B. ephemeral aws_secretsmanager_random_password + write-only secret_string_wo + secret_string_wo_version | no | Terraform ≥ 1.11; the value only exists in memory during this run; to rotate, increase _wo_version by 1 |
C. Secrets are written by another process (manual or a rotation Lambda), and Terraform only creates an "empty shell" aws_secretsmanager_secret | no | the cleanest separation of duties; Terraform only knows the ARN |
Regardless of approach,the ECS task definition only references the secret ARN (secrets = [{ name, valueFrom }]). When the task starts, the execution role calls GetSecretValue, injecting it into the container as an environment variable. After the secret is updated,already running tasks do not automatically get the new value, so a new deployment must be triggered.
Overview of related capabilities (verified, aws 6.73.0)
- ephemeral resources:
aws_secretsmanager_random_password,aws_secretsmanager_secret_version,aws_ssm_parameter,aws_kms_secrets,aws_eks_cluster_auth,aws_ecr_authorization_token,aws_lambda_invocationetc. - write-only arguments:
aws_secretsmanager_secret_version.secret_string_wo,aws_db_instance.password_woetc. (each needs the matching*_wo_version). RDS can also usemanage_master_user_password = trueto have RDS itself generate and rotate the password in Secrets Manager. - ephemeral values can only be used in write-only arguments, provider configuration, other ephemeral resources,
localsand variables/outputs markedephemeral = truevariables or outputs; passing one to a regular argument produces an error. aws_secretsmanager_secret_versionThearnattribute is deprecated; usesecret_arninstead.
When: choosing a policy-writing approach
- Use
data "aws_iam_policy_document"instead of hand-writing JSON strings: it can reference resource ARNs, compose, and shows differences in the plan more clearly. - Inline policies (
aws_iam_role_policy) are tied to the role's lifecycle and suit role-specific permissions; standalone managed policies suit sharing across multiple roles. - When you want developers to be able to create roles but not exceed their own privileges, add a permissions boundary (
permissions_boundary).
Comparison with lesson 3 Azure
| Azure | AWS | |
|---|---|---|
| Workload identity | managed identity (system or user assigned) | IAM role (task role / instance profile) |
| Authorization model | RBAC role assignment to a scope | policy documents (Action/Resource/Condition) |
| Secrets | Key Vault + Container Apps secret references | Secrets Manager + task definition secrets.valueFrom |
| write-only | azurerm: some resources support *_wo (per the docs) | secret_string_wo,password_wo etc. |
sensitive = true does not enter state” — it is still in state. ③ “Using ephemeral is enough” — writing an ephemeral value into a regular argument errors out directly; it must be paired with a write-only argument. ④ “The container gets the new value automatically after the secret is updated” — environment-variable injection only happens when the task starts.Architecture diagram: who uses which role, and when
Data flow: lifecycle of a write-only secret
Interactive demo: where will the secret end up?
Choose one approach and step through it plan → apply → the task starts; on the right, the plan output and terraform.tfstate related fields in it are shown in real time.
Core resources and commands
| Resource / command | Purpose | Key arguments |
|---|---|---|
data "aws_iam_policy_document" | Generate the policy JSON | statement { actions, resources, condition, principals } |
aws_iam_role_policy | inline policy | role,policy |
ephemeral "aws_secretsmanager_random_password" | generate a random password (not stored in state) | password_length,exclude_punctuation → random_password |
aws_secretsmanager_secret_version.secret_string_wo | write the secret with write-only | paired with secret_string_wo_version |
aws iam simulate-principal-policy | simulate whether a role can perform an operation | --action-names,--resource-arns |
aws secretsmanager get-secret-value | verify that the secret was written (for the lab) | --query SecretString |
app/secrets.tf: secret not stored in state
resource "aws_secretsmanager_secret" "app" {
name = "${var.prefix}/app-secret"
recovery_window_in_days = 0 # lab: delete immediately so the same-named secret can be recreated; keep the default 30 in production
}
ephemeral "aws_secretsmanager_random_password" "app" {
password_length = 32
exclude_punctuation = true
}
variable "app_secret_version" {
type = number
default = 1 # rotation: change to 2 and apply again
}
resource "aws_secretsmanager_secret_version" "app" {
secret_id = aws_secretsmanager_secret.app.id
secret_string_wo = ephemeral.aws_secretsmanager_random_password.app.random_password
secret_string_wo_version = var.app_secret_version
}
app/iam.tf: least-privilege execution role (replacing the managed policy in module 4)
data "aws_iam_policy_document" "exec" {
statement {
sid = "EcrAuth"
actions = ["ecr:GetAuthorizationToken"]
resources = ["*"] # this action does not support resource-level permissions
}
statement {
sid = "EcrPull"
actions = ["ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage"]
resources = [aws_ecr_repository.myapp.arn]
}
statement {
sid = "Logs"
actions = ["logs:CreateLogStream", "logs:PutLogEvents"]
resources = ["${aws_cloudwatch_log_group.myapp.arn}:*"]
}
statement {
sid = "ReadAppSecret"
actions = ["secretsmanager:GetSecretValue"]
resources = [aws_secretsmanager_secret.app.arn]
}
}
resource "aws_iam_role_policy" "exec" {
name = "least-privilege"
role = aws_iam_role.exec.id
policy = data.aws_iam_policy_document.exec.json
}
# remove aws_iam_role_policy_attachment.exec_managed from module 4
data "aws_caller_identity" "me" {}
data "aws_iam_policy_document" "task_trust" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
condition { # guards against the confused deputy
test = "StringEquals"
variable = "aws:SourceAccount"
values = [data.aws_caller_identity.me.account_id]
}
}
}
resource "aws_iam_role" "task" {
name = "${var.prefix}-task"
assume_role_policy = data.aws_iam_policy_document.task_trust.json
}
reference the secret in the task definition (edit the app container in ecs.tf)
task_role_arn = aws_iam_role.task.arn # add at the top level of aws_ecs_task_definition
# add to the app container definition:
secrets = [
{ name = "APP_SECRET", valueFrom = aws_secretsmanager_secret.app.arn }
# to take one key from a JSON secret: valueFrom = "${aws_secretsmanager_secret.app.arn}:password::"
]
ROLE_ARN=$(aws iam get-role --role-name myapp-ecs-exec --query Role.Arn --output text) aws iam simulate-principal-policy --policy-source-arn $ROLE_ARN \ --action-names secretsmanager:GetSecretValue s3:ListAllMyBuckets \ --resource-arns $(aws secretsmanager describe-secret --secret-id myapp/app-secret --query ARN --output text) \ --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text
secretsmanager:GetSecretValue allowed s3:ListAllMyBuckets implicitDeny
How to verify the secret is not in state:terraform state pull | grep -c "$(aws secretsmanager get-secret-value --secret-id myapp/app-secret --query SecretString --output text)" should output 0. Common errors: forgetting _wo_version (the error asks for it to be set); Terraform < 1.11 does not recognize write-only.
Lab 5: least privilege + secret injection + state check (about 6 min; Secrets Manager ≈ 0.40 USD/secret/month, prorated by time)
exec_managed attachment, and add to the task definition task_role_arn and secrets. First look at the plan:
cd ~/tf-lab/aws/app terraform plan | grep -E "secret_string_wo|will be|must be replaced|Plan:"
# aws_ecs_service.myapp will be updated in-place
# aws_ecs_task_definition.myapp must be replaced
# aws_iam_role.task will be created
# aws_iam_role_policy.exec will be created
# aws_iam_role_policy_attachment.exec_managed will be destroyed
# aws_secretsmanager_secret.app will be created
# aws_secretsmanager_secret_version.app will be created
+ secret_string_wo = (write-only attribute)
Plan: 5 to add, 1 to change, 2 to destroy.terraform apply -auto-approve aws secretsmanager get-secret-value --secret-id myapp/app-secret --query 'length(SecretString)' aws ecs describe-task-definition --task-definition myapp --query 'taskDefinition.containerDefinitions[0].secrets'
32
[
{
"name": "APP_SECRET",
"valueFrom": "arn:aws:secretsmanager:ca-central-1:111122223333:secret:myapp/app-secret-Ab12Cd"
}
]terraform state show aws_secretsmanager_secret_version.app S=$(aws secretsmanager get-secret-value --secret-id myapp/app-secret --query SecretString --output text) terraform state pull | grep -c "$S"; unset S
# aws_secretsmanager_secret_version.app:
resource "aws_secretsmanager_secret_version" "app" {
has_secret_string_wo = true
id = "arn:aws:secretsmanager:…:secret:myapp/app-secret-Ab12Cd|terraform-2026…"
secret_arn = "arn:aws:secretsmanager:…:secret:myapp/app-secret-Ab12Cd"
secret_string_wo_version = 1
version_id = "terraform-20261115…"
version_stages = ["AWSCURRENT"]
}
0terraform apply -var app_secret_version=2 -auto-approve aws ecs update-service --cluster myapp-lab --service myapp --force-new-deployment --query 'service.deployments[0].status'
The second command triggers a new deployment, and the new task reads the new value at startup. In production, you can make the "secret version number" an environment variable of the task definition, so that Terraform naturally produces a new revision instead of forcing it manually.
secret_string_wo with a plain random_password resource + secret_string, run terraform state pull | jq '.resources[] | select(.type=="random_password") | .instances[0].attributes.result', and you will see plaintext. Revert immediately after looking. Cleanup: is destroyed together with app in module 8; recovery_window_in_days = 0 makes the secret delete immediately.Case 1: state leak causes database password exposure
Problem: A team granted read access to the state bucket to all developers (“just to look”), while RDS password keeps it in plaintext in state. Approach: Migrate to manage_master_user_password = true (managed and rotated by RDS) or password_wo; rotate the existing password; restrict state read access to the CI role. Limitations: Old state versions still contain the old password; clean up old versions according to the retention policy, or accept that the old password has been rotated and is invalid.
Case 2: overly broad managed policy
Problem: A security audit found that the execution roles of all services had AmazonECSTaskExecutionRolePolicy attached, which can pull images from any repository in the account. Approach: Use IAM Access Analyzer to generate a policy from CloudTrail, or follow this lesson's iam.tf pattern to scope by repository, log group or secret ARN; use policy checks in CI (lessons 5 and 7). Limitations:ecr:GetAuthorizationToken It must be *.
Case 3: privilege escalation risk from developer-created roles
Problem: The platform allowed application teams to create their own IAM roles with Terraform, but someone created a role with AdministratorAccess attached. Approach: The deployment role may only create roles with a specified permissions_boundary (IAM condition iam:PermissionsBoundary), and all role names carry a prefix; SCPs forbid modifying boundary policies. Limitations: A boundary only limits the maximum permissions; it does not grant any.
Common errors and fixes
ResourceInitializationError: unable to pull secrets or registry auth: execution resource retrieval failed: unable to retrieve secret from asm: ... AccessDeniedException
Cause: The execution role lacks the secretsmanager:GetSecretValue permission on this secret; or the secret uses a customer-managed KMS key and lacks kms:Decrypt; or valueFrom uses the name while the ARN suffix does not match.
aws iam simulate-principal-policy --policy-source-arn EXEC_ROLE_ARN --action-names secretsmanager:GetSecretValue --resource-arns SECRET_ARN
Fix: Grant the full secret ARN in the execution role policy (including the 6-character random suffix; use aws_secretsmanager_secret.app.arn references).
Error: Invalid use of ephemeral value ... Ephemeral values are not valid in "secret_string", because it is not a write-only attribute
Cause: An ephemeral value was passed to a regular argument.
Fix: Use secret_string_wo + secret_string_wo_version.
Error: ... InvalidRequestException: You can't create this secret because a secret with this name is already scheduled for deletion.
Cause: By default, deleting a secret has a 7–30 day recovery window, so a same-named secret cannot be recreated immediately.
aws secretsmanager delete-secret --secret-id myapp/app-secret --force-delete-without-recovery
Fix: In the lab, set recovery_window_in_days = 0; or run the forced deletion above (not recoverable!); or restore-secret , then import.
Error: creating IAM Role: MalformedPolicyDocument: Invalid principal in policy: "SERVICE":"ecs-task.amazonaws.com"
Cause: The service principal is misspelled (the correct form is ecs-tasks.amazonaws.com). Fix: Use aws_iam_policy_document and check against the docs.
Application log: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation
Cause: The application calls AWS APIs using the task role, without task_role_arn set, or the task role lacks permissions. Fix: Grant the task role permissions scoped to the bucket ARN, not the execution role.
1. List the resource types in state that may contain plaintext secrets (a rough screen).
terraform state pull | jq -r '.resources[] | select(.type | test("random_password|secret_version|db_instance|tls_private_key")) | "\(.type).\(.name)"'2. Check whether the execution role still has broad managed policies attached.
aws iam list-attached-role-policies --role-name myapp-ecs-exec --query 'AttachedPolicies[].PolicyName' aws iam list-role-policies --role-name myapp-ecs-exec
The security team requires: “no secret may appear in Terraform state or CI logs, and secrets must be rotated every 30 days”. Give the design for myapp.
① The secret is created by aws_secretsmanager_secret as an empty shell; the value uses an ephemeral random password plus secret_string_wo to write it (or a rotation Lambda writes it, with Terraform managing only the ARN); ② configure rotation with aws_secretsmanager_secret_rotation (rotation_rules { automatically_after_days = 30 }); ③ the task definition only references the ARN; after rotation, deploy again so the task reads the new value (or the app reads the secret through the SDK with caching, using the task role); ④ CI does not output sensitive values in the plan (write-only values show as a write-only attribute in the plan); ⑤ the state bucket's KMS plus minimal read permissions as defense in depth.
Verified teaching videos
No verified video on Terraform ephemeral resources / write-only arguments was found; a storyboard script is provided.
Official docs
- Terraform: ephemeral values / write-only arguments
- aws_secretsmanager_secret_version (secret_string_wo)
- ECS task execution IAM role
- Use Secrets Manager to pass sensitive data to containers
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: two badges; one reads "Execution role: pull images, fetch secrets, write logs", the other reads "Task role: application calls AWS".
Narration: ECS has two roles. The execution role works for the platform before the container starts; the task role works for your code inside the container.
Scene: a magnifying glass scans a state file; in the traditional approach the password is highlighted in red; after switching to the write-only approach, the same spot shows has secret string wo equal to true.
Narration: a plain argument writes the secret into state. Use a temporary resource to generate the password and hand it to a write-only argument; only a marker remains in state.
Scene: the task definition holds only one ARN; when the task starts, the value is fetched from Secrets Manager and becomes an environment variable; the version number goes from one to two, and the new task replaces the old one.
Narration: the task definition only stores the address of the secret. To rotate, increment the version number and start a deployment; the new tasks will read the new value.
Module 6 · Community modules and EKS
- Evaluate community modules (maintenance activity, provider constraints, inputs and outputs, breaking-change notes), lock versions correctly, and know that
.terraform.lock.hcldoes not lock modules. - Use
terraform-aws-modules/eksv21 to create an EKS Auto Mode cluster (compute_config), configure access entries (access entries), and useaws eks update-kubeconfigto connect. - Understand the risks of deploying in-cluster resources with kubernetes/helm providers in the same root module, and the residues left behind when deleting EKS (load balancers, ENIs, security groups).
What: terraform-aws-modules
terraform-aws-modules is a community-maintained collection of AWS modules (started by Anton Babenko); the vpc (6.7.3),eks (21.29.0),ecs (7.6.1) used in this lesson all come from it (versions verified via the Registry API on 2026-11-15). The v6/v21/v7 generation of major versions was rewritten for aws provider 6.x, and variable names changed significantly (for example, the eks module uses name,kubernetes_version).
Why: use a module or write it by hand
| Community module | Hand-written native resources | |
|---|---|---|
| Speed | a few dozen lines to build the 30+ resources EKS needs | Slow; you need to understand each resource |
| Best practice | Built-in (IRSA/Pod Identity, encryption, access entries, tags) | Do it yourself |
| Controllability | Limited to the variables the module exposes; a major version upgrade may require moved | Fully controllable |
| Supply chain risk | Introduces third-party code; requires pinning versions and reviewing changes | None |
How: module versions and locking
- Registry modules use
version = "~> 21.0"(allows minor and patch upgrades within 21.x) or pin an exact version"21.29.0"(recommended for production, together with Renovate/Dependabot upgrade PRs). .terraform.lock.hclOnly the provider is locked, the module version is not locked; the module version is entirely determined byversionconstraints. Where security requirements are high, you can use a Git source and pin the commit SHA:source = "git::https://github.com/terraform-aws-modules/terraform-aws-eks.git?ref=<commit-sha>".- Modules are downloaded to
.terraform/modules/, and you can read the source directly to confirm what they create (terraform planentries in it look likemodule.eks.aws_eks_cluster.this[0]). - Before upgrading a major version, read
UPGRADE-xx.md, which often requiresmovedblocks orterraform state mv(lesson 2).
EKS Auto Mode
In Auto Mode, EKS manages compute (node auto-provisioning based on Karpenter), storage (EBS CSI), load balancing (AWS Load Balancer Controller capabilities), networking (VPC CNI) and core add-ons, so you no longer manage node groups. The eks module v21 enables it with compute_config = { enabled = true, node_pools = ["general-purpose"] } . The module README specifically notes: To turn off Auto Mode, you must first apply compute_config = { enabled = false }, and only then can the block be deleted.
| Compute approach | Who manages nodes | Syntax in Terraform |
|---|---|---|
| Auto Mode | EKS (NodePool/NodeClass) | compute_config |
| managed node groups | EKS manages the ASG; you choose instance types/AMI | eks_managed_node_groups |
| Fargate Profile | no nodes (one micro-VM per Pod) | fargate_profiles |
| self-managed Karpenter | you deploy and upgrade Karpenter | modules/karpenter submodule + Helm |
Versions and costs (verified): EKS currently supports standard versions 1.34–1.37 (1.37 was released on EKS on 2026-10-01, with standard support until 2027-12-01); 1.31–1.33 are in extended support (extra charges). The control plane costs 0.10 USD/hour during standard support; extended support costs more. Auto Mode charges a management fee on top of EC2 instance costs — for specifics, see the EKS pricing pagefor details.
When: ECS or EKS
- A single application or a few services, with a team unfamiliar with Kubernetes → ECS Fargate (this lesson's capstone lab).
- Multi-team platforms that need the Kubernetes ecosystem (Helm, Operators, GitOps) and portability → EKS (Auto Mode reduces the operational burden).
- Terraform owns "cluster + cloud-side dependencies"; in-cluster applications are handed to Argo CD/Flux or a separate root module.
Comparison with lesson 3 Azure
| AKS (azurerm) | EKS (aws + eks module) | |
|---|---|---|
| Control plane cost | Free tier is free; Standard/Premium charge | 0.10 USD/hour (standard support) |
| “fully managed nodes” | AKS Automatic | EKS Auto Mode |
| Identity to K8s | Entra ID integration + Azure RBAC | access entries + access policies |
| Pod access to cloud APIs | Workload Identity | EKS Pod Identity / IRSA |
~> 21.0 is very safe” — a minor version may also introduce new defaults; in production, pin an exact version and review upgrade PRs. ③ “Creating the cluster and installing apps with the helm provider in the same apply is fine” — when the provider configuration depends on a cluster endpoint that does not exist yet, the value is unknown at plan time, which easily causes authentication failures and a messed-up deletion order; splitting into two root modules is recommended. ④ “terraform destroy will delete everything the cluster created” — load balancers (ALB/NLB) created by Kubernetes Services (type LoadBalancer), and EC2 instances and ENIs started by Auto Mode, are not in the Terraform state, so they must be deleted inside the cluster first.Architecture diagram: what the eks module creates
Flowchart: order of creation and deletion
Interactive demo: EKS creation dependency graph and timing
Terraform creates resources in parallel according to the dependency graph (default -parallelism=10). Click play to see which resources run in parallel, which one is the critical path, and what the provider waiter is waiting for (DescribeCluster until status = ACTIVE). Times are typical illustrative values.
Core configuration and commands
| Command / configuration | Purpose | Notes |
|---|---|---|
terraform init -upgrade | Upgrade modules and providers within constraints | The module version is decided only by version . |
terraform get -update | Update only the module | — |
terraform providers | View the provider constraint tree of the root module and submodules | Troubleshoot version conflicts (e.g., the eks module requires aws ≥ 6.59) |
aws eks update-kubeconfig | Write kubeconfig | --name,--region,--alias |
aws eks list-access-entries | See who can access the cluster | API authentication mode |
aws eks describe-cluster-versions | View available K8s versions and support windows | Choose kubernetes_version |
eks/main.tf (Auto Mode, optional lab)
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.59" # the eks module v21 requires >= 6.59
}
}
}
provider "aws" {
region = "ca-central-1"
default_tags { tags = { Project = "myapp-tf-lab", ManagedBy = "terraform", Layer = "eks" } }
}
data "aws_availability_zones" "azs" {
state = "available"
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "6.7.3"
name = "myapp-eks"
cidr = "10.30.0.0/16"
azs = slice(data.aws_availability_zones.azs.names, 0, 3)
public_subnets = ["10.30.0.0/24", "10.30.1.0/24", "10.30.2.0/24"]
private_subnets = ["10.30.16.0/20", "10.30.32.0/20", "10.30.48.0/20"] # Pods also consume IPs, so make these large
enable_nat_gateway = true
single_nat_gateway = true
public_subnet_tags = { "kubernetes.io/role/elb" = 1 }
private_subnet_tags = { "kubernetes.io/role/internal-elb" = 1 }
}
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "21.29.0"
name = "myapp-eks"
kubernetes_version = "1.37" # confirm first with aws eks describe-cluster-versions
endpoint_public_access = true # convenient for the lab; in production use a CIDR allowlist or a private endpoint
enable_cluster_creator_admin_permissions = true # adds the current caller as cluster admin (access entry)
compute_config = {
enabled = true
node_pools = ["general-purpose"]
}
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.private_subnets
}
output "cluster_name" { value = module.eks.cluster_name }
Module input names follow the Inputs table in the v21 README (verified name,kubernetes_version,endpoint_public_access,enable_cluster_creator_admin_permissions,compute_config,vpc_id,subnet_ids). endpoint_public_access and enable_cluster_creator_admin_permissions both default to false—if you don't turn them on, you can't connect from this machine, or you can connect but have no permissions.
If you really must configure the kubernetes provider in the same root module
provider "kubernetes" {
host = module.eks.cluster_endpoint
cluster_ca_certificate = base64decode(module.eks.cluster_certificate_authority_data)
exec { # obtains the token on each call to avoid token expiry
api_version = "client.authentication.k8s.io/v1beta1"
command = "aws"
args = ["eks", "get-token", "--cluster-name", module.eks.cluster_name]
}
}
# you can also use ephemeral "aws_eks_cluster_auth" to get the token (the token does not enter state).
# Still recommended: one root module for the cluster, and another root module (or GitOps) for in-cluster resources.
cd ~/tf-lab/aws/eks aws eks describe-cluster-versions --query 'clusterVersions[?status==`STANDARD_SUPPORT`].clusterVersion' --output text terraform init && time terraform apply -auto-approve aws eks update-kubeconfig --name myapp-eks --region ca-central-1 kubectl get nodes; kubectl get nodepools
1.37 1.36 1.35 1.34 Apply complete! Resources: 52 added, 0 changed, 0 destroyed. real 13m41s Added new context arn:aws:eks:ca-central-1:111122223333:cluster/myapp-eks to /home/andy/.kube/config No resources found NAME NODECLASS NODES READY AGE general-purpose default 0 True 9m
Note: In Auto Mode, the node count can be 0 when there are no Pods to schedule; EC2 instances are provisioned only after the first workload is deployed. Resource counts are examples.
Lab 6 (optional): EKS Auto Mode cluster (about 25 min including waiting; cost ≈ 0.10 USD/hour control plane + NAT + nodes; delete immediately when done)
mkdir -p ~/tf-lab/aws/eks && cd ~/tf-lab/aws/eks # after saving main.tf terraform init ls .terraform/modules/ terraform plan -out=eks.tfplan | grep -E "^ # module\.eks\." | sed 's/ will be created//' | head -20
eks eks.kms modules.json vpc # module.eks.aws_cloudwatch_log_group.this[0] # module.eks.aws_eks_access_entry.this["cluster_creator"] # module.eks.aws_eks_access_policy_association.this["cluster_creator_admin"] # module.eks.aws_eks_cluster.this[0] # module.eks.aws_iam_role.eks_auto[0] # module.eks.aws_iam_role.this[0] # module.eks.module.kms.aws_kms_key.this[0] …
terraform providers | head -15
Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/aws] ~> 6.59
├── module.vpc
│ └── provider[registry.terraform.io/hashicorp/aws] >= 6.28
└── module.eks
├── provider[registry.terraform.io/hashicorp/aws] >= 6.59
├── provider[registry.terraform.io/hashicorp/tls] >= 4.0
├── provider[registry.terraform.io/hashicorp/time] >= 0.9
└── module.kms …terraform apply eks.tfplan aws eks update-kubeconfig --name myapp-eks --region ca-central-1 kubectl create deployment hello --image=public.ecr.aws/nginx/nginx:stable --replicas=2 kubectl get pods -w # Running in about 1 minute (Auto Mode provisions nodes first) kubectl get nodes -o wide
hello-6d8f9c7b5d-2xk4p 0/1 Pending 0 5s hello-6d8f9c7b5d-2xk4p 1/1 Running 0 58s NAME STATUS ROLES AGE VERSION INTERNAL-IP i-0a1b2c3d4e5f60789 Ready <none> 40s v1.37.x-eks-… 10.30.21.14
kubectl delete deployment hello kubectl get svc -A | grep LoadBalancer # must be empty; if not, delete them first sleep 60 # wait for Auto Mode to reclaim idle nodes terraform destroy -auto-approve aws ec2 describe-instances --filters Name=tag:eks:eks-cluster-name,Values=myapp-eks Name=instance-state-name,Values=running --query 'Reservations[].Instances[].InstanceId'
Destroy complete! Resources: 52 destroyed. []
Instance label keys depend on the actual values (you can check them with aws ec2 describe-instances --query 'Reservations[].Instances[].Tags' ). If the last command returns an empty array, there are no leftover nodes.
Case 1: a minor module version upgrade removed cluster access
Problem: A team using ~> 20.0 got the new version automatically in a CI run; the plan showed an access entry being deleted, the reviewer missed it, and after apply the CI role lost cluster access. Approach: Switch to an exact version; upgrades go through Renovate PRs that include the plan output and require platform team approval; add prevent_destroy to key resources. Limitations: Exact versions require sustained upgrade effort; otherwise they become harder and harder to manage.
Case 2: VPC deletion stuck for 20 minutes
Problem:terraform destroy Stuck deleting subnets and security groups, eventually failing with DependencyViolation. The cause was a Service type=LoadBalancer created an NLB, which is not in state. Approach: The destroy pipeline runs kubectl delete svc,ingress -A --all before destroy (excluding required kube-system objects) and waits; or manage these Services with Terraform and make sure they are deleted before the cluster. Limitations: Once stuck, the only option is to delete the LB manually and retry destroy (module 7).
Case 3: migrating from managed node groups to Auto Mode
Problem: The ops team wants less node AMI upkeep. Approach: In the module, first add compute_config to enable Auto Mode alongside the existing node groups; gradually move workloads to Auto Mode nodes with node selectors/taints; finally delete eks_managed_node_groups. Limitations: Auto Mode has an extra management fee, and some customizations (such as specific AMIs or daemonsets) are restricted; validate in non-production first.
Common errors and fixes
Error: Unsupported argument ... An argument named "cluster_name" is not expected here.
Cause: The v20 example was copied as-is; v21 uses new variable names such as name,kubernetes_version etc.
Fix: Check against the v21 README Inputs and UPGRADE-21.0.md; do not mix examples from different major versions.
Error: Failed to query available provider packages ... no available releases match the given constraints ~> 6.0, >= 6.59, < 6.10
Cause: The provider constraints in the root module or other modules conflict with the eks module (≥ 6.59), or the lock file is pinned to an older version.
terraform providers terraform init -upgrade
Fix: Relax the conflicting constraints and init -upgrade update the lock file.
error: You must be logged in to the server (Unauthorized) / kubectl: the server has asked for the client to provide credentials
Cause: The current IAM identity has no access entry (for example, the cluster was created by the CI role without enable_cluster_creator_admin_permissions, or you are using a different SSO role).
aws sts get-caller-identity aws eks list-access-entries --cluster-name myapp-eks
Fix: In the module access_entries add an entry for your role and associate AmazonEKSClusterAdminPolicy (or a more limited policy).
Error: Get "http://localhost/api/v1/namespaces/...": dial tcp [::1]:80: connect: connection refused
Cause: The kubernetes/helm provider is initialized while the cluster does not yet exist or has already been deleted; configuration values are unknown/empty and fall back to the localhost default.
Fix: Split the in-cluster resources into a separate root module; or first terraform apply -target=module.eks and then run a full apply (a temporary workaround only). When destroying, delete the in-cluster resources first.
Pod stays Pending: 0/0 nodes are available ... (Auto Mode has not provisioned nodes)
Cause: The node pool is not enabled, the private subnets have no outbound path (nodes cannot join), or the requested resources exceed the NodePool limits.
kubectl get nodepools,nodeclaims kubectl describe nodeclaim | tail -20
Fix: Check compute_config.node_pools, NAT routes; refer to the K8s course's Pending troubleshooting tree.
1. List all modules used by the current root module and the versions actually downloaded.
jq -r '.Modules[] | "\(.Key)\t\(.Source)\t\(.Version // "-")"' .terraform/modules/modules.json
2. Before destroy, find all objects in the cluster that create AWS load balancers.
kubectl get svc -A -o jsonpath='{range .items[?(@.spec.type=="LoadBalancer")]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'
kubectl get ingress -AA team wants to create EKS in one root module, install Argo CD with the helm provider, and create namespaces with the kubernetes provider. What is your review comment?
Risks: ① the provider configuration depends on cluster outputs, so values are unknown at the first plan; ② when the cluster is replaced or deleted, the helm/kubernetes providers lose their connection first, so destroy fails or leaves residues such as LBs; ③ the blast radius is large, so one change affects every layer of the platform. Recommendation: split into eks/ (cluster + cloud-side dependencies) and platform/ (Argo CD and similar), where the latter reads cluster information through terraform_remote_state or data sources aws_eks_cluster to read cluster information; hand the application layer to Argo CD. If it must be in the same module, use exec authentication and delete in-cluster resources first in the destroy pipeline.
Verified teaching videos
No verified Terraform video dedicated to the eks module v21 / EKS Auto Mode was found; a storyboard script is provided.
Official docs
- terraform-aws-modules/eks
- EKS Auto Mode
- EKS Kubernetes version lifecycle
- EKS access entries
- Terraform module sources and versions
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: a 30-line module "eks" code block expands into a tree of 50+ resources.
Narration: a community module packs dozens of resources into dozens of lines of configuration. Before using it, look at what it creates.
Scene: the lock file has only the provider's hash; a question mark appears beside the module; then a version equal to 21.29.0 appears.
Narration: the lock file locks only the provider, not the module. The module version depends entirely on the version constraint, so lock an exact version in production.
Scene: a timeline — VPC two minutes, cluster ten minutes, access entries a few seconds; once Pods appear, Auto Mode launches an EC2 instance automatically.
Narration: the cluster is the critical path and takes about ten minutes. In Auto Mode, EKS provisions nodes only when Pods need scheduling.
Scene: destroy gets stuck with a red DependencyViolation notice; the view cuts to kubectl delete svc, and the second destroy succeeds.
Narration: before deleting the cluster, delete the Services and Ingresses that create load balancers, otherwise the VPC cannot be deleted.
Module 7 · Cloud troubleshooting in practice
- Classify an error message into one of six categories: credential chain, IAM authorization (including SCP/boundary/resource policies), resource dependencies (DependencyViolation), eventual consistency, API throttling, and service quotas.
- Skillfully use diagnostic tools:
sts get-caller-identity,sts decode-authorization-message,iam simulate-principal-policy,TF_LOG_PROVIDER, CloudTraillookup-events, Service Quotas. - Handle destroy hangs/failures: find dependencies not in state (ENIs, LBs, manually created resources), remediate safely, and make state match reality.
What: the six major categories of AWS errors
| Category | Typical error keywords | Who refused you | First diagnostic command |
|---|---|---|---|
| ① Credential chain | No valid credential sources,ExpiredToken,InvalidClientTokenId,SSO session has expired | SDK / STS (has not reached the target service yet) | aws sts get-caller-identity |
| ② IAM authorization | AccessDenied,UnauthorizedOperation,not authorized to perform,explicit deny in a service control policy | IAM policy evaluation engine | decode-authorization-message / simulate-principal-policy |
| ③ Resource dependencies | DependencyViolation,has a dependent object,ResourceInUse,BucketNotEmpty | target service (resource still referenced) | describe-network-interfaces --filters group-id/subnet-id |
| ④ Eventual consistency | NotFound right after creation, NotFound,InvalidGroup.NotFound,role cannot be assumed,Invalid principal | target service (data not yet propagated) | retry; check whether the provider version already has built-in retries |
| ⑤ Throttling | RequestLimitExceeded,ThrottlingException,Rate exceeded,TooManyRequestsException | API rate limits (token bucket) | TF_LOG_PROVIDER=DEBUG check the retry count |
| ⑥ Quotas | LimitExceeded,VpcLimitExceeded,AddressLimitExceeded,You have requested more vCPU capacity | account/region quotas | aws service-quotas get-service-quota |
Why: why cloud troubleshooting is harder
- Partial success: when apply fails midway, resources already created are written to state, and failed resources may be marked tainted; do not rush to delete state — first
terraform planlook at the current situation. - The world outside state: ECS/EKS/Lambda create ENIs, load balancers and security group rules on your behalf; they are not in state, yet they block deletion.
- Async and propagation: IAM is a global service, and changes take time to propagate to each region; many "create" APIs return immediately while resources are still pending. The aws provider has built-in retries for known consistency issues (commonly up to several minutes), but new services and new scenarios can still hit them.
How: simplified IAM evaluation logic
- Is there any explicit Deny (identity policies, resource policies, SCPs, RCPs, permissions boundaries, session policies)? If yes → deny.
- Organizations SCP Is it allowed? No → deny (the error message will state
service control policy). - Does the resource policy allow it (in the same account, it can be granted separately)?
- permissions boundary, does the session policy allow it? No → deny.
- Does the identity policy allow it? No → implicit deny (implicitDeny).
Since 2024, AccessDenied messages usually state the type of denying source (such as because no identity-based policy allows,with an explicit deny in a service control policy). For services such as EC2, the message is returned as Encoded authorization failure message, which must be decoded with aws sts decode-authorization-message (the caller needs sts:DecodeAuthorizationMessage permission).
When: handling principles
| Situation | Correct approach | Don't |
|---|---|---|
| apply fails midway | fix the cause and run plan/apply again; Terraform continues from the current state | manually delete resources or edit state |
| destroy is blocked by a dependency not in state | find the dependency (ENI/LB) → delete it in the system that owns it → retry destroy | terraform state rm then "pretend it was deleted" (leaves billable resources behind) |
| eventual consistency | just retry; if necessary add depends_on or time_sleep (hashicorp/time) as a last resort | sprinkle sleep everywhere |
| throttling | reduce -parallelism (e.g., to 5),retry_mode = "adaptive", split a large state | raise max_retries very high to hide the problem |
| a resource takes a long time to create/delete | use the timeouts { create = "30m" } block of the resource | Ctrl+C interruption (leaves locks and inconsistency) |
* permissions” — first confirm which policy is denying; when an SCP denies, adding identity policies is useless. ② “If destroy fails, just state rm” — the resource is still billed. ③ “Throttling is an AWS outage” — usually it is your own concurrency (multiple pipelines + a large state) exceeding the account-level API rate; all tools using the same account/region share that quota. ④ “A provider error must be a code error” — many are environment problems (credentials, quotas, leftover resources); check the error classification first.Diagram: where an API request can be refused
Diagram: why destroy gets blocked by “invisible dependencies”
Interactive demo: failure replayer
Choose a real failure scenario and step through it: Terraform output → the diagnostic command you run → root cause → fix → verification. The API names and error text in the logs follow the real formats of AWS/Terraform (IDs are examples).
Diagnostic toolbox
| Command | Purpose | Notes |
|---|---|---|
aws sts get-caller-identity | Who am I | first step for any error |
aws sts decode-authorization-message --encoded-message MSG | Decode the authorization failure message from services such as EC2 | in the output matchedStatements,explicitDeny |
aws iam simulate-principal-policy | Simulate policy evaluation | does not consider SCPs (check at the Organizations level) |
aws cloudtrail lookup-events | Look up recent API calls and error codes | management events, with a delay of a few minutes |
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=… | provider requests/responses, retries | contains sensitive information |
aws ec2 describe-network-interfaces --filters | Find the ENIs occupying subnets/security groups | Name=group-id,Name=subnet-id |
aws service-quotas get-service-quota / request-service-quota-increase | Check/request quotas | quota code such as L-F678F1CE (VPCs per region) |
terraform apply -parallelism=5 | reduce concurrency | ease throttling |
terraform apply -replace=ADDR | force replacement of a resource | replace the deprecated taint |
# decode an authorization failure message (attached when EC2 reports UnauthorizedOperation)
aws sts decode-authorization-message --encoded-message "$MSG" --query DecodedMessage --output text \
| jq '{allowed, explicitDeny, action: .context.action, resource: .context.resource, matched: .matchedStatements}'
{
"allowed": false,
"explicitDeny": true,
"action": "ec2:RunInstances",
"resource": "arn:aws:ec2:ca-central-1:111122223333:instance/*",
"matched": { "items": [ { "statementId": "DenyLargeInstances", "effect": "DENY", … } ] }
}
# find the ENI blocking deletion of the security group SG=sg-0123456789abcdef0 aws ec2 describe-network-interfaces --filters Name=group-id,Values=$SG \ --query 'NetworkInterfaces[].[NetworkInterfaceId,InterfaceType,Status,Description,RequesterId]' --output table
---------------------------------------------------------------------------------------------- | DescribeNetworkInterfaces | +------------------------+-------------+---------+----------------------------------+--------+ | eni-0f9e8d7c6b5a43210 | interface | in-use | arn:aws:ecs:…:attachment/9a8b… | … | +------------------------+-------------+---------+----------------------------------+--------+
# CloudTrail: failed calls in the past hour (by error code) aws cloudtrail lookup-events --start-time $(date -u -d '-1 hour' +%FT%TZ) --max-results 50 \ --query 'Events[].CloudTrailEvent' --output text | jq -r 'select(.errorCode) | [.eventTime,.eventName,.errorCode,.errorMessage] | @tsv'
# long-running resources: custom timeouts
resource "aws_nat_gateway" "x" {
# ...
timeouts {
create = "15m"
delete = "30m"
}
}
# provider level: adaptive retries (large accounts with severe throttling)
provider "aws" {
retry_mode = "adaptive"
max_retries = 25
}
Lab 7: deliberately trigger 3 faults and fix them (about 7 min; cost ≈ 0)
Do this in the app environment of modules 3–5 (requires an applied VPC and security groups).
AWS_PROFILE=does-not-exist terraform plan 2>&1 | grep -m2 Error aws sso logout; terraform plan 2>&1 | grep -m1 -i "sso\|credential" aws sso login --profile tf-lab
Error: failed to get shared config profile, does-not-exist Error: ... failed to refresh cached credentials, the SSO session has expired or is invalid
SUBNET=$(terraform output -json private_subnets | jq -r '.[0]') SG=$(terraform output -raw app_sg_id) ENI=$(aws ec2 create-network-interface --subnet-id $SUBNET --groups $SG --description "orphan-demo" --query NetworkInterface.NetworkInterfaceId --output text) terraform destroy -target=aws_security_group.app -auto-approve 2>&1 | tail -4
aws_security_group.app: Still destroying... [04m50s elapsed] Error: deleting Security Group (sg-0123456789abcdef0): operation error EC2: DeleteSecurityGroup, https response error StatusCode: 400, RequestID: …, api error DependencyViolation: resource sg-0123456789abcdef0 has a dependent object
Tip: -target will also destroy resources that depend on it (ECS service, rules). If you don't want to break the app, press Ctrl+C once in advance (to let it exit gracefully) and only observe the diagnostic steps.
aws ec2 describe-network-interfaces --filters Name=group-id,Values=$SG --query 'NetworkInterfaces[].[NetworkInterfaceId,Description]' --output text aws ec2 delete-network-interface --network-interface-id $ENI terraform apply -auto-approve # restore the environment to the state described by the code
aws configure sso --profile tf-ro # choose the ReadOnlyAccess permission set AWS_PROFILE=tf-ro aws ec2 run-instances --dry-run --image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --instance-type t3.micro 2>&1 | head -2
An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. User: arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_ReadOnlyAccess_…/andy is not authorized to perform: ec2:RunInstances … because no identity-based policy allows the ec2:RunInstances action. Encoded authorization failure message: 3vX9…
Copy Encoded authorization failure message: the string after it, and decode it with the decode command in the “Commands” tab (requires sts:DecodeAuthorizationMessage permission, run with the tf-lab profile). Without a read-only permission set, just use the SCP scenario in the “Animation” tab to understand it.
aws ec2 describe-network-interfaces --filters Name=description,Values=orphan-demo returns empty.Case 1: a Lambda ENI made VPC deletion fail
Problem: The environment teardown pipeline timed out every time it deleted subnets/security groups. Root cause: Lambda functions in the VPC use Hyperplane ENIs; after the function is deleted, reclaiming the ENIs is asynchronous and may take a long time. Approach: In the teardown order, delete Lambda first and then wait; set a longer timeouts { delete = "45m" } for the security group; automatically retry destroy after a pipeline failure. Limitations: Do not manually delete the InterfaceType = lambda ENIs (usually not permitted either); wait for them to be reclaimed.
Case 2: plan on a large state was throttled
Problem: A root module with 3000 resources took 25 minutes to plan and frequently hit RequestLimitExceeded retries; other teams' tools in the same account also began reporting throttling. Approach: Split the state (network/data/application); in CI, -parallelism=5; for changes that care about only a few resources, use the option added in 1.17 -minimal-refresh (refreshes only resources with changes; verified from the 1.17 release notes), or -refresh=false (use with caution). Limitations: Reducing refresh lowers drift-detection ability; a periodic full plan is needed separately (lesson 5 drift detection).
Case 3: an SCP refusal made deployment to a new region fail
Problem: The team tried to deploy DR resources to us-west-2 and got with an explicit deny in a service control policy. Approach: This is not a Terraform or role-permissions problem; an organization SCP restricts the allowed regions. Go through the change process to request adding the region to the SCP allow list, or switch to an approved region. Limitations:simulate-principal-policy SCPs are not evaluated by a policy simulator, so it is easy to wrongly conclude that the permissions are fine.
Interactive troubleshooting tree: Terraform failures on AWS
Start from the symptom, choose step by step, and get diagnostic commands and fix suggestions.
Supplement: quick reference for frequent errors
Error: deleting EC2 Subnet (subnet-…): DependencyViolation: The subnet 'subnet-…' has dependencies and cannot be deleted.
aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=subnet-… --query 'NetworkInterfaces[].[NetworkInterfaceId,InterfaceType,Description]' --output table
Determine ownership from the Description (ELB, ECS attachment, Lambda, VPC endpoint, NAT gateway), delete it in the corresponding system, then retry destroy.
Error: deleting EC2 Internet Gateway: DependencyViolation: Network vpc-… has some mapped public address(es). Please unmap those public address(es) before detaching the gateway.
aws ec2 describe-addresses --filters Name=domain,Values=vpc --query 'Addresses[].[PublicIp,AssociationId,NetworkInterfaceId]' --output table
ENIs with public IPs remain in the VPC (NAT gateways, tasks with public IPs, load balancers). Wait for them to be deleted, or release the EIP manually, then retry.
Error: creating ECS Service: InvalidParameterException: Unable to assume the service linked role. Please verify that the ECS service linked role exists.
When ECS is used for the first time in a new account, the service-linked role may not have been created yet, or was just created and has not propagated (eventual consistency). Retry later, or create it in advance with aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com (it errors if the role already exists; you can ignore that).
Error: ... api error RequestLimitExceeded: Request limit exceeded.
Reduce -parallelism, avoid having multiple pipelines operate on the same account/region at the same time,retry_mode = "adaptive", and split the state.
Error: deleting S3 Bucket (…): BucketNotEmpty: The bucket you tried to delete is not empty. You must delete all versions in the bucket.
A versioned bucket must have all object versions and delete markers removed. For a lab bucket, you can set force_destroy = true and then apply before destroy; for production buckets, confirm whether they really should be deleted.
1. destroy hangs while deleting a security group. Write the commands that find and identify the occupant.
aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-0123456789abcdef0 \ --query 'NetworkInterfaces[].[NetworkInterfaceId,InterfaceType,Status,Description]' --output table aws ec2 describe-security-groups --filters Name=ip-permission.group-id,Values=sg-0123456789abcdef0 \ --query 'SecurityGroups[].GroupId' # whether rules in other security groups reference it
2. Check the vCPU quota for On-Demand Standard instances in this region.
aws service-quotas get-service-quota --service-code ec2 --quota-code L-1216C47A --query 'Quota.[QuotaName,Value]'
apply failed with AccessDenied at resource 37, and the first 36 had already been created. A colleague suggests "delete the state, clean up manually, and start over". What is your view?
Do not delete the state. The first 36 resources are correctly recorded in state. Fix the permissions (first confirm the identity with get-caller-identity and read the source of the denial: identity policy / SCP / boundary / resource policy), then run terraform apply again, and Terraform will create only the remaining resources. Deleting the state would turn the 36 resources into orphans (still billed, and name conflicts would make later creation fail), and manual cleanup is easy to get wrong.
Verified teaching videos
No verified video on "troubleshooting Terraform on AWS (DependencyViolation / throttling / eventual consistency)" was found; a storyboard script is provided.
Official docs
- IAM policy evaluation logic
- Troubleshooting IAM access denied
- Terraform debugging (TF_LOG)
- Service Quotas
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: six doors line up in order: credentials, throttling, authorization, quotas, dependencies, consistency; a request envelope passes through them from left to right.
Narration: AWS errors can mostly be grouped into six categories. First work out which door the request was stopped at.
Scene: an AccessDenied error is magnified, with "service control policy" highlighted at the end; beside it, an "add wildcard permissions" button is crossed out.
Narration: see clearly who refused you. If it is the organization's SCP, adding more permissions to the role will not help.
Scene: a security group deletion fails; the camera goes through the security group and finds an ENI that is not in state, described as ECS attachment.
Narration: DependencyViolation often comes from resources outside state. Find the occupant, delete it in the system it belongs to, then retry.
Scene: in the terminal, parallelism drops from ten to five, and the red RequestLimitExceeded disappears.
Narration: when you hit throttling, reduce concurrency and split the state, rather than endlessly raising the retry count.
Module 8 · Cost, cleanup and self-check
- List the cost structure of this lesson's architecture, distinguishing hourly billing (NAT, ALB, public IPv4, Fargate, EKS control plane) from usage or monthly billing (data processing, logs, secrets, KMS, S3).
- Use tags (cost allocation tags), AWS Budgets (manageable with Terraform) and Infracost to estimate costs at the plan stage.
- Destroy in the correct order (app → eks → bootstrap), and use the Resource Groups Tagging API and targeted commands to scan for leftovers.
What: the cost structure of this lesson's architecture (approximate ca-central-1 prices; refer to the AWS pricing page)
| Resource | Billing method | Approximate unit price | Quantity in the lab | Per hour |
|---|---|---|---|---|
| NAT gateway | hourly + per GB processed | ≈ 0.05 USD/hour + ≈ 0.05 USD/GB | 1 | ≈ 0.050 |
| Public IPv4 (NAT's EIP, ALB node per AZ) | hourly | 0.005 USD/IP/hour | ≈ 3 | ≈ 0.015 |
| ALB | hourly + LCU | ≈ 0.025 USD/hour + LCU | 1 | ≈ 0.025–0.035 |
| Fargate (0.25 vCPU / 0.5 GB) | per second (1-minute minimum) | vCPU ≈ 0.045 USD/hour, GB ≈ 0.005 USD/hour | 2 tasks | ≈ 0.027 |
| Secrets Manager | per secret per month + API calls | 0.40 USD/month | 1 | ≈ 0.0005 |
| KMS customer-managed key | monthly + requests | 1 USD/month | 1 (state) | ≈ 0.0014 |
| CloudWatch Logs / ECR / S3 | per GB | very small | — | ≈ 0 |
| Total (excluding EKS) | ≈ 0.12 USD/hour ≈ 2.9 USD/day ≈ 87 USD/month | |||
| EKS control plane (optional lab) | hourly | 0.10 USD/hour (standard support) | 1 | +0.10 (plus nodes and the Auto Mode management fee) |
Why: why care about cost at the plan stage
The cost of cloud resources is determined by architecture decisions (single NAT or one per AZ, endpoints or NAT, Fargate size). These decisions are all written in Terraform code. Seeing cost changes during code review is much cheaper than finding them on the monthly bill.
How: three layers of cost control
- Before deployment: Infracost reads the plan JSON to estimate monthly cost and changes (
infracost breakdown/infracost diff), and comments on the PR (connected to CI in lesson 5). Terraform 1.17's GA Policy (-policies) or OPA can also set rules such as “forbid one NAT per AZ” or “forbid large instance sizes” (lessons 5 and 7). - During deployment:
default_tagsapply consistent tags viaProject/Environment/Owner; in the Billing console,activate the cost allocation tags before they can be grouped by tag in Cost Explorer (they take effect only after activation and are not back-filled). Useaws_budgets_budgetto set budget alerts. - After:
terraform destroy+ leftover scan; for long-running environments, use scheduled scale-downs (ECS desired_count 0, turn off NAT).
When: the order of destroy
| Order | Object | Notes |
|---|---|---|
| 1 | in-cluster objects (EKS LoadBalancer Services, Ingresses, PVCs) | otherwise they leave NLBs/ALBs/EBS volumes behind, blocking VPC deletion |
| 2 | eks/ root module | about 10–15 minutes |
| 3 | app/ root module | ECR force_delete, secrets recovery_window_in_days = 0 to leave no residue; ALB/NAT deletion takes several minutes |
| 4 | bootstrap/ (state bucket and KMS) | last delete; the app's state lives here. The bucket force_destroy = true must have all versions deleted before it can be removed; the KMS key enters a 7–30 day pending-deletion period |
| 5 | leftover scan | by tag + EIP/ENI/snapshots/log groups/ECR |
Comparison with lesson 3 Azure
| Azure | AWS | |
|---|---|---|
| catch-all cleanup | az group delete -n rg-tf-lab | no resource-group-level deletion; rely on destroy + tag scans |
| cost grouping | resource groups / tags | cost allocation tags (must be activated) / accounts |
| strongest isolation | subscriptions | accounts (sandbox accounts for labs; close the whole account if necessary) |
Diagram: composition of the hourly bill (excluding EKS)
Diagram: cleanup order and verification
Interactive: lab cost calculator + cleanup order walkthrough
Adjust resources and duration to see the cost estimate (approximate unit prices, see the table in Principles); then play the cleanup walkthrough to see what each deletion step removes and why it must happen in this order.
Cost and cleanup commands
| Command | Purpose | Notes |
|---|---|---|
infracost breakdown --path . | Estimate monthly cost | requires an Infracost API key (free sign-up); offline, use terraform show -json plan and pass it to Infracost |
terraform state list | wc -l | Record the resource count before destroy | compare with the destroy output |
terraform plan -destroy | Preview deletion | check whether bootstrap would be deleted by mistake |
aws resourcegroupstaggingapi get-resources | find leftovers by tag | --tag-filters Key=Project,Values=myapp-tf-lab |
aws ce get-cost-and-usage | Check actual costs | billing data is delayed |
Manage budgets with Terraform (place in bootstrap or the account baseline)
resource "aws_budgets_budget" "lab" {
name = "myapp-tf-lab-monthly"
budget_type = "COST"
limit_amount = "10"
limit_unit = "USD"
time_unit = "MONTHLY"
cost_filter {
name = "TagKeyValue"
values = ["user:Project$myapp-tf-lab"] # the Project cost allocation tag must first be activated in Billing
}
notification {
comparison_operator = "GREATER_THAN"
threshold = 80
threshold_type = "PERCENTAGE"
notification_type = "FORECASTED"
subscriber_email_addresses = ["you@example.com"]
}
}
Leftover scan script (scan-leftovers.sh)
#!/usr/bin/env bash
set -euo pipefail
R=${AWS_REGION:-ca-central-1}
echo "== By tag Project=myapp-tf-lab (just-deleted resources may still briefly appear)"
aws resourcegroupstaggingapi get-resources --region $R --tag-filters Key=Project,Values=myapp-tf-lab \
--query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n'
echo "== Unassociated Elastic IPs"
aws ec2 describe-addresses --region $R --query 'Addresses[?AssociationId==null].[PublicIp,AllocationId]' --output text
echo "== Available (unattached) ENIs"
aws ec2 describe-network-interfaces --region $R --filters Name=status,Values=available \
--query 'NetworkInterfaces[].[NetworkInterfaceId,Description]' --output text
echo "== Remaining NAT gateways / load balancers"
aws ec2 describe-nat-gateways --region $R --filter Name=state,Values=pending,available --query 'NatGateways[].NatGatewayId' --output text
aws elbv2 describe-load-balancers --region $R --query 'LoadBalancers[].LoadBalancerName' --output text
echo "== ECR repositories / ECS clusters / EKS clusters"
aws ecr describe-repositories --region $R --query 'repositories[].repositoryName' --output text
aws ecs list-clusters --region $R --query 'clusterArns' --output text
aws eks list-clusters --region $R --query 'clusters' --output text
echo "== Log groups / secrets with names starting with myapp"
aws logs describe-log-groups --region $R --log-group-name-prefix /ecs/myapp --query 'logGroups[].logGroupName' --output text
aws secretsmanager list-secrets --region $R --filters Key=name,Values=myapp --query 'SecretList[].Name' --output text
echo "== Cross-region lab resources from module 1 in us-east-1"
aws logs describe-log-groups --region us-east-1 --log-group-name-prefix /myapp --query 'logGroups[].logGroupName' --output text
How to verify: Each section of output should be empty (the KMS key will show as PendingDeletion, which is normal). Common errors: Scanning only the default region and forgetting the resources module 1 created in us-east-1. Production use: Run it regularly (e.g., weekly) in sandbox accounts, or use a tool such as aws-nuke to bulk-clean sandboxes (be sure to configure an account allowlist; misuse deletes everything).
Lab 8: cost estimate, destroy and leftover check (about 10 min; costs drop to zero afterwards, and the KMS key enters its pending-deletion period)
cd ~/tf-lab/aws/app infracost breakdown --path . --format table 2>/dev/null | tail -12
Name Monthly Qty Unit Monthly Cost module.vpc.aws_nat_gateway.this[0] ├─ NAT gateway 730 hours $36.50 └─ Data processed Monthly cost depends on usage: $0.05 per GB aws_lb.myapp └─ Application load balancer 730 hours $18.03 aws_ecs_service.myapp ├─ Per GB per hour 1 GB $3.57 └─ Per vCPU per hour 0.5 CPU $16.27 OVERALL TOTAL $~80
terraform state list | wc -l time terraform destroy -auto-approve
41 … module.vpc.aws_nat_gateway.this[0]: Destruction complete after 1m2s aws_lb.myapp: Destruction complete after 2s module.vpc.aws_internet_gateway.this[0]: Destruction complete after 41s Destroy complete! Resources: 41 destroyed. real 4m37s
cd ~/tf-lab/aws/bootstrap terraform destroy -auto-approve KEY=$(aws kms list-aliases --query "Aliases[?AliasName=='alias/myapp-tf-state'].TargetKeyId" --output text) [ -z "$KEY" ] && echo "alias deleted" || aws kms describe-key --key-id "$KEY" --query KeyMetadata.KeyState
aws_s3_bucket.state: Destruction complete after 3s aws_kms_key.state: Destruction complete after 1s Destroy complete! Resources: 10 destroyed. alias deleted
The KMS key “deletion” actually schedules it for deletion after 7 days (PendingDeletion); if needed, you can use aws kms cancel-key-deletion to recover it during the pending-deletion period.
bash ~/tf-lab/aws/scan-leftovers.sh
== By tag Project=myapp-tf-lab (just-deleted resources may still briefly appear) == Unassociated Elastic IPs == Available (unattached) ENIs …(all empty)
If the tag scan still lists deleted resources, run it again after a few minutes; if it is an ENI/EIP, go back to the module 7 troubleshooting. If you did the EKS in module 6, confirm aws eks list-clusters is empty.
aws ce get-cost-and-usage --time-period Start=$(date -u -d '-2 day' +%F),End=$(date -u +%F) --granularity DAILY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE, confirm that EC2-Other (NAT/EIP), ELB and ECS costs have stopped growing.Case 1: sandbox account bill of 1200 USD at month end
Problem: During training, 20 students each created EKS + NAT, and after it ended, half of them had not run destroy. Approach: Each student uses a temporary sandbox account under Organizations; SCPs restrict regions and instance sizes; a nightly cleanup job runs (aws-nuke with an allowlist, or a tag-based Lambda); budget alerts go to the instructor. Limitations: Cleanup tools must be strictly scoped to accounts; some teams have accidentally deleted production resources.
Case 2: dev environments scale down after hours
Problem: Dev environments run 24×7 but are only used during working hours. Approach: Terraform variables enable_nat_gateway = var.office_hours,desired_count = var.office_hours ? 2 : 0, applied by a scheduled pipeline in the morning and evening; or adjust the ECS service with EventBridge Scheduler. Limitations: Applying this way can conflict with manual changes, so agree on a single "sole writer" for each environment.
Case 3: cost review included in PRs
Problem: A seemingly harmless PR changed single_nat_gateway to one_nat_gateway_per_az (3 AZs), adding about 70 USD per month, and nobody noticed. Approach: Run infracost diff in CI and comment on the PR; exceeding the threshold requires FinOps approval (lesson 5). Limitations: Usage-based parts (traffic, logs) can only be estimated; combine with real monitoring.
Common errors and fixes
Error: deleting S3 Bucket (myapp-tf-state-…): BucketNotEmpty: The bucket you tried to delete is not empty. You must delete all versions in the bucket.
Cause: The versioned bucket contains historical versions; force_destroy is false, or it was just changed to true in an apply that has not run yet.
Fix: After confirming the bucket can really be deleted: first terraform apply so that force_destroy = true takes effect, then destroy. Do not do this for production state buckets.
Error: Failed to load state: ... NoSuchBucket: The specified bucket does not exist
Cause: bootstrap (the state bucket) was deleted first, and then you tried to manage the app.
Fix: If app resources still exist: neither the bucket's backups nor the local .terraform/terraform.tfstate (backend configuration only, which contains no resources) can restore the resource state, so you can only re-import with import blocks or delete the resources manually. Lesson: delete bootstrap last.
Error: deleting ECR Repository (myapp): RepositoryNotEmptyException: The repository with name 'myapp' ... cannot be deleted because it still contains images
Cause: The force_delete = true was not set. Fix: In the lab, set it, apply, then destroy; or aws ecr batch-delete-image empty the bucket.
Error: deleting Secrets Manager Secret ... (destroy succeeds, but a second apply reports already scheduled for deletion)
Cause: Within the default recovery window, a same-named secret cannot be recreated. Fix: In the lab use recovery_window_in_days = 0, or --force-delete-without-recovery.
The bill still shows “Public IPv4 address” or “NAT Gateway” charges
Cause: Unreleased EIPs, or NAT gateways in other regions or other root modules. Fix: Run the leftover-scan script, and loop over all enabled regions (aws ec2 describe-regions --query 'Regions[].RegionName').
1. Find NAT gateways still running in all enabled regions.
for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do n=$(aws ec2 describe-nat-gateways --region $r --filter Name=state,Values=available --query 'length(NatGateways)') [ "$n" != "0" ] && echo "$r: $n" done
2. Preview which resources destroy would delete, outputting addresses only.
terraform plan -destroy -no-color | grep -E '^ # .* will be destroyed' | sed 's/ # //; s/ will be destroyed//'
On Monday morning you find that last Friday's lab environment was not deleted, and 60 hours have passed. Estimate the cost and explain what you will do next.
At ≈ 0.12 USD/hour, that is about 7 USD (plus about 6 USD and node costs if EKS was included). Handling: ① immediately run destroy in the app directory terraform destroy (if EKS exists, delete the in-cluster LBs first, then destroy eks), and finally destroy bootstrap; ② run the leftover scan; ③ review: add Owner and ExpiresAt tags to the environment, set budget alerts, and run scheduled cleanup in the sandbox account; ④ the next day, use Cost Explorer to confirm that costs have stopped growing.
Verified teaching videos
No verified video on AWS cost control + Terraform cleanup was found; a storyboard script is provided.
Official docs
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.
Scene: a stacked bar chart; NAT takes the largest segment, followed by load balancers; compute takes only a small slice.
Narration: the bulk of the lab bill is not compute, but hourly-billed network components: NAT gateways, load balancers and public IPs.
Scene: five numbered blocks light up in turn: in-cluster load balancers, eks, app, bootstrap, leftover scan; bootstrap has a lock labeled “last”.
Narration: cleanup has an order. The state bucket is deleted last; otherwise you can no longer use Terraform to delete the other resources.
Scene: the leftover-scan script outputs blank sections in turn; the last line shows that everything is empty, with a green check mark.
Narration: AWS has no resource groups, so verify with tags and targeted commands. Only when everything is empty is the cleanup really complete.
Command cheat sheet
Authentication
aws configure sso --profile tf-lab aws sso login --profile tf-lab export AWS_PROFILE=tf-lab aws sts get-caller-identity aws configure list aws configure export-credentials --format env env | grep ^AWS_ # check for "ghost keys"
S3 backend
terraform init -backend-config=backend-lab.hcl -migrate-state terraform init -reconfigure terraform plan -lock-timeout=5m terraform force-unlock LOCK_ID aws s3 cp s3://BUCKET/KEY.tflock - | jq . aws s3api list-object-versions --bucket BUCKET --prefix KEY
Networking
aws ec2 describe-route-tables --filters Name=vpc-id,Values=$VPC
aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=$VPC
aws ec2 describe-security-group-rules --filters Name=group-id,Values=$SG
aws ec2 describe-addresses --query 'Addresses[?AssociationId==null]'
terraform console # cidrsubnet("10.20.0.0/16", 8, 10)ECR / ECS / ALB
aws ecr get-login-password | docker login --username AWS --password-stdin $REG docker push $ECR:1.0 aws ecs describe-services --cluster myapp-lab --services myapp --query 'services[0].events[:5].message' aws ecs list-tasks --cluster myapp-lab --desired-status STOPPED aws ecs describe-tasks --cluster myapp-lab --tasks $T --query 'tasks[0].stoppedReason' aws elbv2 describe-target-health --target-group-arn $TG aws logs tail /ecs/myapp --follow
IAM and secrets
aws iam simulate-principal-policy --policy-source-arn $ROLE \ --action-names secretsmanager:GetSecretValue --resource-arns $SECRET aws sts decode-authorization-message --encoded-message "$MSG" aws secretsmanager describe-secret --secret-id myapp/app-secret terraform state show aws_secretsmanager_secret_version.app terraform state pull | grep -c "$VALUE" # should be 0
EKS
aws eks describe-cluster-versions --query 'clusterVersions[].clusterVersion' aws eks update-kubeconfig --name myapp-eks --region ca-central-1 aws eks list-access-entries --cluster-name myapp-eks kubectl get nodepools,nodeclaims kubectl get svc -A | grep LoadBalancer # must be empty before destroy terraform providers
Troubleshooting
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=tf.log terraform apply aws ec2 describe-network-interfaces --filters Name=group-id,Values=$SG aws cloudtrail lookup-events --max-results 50 aws service-quotas get-service-quota --service-code vpc --quota-code L-F678F1CE terraform apply -parallelism=5 terraform apply -replace=aws_instance.demo
Cost and cleanup
infracost breakdown --path . terraform state list | wc -l terraform plan -destroy terraform destroy -auto-approve # app → eks → bootstrap aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=myapp-tf-lab bash scan-leftovers.sh
Quick troubleshooting table
| Error keyword | Category | First action | Module |
|---|---|---|---|
No valid credential sources / SSO session has expired | credential chain | aws sso login, check AWS_PROFILE | M1 |
InvalidClientTokenId | credential chain | env | grep AWS_ look for leftover static keys | M1 |
AWS account ID not allowed | guardrail | switch to the correct profile | M1 |
Error acquiring the state lock + PreconditionFailed | state lock | check the .tflock holder → after confirming, force-unlock | M2 |
kms:Decrypt AccessDenied (during init) | IAM | KMS key policy + caller permissions | M2 |
InvalidSubnet.Conflict | Networking | check cidrsubnet netnum | M3 |
ResourceInitializationError ... i/o timeout | Networking | private subnet outbound (NAT/endpoints) and SG outbound | M3/M4 |
CannotPullContainerError | image | tag/region/architecture | M4 |
Target.FailedHealthChecks | application/network | path, listening address, SG references | M4 |
unable to retrieve secret from asm | IAM | execution role GetSecretValue | M5 |
Invalid use of ephemeral value | Terraform | switch to *_wo argument | M5 |
Unsupported argument "cluster_name" | module version | compare against eks v21 input names | M6 |
DependencyViolation | dependencies | find ENIs by SG/subnet, delete the occupant | M7 |
explicit deny in a service control policy | IAM (organization) | contact the platform team; it is not a role problem | M7 |
RequestLimitExceeded | throttling | -parallelism=5, split the state | M7 |
BucketNotEmpty / RepositoryNotEmptyException | cleanup | force_destroy/force_delete apply first | M8 |
Recommended configuration snippets
# providers.tf: short-term credentials + guardrails + unified tags
provider "aws" {
region = "ca-central-1"
allowed_account_ids = [var.account_id]
default_tags {
tags = { Project = "myapp-tf-lab", Environment = var.env, ManagedBy = "terraform" }
}
}
# backend.tf: native locking
terraform {
backend "s3" {
use_lockfile = true
encrypt = true
}
}
# secrets not in state
ephemeral "aws_secretsmanager_random_password" "app" {
password_length = 32
}
resource "aws_secretsmanager_secret_version" "app" {
secret_id = aws_secretsmanager_secret.app.id
secret_string_wo = ephemeral.aws_secretsmanager_random_password.app.random_password
secret_string_wo_version = 1
}
Capstone lab + final quiz
Project=myapp-tf-lab tag; after acceptance, delete everything completely and prove there are no leftovers.Required permissions: VPC/EC2, ECS, ECR, ELB, IAM (creating roles), Secrets Manager, S3, KMS, CloudWatch Logs. Security risks: The ALB is open to the public on port 80 (HTTP for the demo; production must use HTTPS + ACM); the lab bucket
force_destroy.aws sso login --profile tf-lab && export AWS_PROFILE=tf-lab
export TF_VAR_account_id=$(aws sts get-caller-identity --query Account --output text)
mkdir -p ~/tf-lab/aws-final/{bootstrap,app} && cd ~/tf-lab/aws-final
docker image inspect myapp:1.0 --format '{{.Architecture}}' # should be amd64bootstrap/main.tf from module 2 and apply; for app, write backend.tf (use_lockfile = true) and backend-lab.hcl (key set to myapp/final/terraform.tfstate).
cd bootstrap && terraform init && terraform apply -auto-approve && cd ../app terraform init -backend-config=backend-lab.hcl
providers.tf,variables.tf,network.tf (vpc module + S3 Gateway endpoint),security.tf,outputs.tf. First, check with plan:
terraform plan -out=net.tfplan | grep -E "Plan:|nat_gateway"
terraform apply -target=aws_ecr_repository.myapp -target=aws_ecr_lifecycle_policy.myapp -auto-approve
ECR=$(terraform output -raw ecr_url)
aws ecr get-login-password | docker login --username AWS --password-stdin ${ECR%%/*}
docker tag myapp:1.0 $ECR:1.0 && docker push $ECR:1.0secrets.tf (ephemeral + secret_string_wo),iam.tf (least-privilege execution role + task role, no managed policies attached),ecs.tf (task definition including secrets and task_role_arn),alb.tf (service wait_for_steady_state = true, circuit breaker).
terraform apply -auto-approve
URL=$(terraform output -raw url)
curl -s $URL/ ; echo; curl -s -o /dev/null -w "%{http_code}\n" $URL/healthz
Apply complete! Resources: 39 added, 0 changed, 0 destroyed. url = "http://myapp-lab-1234567890.ca-central-1.elb.amazonaws.com" Hello from myapp! Visit count: 1 200
# 1) lock and encryption aws s3api get-bucket-versioning --bucket $(terraform -chdir=../bootstrap output -raw bucket) aws s3api get-bucket-encryption --bucket $(terraform -chdir=../bootstrap output -raw bucket) --query 'ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault.SSEAlgorithm' # 2) tasks have no public IP and are spread across two AZs aws ecs describe-tasks --cluster myapp-lab --tasks $(aws ecs list-tasks --cluster myapp-lab --query 'taskArns' --output text) \ --query 'tasks[].[availabilityZone,attachments[0].details[?name==`privateIPv4Address`].value|[0]]' --output text # 3) secrets not in state S=$(aws secretsmanager get-secret-value --secret-id myapp/app-secret --query SecretString --output text); terraform state pull | grep -c "$S"; unset S # 4) the execution role has no managed policies aws iam list-attached-role-policies --role-name myapp-ecs-exec --query 'length(AttachedPolicies)' # 5) tags aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=myapp-tf-lab --query 'length(ResourceTagMappingList)' # 6) plan again shows no drift terraform plan -detailed-exitcode; echo "exit=$?"
{ "Status": "Enabled" }
"aws:kms"
ca-central-1a 10.20.10.37
ca-central-1b 10.20.11.84
0
0
35
No changes. Your infrastructure matches the configuration.
exit=0myapp:1.1,terraform apply -var image_tag=1.1, run curl in a loop in another terminal to confirm zero errors; then trigger the circuit breaker rollback with a nonexistent tag, and let Terraform restore consistency (step 5 of the module 4 lab).terraform destroy -auto-approve cd ../bootstrap && terraform destroy -auto-approve bash ~/tf-lab/aws/scan-leftovers.sh
Done once all scan sections are empty. If destroy reports DependencyViolation, use the module 7 troubleshooting tree.
Open self-check (answer yourself first, then expand the reference answer)
1. Describe the full call chain for one terraform apply creation aws_vpc , from core to AWS and back to state.
core builds the dependency graph → gRPC PlanResourceChange (plan) → during apply ApplyResourceChange → inside the provider, the SDK gets credentials via the credential chain (SSO token exchanged for STS temporary credentials, optionally AssumeRole) → SigV4 signing → ec2.ca-central-1.amazonaws.com request to CreateVpc endpoint (server-side signature verification, IAM evaluation, throttling) → failed calls can be retried (exponential backoff) → waiter polling DescribeVpcs until available → NewState returned → core writes the S3 state (holding the .tflock lock).
2. Why don't new projects need a DynamoDB lock table anymore? What permissions does lockfile locking require?
Since Terraform 1.11, the S3 backend's use_lockfile uses S3 conditional writes (If-None-Match) to atomically create a .tflock object for mutual exclusion; DynamoDB locking is deprecated. Permissions: Get/Put on the state object, ListBucket on the bucket, Get/Put/Delete on the lock object; with KMS also Encrypt/Decrypt/GenerateDataKey.
3. In the lab and in production, how would you choose a NAT approach?
Lab: single NAT + free S3 Gateway endpoint; delete it when done. Production: one NAT per AZ (AZ isolation), or evaluate Regional NAT; add Interface endpoints when traffic is large and concentrated on AWS services; quantify processing fees with Infracost and Flow Logs.
4. What is the difference between the ECS task execution role and the task role? What permissions does myapp need for each?
The execution role is used by the platform before the container starts: ECR pull (scoped to the repository + GetAuthorizationToken), Logs writes, and reading the secrets referenced by the task definition. The task role is used by application code; myapp does not call AWS APIs, so it can have no permissions (only a trust policy).
5. How do you ensure secrets do not appear in state? What are the limitations?
Generate the value with an ephemeral resource and write it through a write-only argument (secret_string_wo + _wo_version); or Terraform creates only an empty shell and the value is written externally; the task definition references only the ARN. Limitations: requires Terraform ≥ 1.11; rotation requires manually incrementing the version number; running tasks must be redeployed to get the new value; historical state versions may still contain secrets left by an older approach.
6. destroy reports DependencyViolation, what is your handling process?
Confirm the blocked resource (SG/subnet/IGW) → use describe-network-interfaces (by group-id/subnet-id) or describe-addresses to find occupants outside state → determine ownership from the Description (ELB, ECS, Lambda, EKS LB, manual resources) → delete in the system that owns it or wait for asynchronous reclamation → retry destroy → leftover scan. Do not use state rm to cover it up.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| Terraform CLI | Latest v1.17.2 (2026-11-11); 1.17 adds -minimal-refresh, Policy GA; ephemeral resources 1.10, write-only arguments 1.11 | Terraform CHANGELOG |
| aws provider version | 6.73.0 (released 2026-11-11) | Registry(API /v1/providers/hashicorp/aws) |
| resource-level region | Since 6.0.0, most resources, data sources and ephemeral resources have gained an optional region; changing it forces replacement; global services do not have this argument; the import ID can include @region; the alias syntax still works; migration requires first apply -refresh-only | Enhanced Region Support |
| Authentication order and retries | provider arguments → environment variables → shared credentials → shared config → container credentials → instance profile; max_retries default 25; retry_mode standard/adaptive | AWS Provider docs |
| S3 backend | use_lockfile (default false); “DynamoDB-based locking is deprecated”; lock file = key + .tflock, requires Get/Put/Delete; KMS requires Encrypt/Decrypt/GenerateDataKey; assume_role uses object-assignment syntax; workspace_key_prefix default env: | Backend Type: s3 |
| NAT gateway | availability_mode zonal (default) / regional; regional requires vpc_id, must not set subnet_id/allocation_id,connectivity_type must be public; omitting availability_zone_address gives automatic mode | aws_nat_gateway |
| Community modules | vpc 6.7.3 (2026-09-18, requires aws ≥ 6.28, no regional NAT input); eks 21.29.0 (2026-10-07, requires aws ≥ 6.59 and Terraform ≥ 1.5.7); ecs 7.6.1 | terraform-aws-modules(Registry API) |
| EKS Auto Mode (module) | compute_config = { enabled = true, node_pools = ["general-purpose"] }; to turn it off, first set enabled = false and then delete the block; endpoint_public_access,enable_cluster_creator_admin_permissions default false | terraform-aws-eks README |
| EKS versions | standard support 1.37/1.36/1.35/1.34; extended support 1.33/1.32/1.31; 1.37 was released on EKS on 2026-10-01, with standard support until 2027-12-01 | EKS Kubernetes versions |
| ephemeral / write-only (aws) | ephemeral: secretsmanager_random_password (attribute random_password), secretsmanager_secret_version, ssm_parameter, kms_secrets, eks_cluster_auth, ecr_authorization_token, lambda_invocation, sts_web_identity_token, etc.; secret_string_wo requires secret_string_wo_version; arn attribute is deprecated, use secret_arn; aws_db_instance.password_wo | provider docs source code · secretsmanager_secret_version |
| ECS / Fargate | awsvpc, CPU/memory combinations, circuit breaker, task execution role | ECS on Fargate · execution role |
| Pricing | NAT, ALB, Fargate, public IPv4 (0.005 USD/hour), EKS (0.10 USD/hour standard support) and similar figures are all approximate | VPC pricing · Fargate pricing · EKS pricing |
Video verification notes
The following videos were verified by title and channel via the YouTube oEmbed endpoint (2026-11-15): Fireship “Terraform in 100 Seconds” (tomUWcQ0P3k); freeCodeCamp.org “Terraform Course - Automate your AWS cloud infrastructure” (SLB_c_ayRMo) and “Learn Terraform (and AWS) by Building a Dev Environment – Full Course for Beginners” (iRaai1IBlB0); TechWorld with Nana “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); KodeKloud “Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide!” (YcJ9IeukJL8). oEmbed does not return durations or publish dates, so no durations are listed on the cards. These videos were all recorded before aws provider 6.x,use_lockfile and write-only arguments; the new mechanisms follow this lesson. No oEmbed-verifiable video was found for ECS Fargate + ALB, Regional NAT, ephemeral/write-only, EKS Auto Mode (Terraform), AWS troubleshooting, or cost cleanup; storyboard scripts are provided instead.
Voice narration notes
The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud; English terms are pronounced with en-US, and results depend on the voices installed on the system. This courseware's generation environment cannot call a TTS service, so no MP3 is embedded; if offline audio is needed, hand the narration script to a TTS service.
Known limitations
- Account IDs, resource IDs, IPs, ARNs, hashes, times, durations and resource counts in the “expected output” are example values; the lab commands in this courseware have not been run in a real AWS account, so use the output of your own environment as the reference.
- Prices are approximate for ca-central-1 as of 2026-11 and are only meant for order-of-magnitude judgment; for Regional NAT billing and availability, refer to the AWS docs.
- Internal resource addresses of the eks module (such as
module.eks.aws_iam_role.eks_auto[0]) follow the module source and your plan output; the wording of AccessDenied messages changes as AWS updates them. - The full list of breaking changes in aws provider 6.x is not itemized here; when upgrading, check the Version 6 Upgrade Guide.
- myapp's Redis runs as a sidecar with an independent count per task, for demonstration only; shared state uses a managed service in lesson 6.
- The times, costs and state sequences in the animations are illustrative values that explain the mechanism.