Terraform Hour 4: Moving to a Cloud Platform (AWS)

Deliver the Docker course's myapp to AWS with Terraform: authentication → remote state → VPC → ECS Fargate + ALB + ECR → IAM and secrets → community modules and EKS → cloud troubleshooting → cost and cleanup
Terraform v1.17.2hashicorp/aws 6.73.0vpc module 6.7.3eks module 21.29.0Region ca-central-1Verified against official docs · 2026-11
Overall learning goals
  • 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 use default_tags to apply consistent tags, and to use the resource-level (new in aws provider 6.x) region argument instead of multiple provider aliases.
  • Build production-grade S3 backend: bucket versioning, SSE-KMS encryption, blocking public access,use_lockfile = true native locking (DynamoDB locking is deprecated), and design cross-account state access.
  • Use terraform-aws-modules/vpc and 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/eks v21 (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

#TimeModuleCore contentAnimation / interactionLab (AWS ca-central-1)
0Before classWarm-up and AWS setupAWS CLI v2, SSO login, lab account and budget alerts, comparison with lesson 3Environment self-checkaws sts get-caller-identity
100–06AWS Provider and authenticationcredential chain, SSO profile, assume_role, OIDC, default_tags, 6.x resource-level regionCore animation: Terraform → provider → SigV4 → AWS API (retry/throttling) → waiter → stateSSO profile + cross-region resources
206–13S3 Backend and native lockingbootstrap bucket, versioning, SSE-KMS,use_lockfile, migrating from DynamoDB, cross-accountlock contention when two people apply at the same time (conditional writes)Create the state bucket and migrate
313–21Networking: VPC, subnets, security groupsCIDR planning, public/private subnets, IGW, route tables, NAT (zonal / regional), security group references, VPC endpointsVPC builder + NAT cost calculation + packet pathBuild a two-AZ network with the vpc module
421–30Compute: EC2 and ECS FargateAMI data source, user_data, ECR, task definitions, services, ALB/target groups, circuit breakerECS rolling deployment and ALB health checksmyapp on Fargate
530–37IAM and secretstrust policy vs permissions policy, execution role/task role, least privilege, Secrets Manager, ephemeral + write-onlySecret flow: which values end up in stateSecret injection + state check
637–45Community modules and EKSmodule selection and version constraints, eks module v21, Auto Mode, access entries, helm/kubernetes provider pitfallsEKS creation dependency graph and timing(optional) Auto Mode cluster
745–53Cloud troubleshooting in practicecredential chain, AccessDenied decoding, DependencyViolation, eventual consistency, throttling, quotasdestroy failure replayer + interactive troubleshooting treeDeliberately trigger 3 faults
853–60Cost, cleanup and self-checkcost structure, tags and budgets, Infracost, destroy order, leftover scanLab cost calculatordestroy + leftover check
—After classCheat sheet · Capstone labDeliver myapp with VPC + ECS Fargate + ALB + ECR + Secrets Manager, then destroyFinal quiz (12 questions)Capstone lab (about 0.3 USD)

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / resourcesLab
Authenticate the aws provider with short-term credentials✓✓··✓·✓·aws sso login,assume_roleM1
remote state and locking·✓····✓✓backend "s3",use_lockfile,force-unlockM2
VPC network design··✓✓·✓✓✓module "vpc",aws_security_groupM3
Containers on the cloud: ECR + ECS Fargate + ALB···✓✓·✓·aws_ecs_service,aws_lb_target_groupM4 / capstone
virtual machines and user_data···✓····aws_instance,data "aws_ssm_parameter"M4
IAM least privilege✓✓·✓✓✓✓·aws_iam_policy_documentM5
secrets not in state····✓···ephemeral,secret_string_woM5
community modules / EKS··✓··✓··module "eks",compute_configM6 (optional)
cloud fault diagnosis✓✓·✓✓·✓✓TF_LOG,decode-authorization-messageM7
cost control and cleanup✓·✓··✓·✓terraform destroy, Resource Groups Tagging APIM8

Topics not covered in this lesson (and where to learn them)

TopicWhy it is not in this lessonWhere to learn it
The full CI/CD pipeline with GitHub Actions + OIDC, plan approval, drift detectionThis lesson only configures the OIDC trust relationship and provider authenticationLesson 5: Automated operations
Multi-account landing zones (Control Tower, AFT), Organizations SCP designBelongs to platform architecture, beyond 1 hourLesson 6 (architecture practice) overview;AFT official docs
RDS / Aurora, ElastiCache and other managed data layersExpensive and slow to create; this lesson runs Redis as a sidecar containerLesson 6 (multi-tier architecture)
terraform test, Policy (-policies), Checkov/tflint and other quality gatesBelongs to the automation and quality topicsLessons 5 and 7
Application delivery on EKS (Helm, Argo CD) and Kubernetes in depthThis lesson only uses Terraform to create the cluster itselfKubernetes 8 + 1-hour lesson
Azure equivalents (azurerm, Container Apps)Covered in the previous lessonLesson 3: Moving to a Cloud Platform (Azure)

How to use this courseware

10 pages for each module
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.
Learning progress
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).
Cost awareness
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.
Version notes This lesson is based on Terraform v1.17.2 (2026-11-11),hashicorp/aws 6.73.0 (released 2026-11-11, verified via the Terraform Registry API) as the baseline, which constrains the writing ~> 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)

Prepare an AWS lab account, AWS CLI v2 and SSO login, budget alerts, and map the Azure concepts from lesson 3 to AWS
Before class ≈ 15 minAWS CLI v2Incurs costs
Prerequisites
  • 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/import blocks.
  • 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 AdministratorAccess permission 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,/healthz health check, passing REDIS_HOST to 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"
}
Tip After the SSO session expires, Terraform will report 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)

ConceptLesson 3 AzureThis lesson's AWS
providerhashicorp/azurerm 5.x (5.14.0)hashicorp/aws 6.x
Human sign-inaz login (Entra ID)aws sso login (IAM Identity Center)
CI without passwordsEntra workload identity federated credentialsIAM OIDC provider + AssumeRoleWithWebIdentity
Remote stateazurerm backend (Blob lease lock)s3 backend (use_lockfile conditional-write lock)
Resource groupsResource group rg-tf-labNo resource group concept → rely on tags + Resource Groups / Tag Editor
NetworkingVNet / Subnet / NSGVPC / Subnet / Security Group (+ NACL)
Container platformContainer Apps (+ ACR)ECS on Fargate + ALB (+ ECR)
SecretsKey VaultSecrets Manager / SSM Parameter Store
Cleanupaz group delete One-step deleteterraform destroy + scan for leftovers by tag (there is no “delete the resource group in one step”)
The biggest mental-model difference Azure has resource groups, so deleting a group is a fallback cleanup; AWS has no equivalent. So from the very first resource, this lesson uses the provider's 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.

Environment self-check list

Module 1 · AWS Provider and authentication

00:00 – 06:00 · Where credentials come from, how requests are signed, how failures are retried: the AWS call chain behind one apply
6 minaws 6.73.0Resource-level region (6.0+)★★★★★
Learning objectives
  • 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_identity or OIDC (CI): configure short-term credentials in three ways.
  • Use default_tags,allowed_account_ids to add guardrails to the provider; use the 6.x resource-level region argument to manage multi-region resources in a single provider.
Prerequisites: Lesson 1's provider/required_providers and basic IAM role concepts. Importance:★★★★★ (the first gate for Terraform on the cloud)

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_ID environment 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

PrioritySourceTypical scenarioNotes
1provider block arguments access_key/secret_key/tokenalmost never should be usedwritten into code or variables,forbidden
2environment variables AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKENShort-term credentials injected by configure-aws-credentials in CIwhen present take precedence over the profile
3shared credentials/config files (profile argument or AWS_PROFILE), including SSO,credential_process,role_arn+source_profileengineer's local machineSSO token cached in ~/.aws/sso/cache
4container credentials (AWS_CONTAINER_CREDENTIALS_*)Running Terraform in ECS tasks / CodeBuildfrom the task role
5EC2 instance profile (IMDSv2)Running Terraform on a self-hosted EC2 runnerfrom 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-level region argument 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 region the official steps: upgrade to 6.x → terraform apply -refresh-only → change the provider = aws.xxx to region = "…".
  • 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 own tags is merged with these, and on key conflicts the resource wins; the merged result appears in the tags_all attribute.
  • 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

ScenarioRecommended approachAvoid
Local development/debugging on an engineer's machineSSO profile (AWS_PROFILE=tf-lab)IAM user long-term keys
Deploying from a tooling account to multiple target accountsbase credentials + assume_role { role_arn = target account role }one set of keys per account
GitHub Actions / GitLab CIOIDC → AssumeRoleWithWebIdentityStoring Access Keys in CI Secrets
HCP TerraformDynamic Provider Credentials (also based on OIDC; follow the official docs)Long-term keys stored in workspace variables

Comparison with Azure in lesson 3

azurermaws
Human sign-inAzure CLI token (az login)SSO profile (aws sso login)
Target scopesubscription_id (required since 4.0; for 5.x follow the azurerm docs)the credentials determine the account; region determines the region
Cross-scopemultiple provider aliases, different subscriptionsassume_role go into different accounts; since 6.x the region can be set at the resource level
CI without passwordsfederated credentials (use_oidc = true)assume_role_with_web_identity
Common misconceptions① “Setting 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

Terraform coredependency graph / planstate read/write gRPC terraform-provider-aws (AWS SDK for Go v2) Credential chainenv/profile/SSO/IMDS+assume_role SigV4 signingAuthorizationX-Amz-DateSecurity-Token Retryerexponential backoff + jittermax_retries 25retry_mode HTTPS AWS service endpoint (ca-central-1) ec2.ca-central-1.amazonaws.comecs.ca-central-1.amazonaws.comiam.amazonaws.com (global) signature verification → IAM authorization → quota/throttling → execution STSAssumeRoleAssumeRoleWithWebIdentity→ temporary AKID/Secret/Token Waiter (polling)Describe* untilstate = available / ACTIVEgoverned by the timeouts block write to stateid / arn / tags_all(S3 backend, module 2) ApplyResourceChange returns NewState
Figure 1-1: core only speaks gRPC to the provider; credentials, signing, retries and waiting all happen inside the AWS SDK within the provider

Flowchart: credential chain lookup order (stop at first match)

① provider argumentsaccess_key (forbidden) ② environment variablesAWS_ACCESS_KEY_ID… ③ shared config/credentialsprofile / SSO ④ container credentialsECS task role ⑤ IMDSv2EC2 instance role Optional: assume_role / assume_role_with_web_identityUse the base credentials obtained above to call STS and get temporary credentials for the target role Tip: a profile set explicitly in the provider block takes precedence over environment variables; with only AWS_PROFILE set, keys in environment variables are matched first
Figure 1-2 Credential chain: from top to bottom, stop at the first set of usable credentials, then decide whether to assume a role based on configuration

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.

coregraph / plan providergRPC server Credentials / STSSSO → temporary credentials SigV4 + retriessigning / backoff EC2 APIca-central-1 waiterDescribe* stateS3

Core commands and configuration

Command / configurationPurposeKey arguments / notes
aws configure sso / aws sso loginCreate SSO profile / refresh SSO token--profile,--use-device-code
aws sts get-caller-identityConfirm "who am I right now and in which account"First command to run when troubleshooting
aws configure export-credentialsResolve a profile into temporary credentials (see what the SDK actually received)--profile tf-lab --format env
provider "aws" { assume_role { … } }Cross-account role assumptionrole_arn,session_name,external_id,duration
assume_role_with_web_identity { … }Exchange OIDC token for credentialsrole_arn,web_identity_token_file
TF_LOG_PROVIDER=DEBUGEnable only the provider's debug logsShows 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.

About 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)

Write variables and the provider (in ~/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!
Verify default_tags and the resource-level region: create two free resources (CloudWatch log groups), one in the default region and one in us-east-1:
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:*" ]
Try the allowed_account_ids guardrail: temporarily enter a wrong account ID and watch the plan fail immediately:
TF_VAR_account_id=000000000000 terraform plan
Error: AWS account ID not allowed: 111122223333
Try the credential chain priority: set a fake static key in the environment and see which one matches first:
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.

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

Command-line task
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.

Scenario analysis
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

▶
Terraform in 100 Seconds — Fireship
English · about 2 min · quick review of how Terraform and providers relate
▶
Terraform Course - Automate your AWS cloud infrastructure — freeCodeCamp.org
English · full course · covers aws provider basics and hands-on EC2/VPC (recorded earlier and uses long-term keys in the demo; follow this lesson's SSO/OIDC approach; the provider version is far older than 6.x)

Official docs

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or get a quiz score of ≥ 70%

Module 2 · S3 Backend and native locking

06:00 – 13:00 · One bucket is enough: versioning keeps history, KMS protects secrets, conditional writes ensure mutual exclusion — the DynamoDB lock table is a thing of the past
7 minuse_lockfile (GA in 1.11)dynamodb_table is deprecated★★★★★
Learning objectives
  • 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 the use_lockfile = true backend, and explain that it relies on S3 conditional writes (If-None-Match) for mutual exclusion, and the IAM permissions needed (.tflock on 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.
Prerequisites: Remote state and locking from lesson 2,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 configurationWhat it prevents
Versioningstate 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-TLSmisconfiguration that makes state public; plaintext transmission
prevent_destroy + keeping the bucket out of the same state it managesthe 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

  1. Terraform computes the lock object key: key + ".tflock"; with a workspace it is env:/<workspace>/<key>.tflock (the prefix can be changed with workspace_key_prefix ).
  2. 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.
  3. After acquiring the lock, read the state (GetObject), run plan/apply, and write the state back (PutObject, versioning automatically keeps the old versions).
  4. At the end, DeleteObject deletes the lock object. If the process is killed, the lock object is left behind and needs terraform 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

OptionApplies toNotes
S3 + use_lockfileDefault for new projectsOne bucket, no extra service; needs Terraform ≥ 1.11
S3 + DynamoDB (dynamodb_table)Transition period for existing projectsDeprecated; 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 permissionsLesson 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 backendazurerm backend (lesson 3)OpenTofu 1.13.x s3 backend
Locking mechanismS3 conditional writes .tflockBlob leasealso supported use_lockfile (check the OpenTofu docs)
Encryption at restSSE-S3 default / SSE-KMSstorage-service encryption / CMKclient-side state encryption is also available (specific to OpenTofu)
Version historybucket versioningBlob versioning / soft deleteSame as S3
Common misconceptions① “Turning on 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

bootstrap/Local state (commit an encrypted copyor create it manually once)Create bucket + KMS key app/ (myapp)backend "s3"use_lockfile = truekms_key_id = alias/… Create Read/write state / lock S3 bucket myapp-tf-state-111122223333-ca-central-1 Versioning ✓ · SSE-KMS ✓ · BPA ✓ · TLS only ✓ · BucketOwnerEnforced myapp/lab/terraform.tfstateVersions v1 … v7 (noncurrent versions expire after 90 days) myapp/lab/terraform.tfstate.tflockExists only during an operation (created by a conditional write) env:/staging/myapp/lab/terraform.tfstateNon-default workspace (workspace_key_prefix) KMS keyalias/myapp-tf-stateKey policy: deployment role onlyEncrypt/Decrypt/GDK
Figure 2-1: first build the foundation with the bootstrap root module, then have the business root module put state and locks in it

Sequence diagram: two applies starting at the same time

Engineer AS3CI pipeline B PUT key.tflock If-None-Match: * 200 OK (A holds the lock) PUT key.tflock If-None-Match: * 412 PreconditionFailed → wait / error GET state → plan/apply → PUT state (new version) DELETE key.tflock Retry (-lock-timeout=5m) 200 OK (B holds the lock and reads the new state written by A)
Figure 2-2: mutual exclusion is guaranteed by the atomicity of S3 conditional writes; DynamoDB is not needed

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.

Engineer A
Idle
S3 bucket
terraform.tfstate (v6)
.tflock: does not exist
CI pipeline B
Idle

Core commands and configuration

Command / configurationPurposeKey arguments / notes
terraform init -migrate-stateMigrate existing state to the new backendprompts for confirmation; -force-copy skip confirmation (CI)
terraform init -reconfigurere-initialize ignoring the old backend configuration (no migration)use when backend arguments change but the state location stays the same
terraform init -backend-config=FILEpartial configurationsame code, different bucket/key per environment
-lock-timeout=5mwait for the lock instead of failing immediatelyrecommended in CI
terraform force-unlock LOCK_IDdelete a leftover lockfirst confirm no process is running
aws s3api list-object-versionsview 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: save the 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-…"
Generate partial configuration for app and migrate (module 1's state is currently local):
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.
Observe the lock object: in terminal 1, run an apply that will stop at the confirmation prompt; in terminal 2, check the bucket:
# 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.

View state version history:
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  |
+----------------------------------+----------------------------+--------+
Keep: keep the bucket and key until the capstone lab ends; final cleanup is in module 8 (destroy app first, then bootstrap; the KMS key enters a 7-day pending-deletion period). Security note: The 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.

Command-line tasks
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
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · full course · includes the section on the S3 remote backend (it still used a DynamoDB lock table when recorded; for new projects, use use_lockfile as in this lesson)

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–80s
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.
or get a quiz score of ≥ 70%

Module 3 · Networking: VPC, subnets, routes, NAT, security groups

13:00 – 21:00 · Whether a subnet is “public” or “private” depends only on its route table; the NAT gateway is the item most often overlooked on the lab bill
8 minterraform-aws-modules/vpc 6.7.3Regional NAT (aws_nat_gateway availability_mode)★★★★★
Learning objectives
  • 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/vpc Create 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_rule resource and security group references (rather than CIDRs) to implement the minimum-privilege allow from the ALB to the application.
Prerequisites: Lesson 3 Azure VNet/NSG, and the port and network concepts from the Docker course. Importance:★★★★★

What: components of a VPC

ComponentTerraform resourcePurpose
VPCaws_vpcA regional private network with one primary CIDR (secondary CIDRs can be added); enable enable_dns_hostnames/enable_dns_support
Subnetaws_subnetbelongs to a single AZ; each subnet reserves 5 addresses (network, VPC router, DNS, reserved, broadcast)
Internet Gatewayaws_internet_gatewayTwo-way entry and exit between the VPC and the internet; scales horizontally and has no hourly fee
Route tableaws_route_table / aws_route / aws_route_table_associationdetermines where subnet traffic goes; 0.0.0.0/0 → igw i.e., a public subnet
NAT gatewayaws_nat_gateway + aws_eipLets private subnets egress only access the internet (pull images, call external APIs); billed by the hour plus data processed
Security groupaws_security_group + aws_vpc_security_group_ingress_rule/egress_ruleattached to an ENI; stateful firewall with allow rules only; can reference other security groups
Network ACLaws_network_aclsubnet-level stateless rules with allow/deny, matched in numeric order; usually keep the defaults
VPC endpointaws_vpc_endpointGateway 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)

OptionTerraformAvailabilityFixed monthly cost (≈730 hours)
No NAT; tasks in public subnets + public IPassign_public_ip = true—Each public IPv4 is about 0.005 USD/hour ≈ 3.6 USD; poor security, lab only
Single zonal NATvpc module single_nat_gateway = trueIf that AZ fails, all private subnets lose connectivityNAT ≈ 0.05 USD/hour ≈ 36 USD + EIP + per-GB processing fee
One zonal NAT per AZone_nat_gateway_per_az = trueAZ isolation (the classic production-recommended approach)× number of AZs (2 AZs ≈ 72 USD)
Regional NAT GatewayNative 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 AZBilling follows the AWS pricing page
VPC endpoints only (no NAT)S3 Gateway + ECR api/dkr, Logs, and Secrets Manager Interface endpointsNo public internet access; the most secureInterface 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—use data "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

AzureAWS
Subnet scoperegional (spans AZs)single AZ
Default outboundNew VNets no longer provide implicit outbound by default (see the Microsoft docs); NAT Gateway is recommendedPrivate subnets have no outbound at all; NAT or endpoints are required
FirewallNSG (can attach to subnets or NICs; has priorities and deny rules)Security group (attached to ENIs, allow only) + NACL (subnet-level, stateless)
ReferenceApplication Security GroupSecurity groups reference security groups
Common misconceptions① “A subnet named public is a public subnet” — the name doesn't matter; check the route table. ② “Security groups are stateless, so return traffic must also be allowed” — security groups are stateful; only NACLs are stateless. ③ “Inline 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

VPC myapp-lab 10.20.0.0/16 (ca-central-1) Internet Gateway AZ ca-central-1a AZ ca-central-1b Public subnet 10.20.0.0/24Route: 0.0.0.0/0 → igw ALB node NAT gateway + EIPsingle_nat_gateway Public subnet 10.20.1.0/24Route: 0.0.0.0/0 → igw ALB node Private subnet 10.20.10.0/24Route: 0.0.0.0/0 → nat-1a Fargate task ENIsg-app :8000 Private subnet 10.20.11.0/24Route: 0.0.0.0/0 → nat-1a (cross-AZ) Fargate task ENIsg-app :8000 Cross-AZ data transfer is billed separately
Figure 3-1: public vs private is determined by the route table; in the single-NAT design, outbound traffic from 1b crosses AZs to the NAT in 1a

Data flow: user requests and task outbound traffic

Inbound User IGW ALB (sg-alb :80) Task IP:8000 (sg-app only trusts sg-alb) Outbound Task (private IP) Private route table NAT (SNAT→EIP) IGW → ECR / Secrets / Logs S3 Gateway endpoint: pl-xxxx prefix-list route; image layers are downloaded from S3 without going through NAT (free)
Figure 3-2: inbound traffic only goes through the ALB; outbound goes through NAT. ECR image layers are actually stored in S3, so adding an S3 Gateway endpoint saves NAT processing fees

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.

Resources to be created
Estimated fixed monthly cost (730 hours, approximate)

Core resources and commands

Resource / commandPurposeKey arguments
module "vpc"Create VPC, subnets, IGW, NAT and route tables in one goazs,public_subnets,private_subnets,single_nat_gateway
cidrsubnet(prefix, newbits, netnum)Compute subnet CIDRscidrsubnet("10.20.0.0/16", 8, 10) = 10.20.10.0/24
data "aws_availability_zones"Get available AZsstate = "available"
aws_vpc_security_group_ingress_ruleA single inbound rulereferenced_security_group_id or cidr_ipv4,ip_protocol
aws ec2 describe-route-tablesVerify routes--filters Name=vpc-id,Values=…
terraform consoleInteractively verify the CIDR functionsNo 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)

Write network.tf and security.tf ("Commands" tab), then:
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
apply and time it (a NAT gateway usually takes 1–2 minutes to become available; this is the provider waiter at work):
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
Verify the route table:
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).

Verify security group references:
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
Cost and cleanup: the network is kept for module 4 (ECS). If you are not continuing today, run 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).

Command-line tasks
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
Scenario analysis
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

▶
Learn Terraform (and AWS) by Building a Dev Environment – Full Course for Beginners — freeCodeCamp.org
English · full course · creating a VPC, subnets, IGW, route tables, security groups and EC2 from scratch with Terraform (uses native resources, good for comparing with this lesson's module approach)

No verified video dedicated to Regional NAT Gateway was found.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or get a quiz score of ≥ 70%

Module 4 · Compute: EC2 (user_data) and ECS on Fargate

21:00 – 30:00 · The same myapp, two ways to run it: manage the VMs yourself, or deliver only the task definition — the ALB, target group and health checks connect it to users
9 minECS Fargate · awsvpcALB target_type = ip★★★★★
Learning objectives
  • Use data "aws_ssm_parameter" to get the latest AMI, and use aws_instance + user_data + IMDSv2 to launch an EC2 instance running myapp, and understand user_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.
Prerequisites: Image, port, health check and multi-container communication from the Docker course; networking from module 3. Importance:★★★★★

What: three common ways to run containers on AWS

EC2 + Docker (user_data)ECS on FargateEKS (module 6)
You manageOS, patches, Docker, process supervision, scalingTask definitions and servicesKubernetes manifests + (under Auto Mode) minimal node configuration
BillingInstance hoursTask vCPU/GB per secondControl plane 0.10 USD/hour + compute
NetworkingInstance ENI, port mappingawsvpc: one ENI and private IP per taskVPC CNI: one IP per Pod
Suited forlegacy applications, cases needing host-level controlthe default choice for stateless servicesexisting 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): keeps desired_count tasks 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

  1. Terraform registers a new revision (RegisterTaskDefinition), then UpdateService points to it.
  2. 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.
  3. The service registers task IP:8000 with the target group, and ALB health checks must consecutively succeed healthy_threshold times, after which the target becomes healthy (health_check_grace_period_seconds — failures within this window are ignored).
  4. 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 → stopTimeout then SIGKILL.
  5. 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.
  6. wait_for_steady_state = true Make 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 AppsECS Fargate
Entry pointbuilt-in ingress (Envoy)requires building your own ALB/target group/listener
Versioningrevisiontask definition revisions + service deployment
Multi-containermulti-container / sidecar within the same Container Appmultiple containers in the same task share the network namespace (localhost communicate)
Scale to 0supporteddesired_count 0 can be set, but there is no built-in "wake on request"
Common misconceptions① “apply succeeded = service is healthy” — if 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

User ALB (public subnet)Listener :80 → forwardTarget group tg-myappip · :8000 · /healthz ECS service myapp (desired 2, private subnets) Task #1 (ENI 10.20.10.37) app container :8000REDIS_HOST=localhostsecrets: APP_SECRET redis container :6379 shared network namespaceawslogs → /ecs/myapp Task #2 (ENI 10.20.11.84) app container :8000 redis container :6379 ECRmyapp:1.0 Secrets Managermyapp/app-secret CloudWatch Logs/ecs/myapp Accessed by the task execution role (module 5)
Figure 4-1: each Fargate task has one ENI; containers in a task share localhost; pulling images, fetching secrets and writing logs are done by the execution role

State machine: lifecycle of tasks and targets

ECS task PROVISIONING PENDING RUNNING DEACTIVATING STOPPING STOPPED create/attach ENIpull image, fetch secretsderegister targetSIGTERM→SIGKILL target group initial healthy unhealthy draining (removed) consecutive healthy_threshold successesderegistration_delay (30s in the lab)
Figure 4-2: a new task must reach RUNNING and then healthy before old tasks are deregistered and stopped; unhealthy tasks are replaced by the service

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.

ECS task
target group tg-myapp

Core resources and commands

Resource / commandPurposeKey arguments
aws_ecr_repositoryprivate image repositoryimage_tag_mutability,image_scanning_configuration,force_delete
aws ecr get-login-password | docker loginLog in to ECR with Docker (token valid for 12 hours)--password-stdin
aws_ecs_task_definitionTask specnetwork_mode = "awsvpc",cpu/memory,execution_role_arn,container_definitions
aws_lb_target_groupbackend set and health checkstarget_type = "ip",health_check.path,deregistration_delay
aws_ecs_servicemaintain task count, rolling deploymentsdeployment_circuit_breaker,wait_for_steady_state,load_balancer
aws ecs describe-servicesview deployments and events--query 'services[0].events[:5]'
aws elbv2 describe-target-healthtarget health status and reasonsTargetHealth.Reason
aws ecs execute-commandenter 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)

First create the ECR repository (the service depends on the image existing, so this takes two steps):
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.

Push the myapp image (the image built in the Docker course):
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.

Deploy ECS + ALB: save 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"
Verify:
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.

Try a rolling deployment and the circuit breaker: change 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.

Keep or clean up: module 5 adds secrets on top of this. To pause your study, run 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.

Command-line tasks
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
Scenario analysis
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

▶
Learn Terraform (and AWS) by Building a Dev Environment – Full Course for Beginners — freeCodeCamp.org
English · full demo with an EC2 instance, AMI data source and user_data (corresponds to the EC2 section of this module)

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

Video storyboard (about 100 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
Shot 4 · 75–100s
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.
or get a quiz score of ≥ 70%

Module 5 · IAM and secrets: roles, least privilege, Secrets Manager

30:00 – 37:00 · The execution role works for the platform; the task role works for the application; secrets appear only at runtime and never enter state
7 minephemeral (1.10) · write-only (1.11)secret_string_wo★★★★★
Learning objectives
  • 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_document data 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 arguments secret_string_wo so that secret values do not appear in plan and state.
Prerequisites: assume_role from module 1, the task definition from module 4, and lesson 2's sensitive. Importance:★★★★★

What: the two policies of a role

trust policy (assume_role_policy)permissions policy (identity-based policy)
answers the questionWho can assume me?What can the people who assume me do?
Key elementsPrincipal Principal (such as ecs-tasks.amazonaws.com),sts:AssumeRole, conditions (aws:SourceAccount)Action,Resource,Condition
Terraformaws_iam_role.assume_role_policyaws_iam_role_policy (inline) / aws_iam_policy + attachment

The two ECS roles

Task execution role execution_role_arnTask role task_role_arn
Who uses itECS agent / Fargate platform (before the container starts)The application code inside the container (the SDK obtains credentials via the container credentials endpoint)
Typical permissionsecr: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
myappneeded (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 AmazonECSTaskExecutionRolePolicy allows 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 = true it is only hidden in CLI output,and it is not removed from state.

How: three ways to hand secrets to myapp

ApproachSecrets in state?Notes
A. random_password resource + secret_stringyes (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_versionnoTerraform ≥ 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_secretnothe 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_invocation etc.
  • write-only arguments: aws_secretsmanager_secret_version.secret_string_wo,aws_db_instance.password_wo etc. (each needs the matching *_wo_version). RDS can also use manage_master_user_password = true to 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,locals and variables/outputs marked ephemeral = true variables or outputs; passing one to a regular argument produces an error.
  • aws_secretsmanager_secret_version The arn attribute is deprecated; use secret_arn instead.

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

AzureAWS
Workload identitymanaged identity (system or user assigned)IAM role (task role / instance profile)
Authorization modelRBAC role assignment to a scopepolicy documents (Action/Resource/Condition)
SecretsKey Vault + Container Apps secret referencesSecrets Manager + task definition secrets.valueFrom
write-onlyazurerm: some resources support *_wo (per the docs)secret_string_wo,password_wo etc.
Common misconceptions① “AccessDenied when calling S3 from a task, so add permissions to the execution role” — the application uses the task role. ② “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

Task execution role myapp-ecs-exectrust: ecs-tasks.amazonaws.comECR pull (scoped to the repository)Logs write · GetSecretValue (1 ARN) Task role myapp-tasktrust: ecs-tasks.amazonaws.com+ aws:SourceAccount conditionneeded by the application (myapp: none) ① Before launch (Fargate platform)GetAuthorizationToken / BatchGetImageGetSecretValue → inject as environment variablesCreateLogStream ② At runtime (application inside the container)SDK → container credentials endpointAWS_CONTAINER_CREDENTIALS_RELATIVE_URItemporary credentials rotate automatically ECR / CloudWatch Logsplatform dependencies Secrets Managermyapp/app-secret S3 / SQS / DynamoDB …business dependencies (as needed)
Figure 5-1: the execution role serves "starting the container"; the task role serves "the code inside the container"

Data flow: lifecycle of a write-only secret

ephemeral resourceGetRandomPassword value in core memorynot written to plan / not written to state secret_string_woPutSecretValue (only at apply time) Secrets ManagerKMS-encrypted storage state only records: secret_string_wo = null · has_secret_string_wo = true · secret_string_wo_version = 1Rotation: change secret_string_wo_version to 2 → the next apply regenerates and writes the value ECS task startsvalueFrom ARN → environment variable
Figure 5-2: ephemeral + write-only: the value is never written to disk from generation to writing into Secrets Manager

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.

Execution steps
terraform.tfstate (excerpt)

Core resources and commands

Resource / commandPurposeKey arguments
data "aws_iam_policy_document"Generate the policy JSONstatement { actions, resources, condition, principals }
aws_iam_role_policyinline policyrole,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_wowrite the secret with write-onlypaired with secret_string_wo_version
aws iam simulate-principal-policysimulate whether a role can perform an operation--action-names,--resource-arns
aws secretsmanager get-secret-valueverify 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)

Add secrets.tf and iam.tf, and modify ecs.tf: remove 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.
Apply and verify the container gets the secret (printing the length only, not the value):
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"
    }
]
Check state:
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"]
}
0
Rotate the secret and have the task get the new value:
terraform 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.

For comparison (optional, do not do this in production): replace 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.

Command-line tasks
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
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · the course discusses sensitive variables and state security (recorded before ephemeral/write-only; the new mechanisms follow this lesson)

No verified video on Terraform ephemeral resources / write-only arguments was found; a storyboard script is provided.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–90s
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.
or get a quiz score of ≥ 70%

Module 6 · Community modules and EKS

37:00 – 45:00 · Stand on the shoulders of terraform-aws-modules: choose wisely, lock versions, read the source — then spin up an EKS Auto Mode cluster with 30 lines of HCL
8 mineks module 21.29.0EKS Auto Mode · K8s 1.37EKS from 0.10 USD/hour★★★★
Learning objectives
  • Evaluate community modules (maintenance activity, provider constraints, inputs and outputs, breaking-change notes), lock versions correctly, and know that .terraform.lock.hcl does not lock modules.
  • Use terraform-aws-modules/eks v21 to create an EKS Auto Mode cluster (compute_config), configure access entries (access entries), and use aws eks update-kubeconfig to 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).
Prerequisites: Modules from lesson 2, and the VPC from module 3 of this lesson; basic Kubernetes objects from the K8s course. Importance:★★★★

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 moduleHand-written native resources
Speeda few dozen lines to build the 30+ resources EKS needsSlow; you need to understand each resource
Best practiceBuilt-in (IRSA/Pod Identity, encryption, access entries, tags)Do it yourself
ControllabilityLimited to the variables the module exposes; a major version upgrade may require movedFully controllable
Supply chain riskIntroduces third-party code; requires pinning versions and reviewing changesNone

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.hcl Only the provider is locked, the module version is not locked; the module version is entirely determined by version constraints. 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 plan entries in it look like module.eks.aws_eks_cluster.this[0]).
  • Before upgrading a major version, read UPGRADE-xx.md, which often requires moved blocks or terraform 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 approachWho manages nodesSyntax in Terraform
Auto ModeEKS (NodePool/NodeClass)compute_config
managed node groupsEKS manages the ASG; you choose instance types/AMIeks_managed_node_groups
Fargate Profileno nodes (one micro-VM per Pod)fargate_profiles
self-managed Karpenteryou deploy and upgrade Karpentermodules/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 costFree tier is free; Standard/Premium charge0.10 USD/hour (standard support)
“fully managed nodes”AKS AutomaticEKS Auto Mode
Identity to K8sEntra ID integration + Azure RBACaccess entries + access policies
Pod access to cloud APIsWorkload IdentityEKS Pod Identity / IRSA
Common misconceptions① “The lock file locks the module version” — it does not. ② “~> 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

your root module eks/ module "vpc" (v6)public_subnet_tags elb=1private_subnet_tags internal-elb=1 module "eks" (v21)name / kubernetes_versioncompute_config (Auto Mode)enable_cluster_creator_admin_permissionsvpc_id / subnet_ids module.eks internal resources (excerpt) aws_eks_cluster.this (API authentication mode + Auto Mode configuration) aws_iam_role.this (cluster role) aws_iam_role.eks_auto (Auto Mode node role) aws_kms_key (envelope encryption for Secrets) aws_security_group (cluster/nodes) aws_eks_access_entry / policy_association aws_cloudwatch_log_group (control plane logs) aws_iam_openid_connect_provider (IRSA, optional) actual resource names follow the module source and the plan output EKS managed (not in state)control plane (AWS account)NodePool general-purposeEC2 started by Auto Modemanaged add-ons cloud resources created by in-cluster objectsService type=LoadBalancer → NLBIngress → ALBPVC → EBS volume⚠ delete inside the cluster before destroy
Figure 6-1: Terraform manages the cluster and cloud-side dependencies; nodes and cloud resources created by Kubernetes objects are not in state

Flowchart: order of creation and deletion

Create VPC + subnet tags IAM roles / KMS EKS cluster (≈ 8–12 minutes) access entries first Pod → node provisioning Delete kubectl delete svc/ingress/pvc wait for LB / node reclamation terraform destroy leftover scan (ENI/SG/EBS) Skipping the first step, VPC deletion often fails with DependencyViolation due to the LB's ENIs/security groups (module 7)
Figure 6-2: the EKS deletion order matters as much as the creation order

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 / configurationPurposeNotes
terraform init -upgradeUpgrade modules and providers within constraintsThe module version is decided only by version .
terraform get -updateUpdate only the module—
terraform providersView the provider constraint tree of the root module and submodulesTroubleshoot version conflicts (e.g., the eks module requires aws ≥ 6.59)
aws eks update-kubeconfigWrite kubeconfig--name,--region,--alias
aws eks list-access-entriesSee who can access the clusterAPI authentication mode
aws eks describe-cluster-versionsView available K8s versions and support windowsChoose 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)

Cost and permissions You need permissions to create EKS, IAM roles, KMS and EC2. Even without deploying any app, the control plane + NAT costs about 0.15 USD per hour. If time or budget is limited, complete only steps 1 and 2 (plan alone is enough to learn the module structure) and skip the apply.
Reading the module to see what it creates (free of charge):
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]
  …
Check the provider constraint tree:
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 …
apply and deploy a test workload:
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
Delete in the correct order:
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.

Command-line tasks
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 -A
Scenario analysis
A 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

▶
Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide! — KodeKloud
English · covers using modules and the Registry, useful as a review of module concepts
▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · 15 minutes · review of Terraform architecture (core + provider) and IaC concepts

No verified Terraform video dedicated to the eks module v21 / EKS Auto Mode was found; a storyboard script is provided.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–70s
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.
Shot 4 · 70–90s
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.
or get a quiz score of ≥ 70%

Module 7 · Cloud troubleshooting in practice

45:00 – 53:00 · First work out "who refused me": credentials, IAM, dependencies, consistency, throttling, quotas — six error classes cover 90% of AWS deployment failures
8 minTF_LOG · CloudTrailInteractive troubleshooting tree★★★★★
Learning objectives
  • 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, CloudTrail lookup-events, Service Quotas.
  • Handle destroy hangs/failures: find dependencies not in state (ENIs, LBs, manually created resources), remediate safely, and make state match reality.
Prerequisites: Modules 1–6. Importance:★★★★★

What: the six major categories of AWS errors

CategoryTypical error keywordsWho refused youFirst diagnostic command
① Credential chainNo valid credential sources,ExpiredToken,InvalidClientTokenId,SSO session has expiredSDK / STS (has not reached the target service yet)aws sts get-caller-identity
② IAM authorizationAccessDenied,UnauthorizedOperation,not authorized to perform,explicit deny in a service control policyIAM policy evaluation enginedecode-authorization-message / simulate-principal-policy
③ Resource dependenciesDependencyViolation,has a dependent object,ResourceInUse,BucketNotEmptytarget service (resource still referenced)describe-network-interfaces --filters group-id/subnet-id
④ Eventual consistencyNotFound right after creation, NotFound,InvalidGroup.NotFound,role cannot be assumed,Invalid principaltarget service (data not yet propagated)retry; check whether the provider version already has built-in retries
⑤ ThrottlingRequestLimitExceeded,ThrottlingException,Rate exceeded,TooManyRequestsExceptionAPI rate limits (token bucket)TF_LOG_PROVIDER=DEBUG check the retry count
⑥ QuotasLimitExceeded,VpcLimitExceeded,AddressLimitExceeded,You have requested more vCPU capacityaccount/region quotasaws 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 plan look 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

  1. Is there any explicit Deny (identity policies, resource policies, SCPs, RCPs, permissions boundaries, session policies)? If yes → deny.
  2. Organizations SCP Is it allowed? No → deny (the error message will state service control policy).
  3. Does the resource policy allow it (in the same account, it can be granted separately)?
  4. permissions boundary, does the session policy allow it? No → deny.
  5. 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

SituationCorrect approachDon't
apply fails midwayfix the cause and run plan/apply again; Terraform continues from the current statemanually delete resources or edit state
destroy is blocked by a dependency not in statefind the dependency (ENI/LB) → delete it in the system that owns it → retry destroyterraform state rm then "pretend it was deleted" (leaves billable resources behind)
eventual consistencyjust retry; if necessary add depends_on or time_sleep (hashicorp/time) as a last resortsprinkle sleep everywhere
throttlingreduce -parallelism (e.g., to 5),retry_mode = "adaptive", split a large stateraise max_retries very high to hide the problem
a resource takes a long time to create/deleteuse the timeouts { create = "30m" } block of the resourceCtrl+C interruption (leaves locks and inconsistency)
Common misconceptions① “AccessDenied means adding * 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

providerSDK ① Credentialsnot found / expiredinvalid signatureInvalidClientTokenIdExpiredToken ⑤ Throttlingtoken bucket exhaustedRequestLimitExceededSDK retries automatically with backoff ② IAM authorizationSCP / RCPboundary / session policyidentity / resource policyAccessDenied ⑥ Quotasaccount/region limitsLimitExceededrequest an increase via Service Quotas ③④ Resource stateDependencyViolationNotFound (not yet propagated)IncorrectStateResourceInUse
Figure 7-1: from left to right, the later a request is refused, the more earlier stages have already passed — checking in this order is the fastest

Diagram: why destroy gets blocked by “invisible dependencies”

In the Terraform state aws_subnet.private aws_security_group.app aws_vpc.main Not in state (created by a service automatically or manually) ENI eni-0abc (Lambda/ECS) NLB (K8s Service) manually added SG rule reference unreleased EIP / VPC endpoint DeleteSecurityGroup / DeleteSubnet → DependencyViolation; Terraform retries for a period by default, then reports an error on timeout
Figure 7-2: half the dependencies are outside state; Terraform cannot order them for you

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

CommandPurposeNotes
aws sts get-caller-identityWho am Ifirst step for any error
aws sts decode-authorization-message --encoded-message MSGDecode the authorization failure message from services such as EC2in the output matchedStatements,explicitDeny
aws iam simulate-principal-policySimulate policy evaluationdoes not consider SCPs (check at the Organizations level)
aws cloudtrail lookup-eventsLook up recent API calls and error codesmanagement events, with a delay of a few minutes
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=…provider requests/responses, retriescontains sensitive information
aws ec2 describe-network-interfaces --filtersFind the ENIs occupying subnets/security groupsName=group-id,Name=subnet-id
aws service-quotas get-service-quota / request-service-quota-increaseCheck/request quotasquota code such as L-F678F1CE (VPCs per region)
terraform apply -parallelism=5reduce concurrencyease throttling
terraform apply -replace=ADDRforce replacement of a resourcereplace 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).

Fault 1: expired credentials / wrong profile:
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
Fault 2: DependencyViolation— manually create an ENI attached to sg-app (simulating an ENI created by a service), then try to delete the security group:
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
Fault 3: reading an AccessDenied— try to create a resource with a read-only role (if your SSO has a ReadOnly permission set):
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.

Review: classify each of the 3 faults (credential chain / dependency / IAM), and walk through them again with the interactive troubleshooting tree in the “Troubleshooting” tab below. Cleanup: Confirm the orphan ENI has been deleted: 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.

Command-line tasks
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]'
Scenario analysis
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

▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · the course includes practical debugging and code organization on AWS; can be used to review this module

No verified video on "troubleshooting Terraform on AWS (DependencyViolation / throttling / eventual consistency)" was found; a storyboard script is provided.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or get a quiz score of ≥ 70%

Module 8 · Cost, cleanup and self-check

53:00 – 60:00 · Hourly-billed resources drive the bill; on AWS, which has no resource groups, tags and inventories turn "deleted cleanly" into something you can verify
7 mindefault_tags · BudgetsPrices are approximate★★★★
Learning objectives
  • 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.
Prerequisites: Modules 1–7. Importance:★★★★

What: the cost structure of this lesson's architecture (approximate ca-central-1 prices; refer to the AWS pricing page)

ResourceBilling methodApproximate unit priceQuantity in the labPer hour
NAT gatewayhourly + per GB processed≈ 0.05 USD/hour + ≈ 0.05 USD/GB1≈ 0.050
Public IPv4 (NAT's EIP, ALB node per AZ)hourly0.005 USD/IP/hour≈ 3≈ 0.015
ALBhourly + LCU≈ 0.025 USD/hour + LCU1≈ 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/hour2 tasks≈ 0.027
Secrets Managerper secret per month + API calls0.40 USD/month1≈ 0.0005
KMS customer-managed keymonthly + requests1 USD/month1 (state)≈ 0.0014
CloudWatch Logs / ECR / S3per GBvery small—≈ 0
Total (excluding EKS)≈ 0.12 USD/hour ≈ 2.9 USD/day ≈ 87 USD/month
EKS control plane (optional lab)hourly0.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

  1. 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).
  2. During deployment: default_tags apply consistent tags via Project/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). Use aws_budgets_budget to set budget alerts.
  3. 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

OrderObjectNotes
1in-cluster objects (EKS LoadBalancer Services, Ingresses, PVCs)otherwise they leave NLBs/ALBs/EBS volumes behind, blocking VPC deletion
2eks/ root moduleabout 10–15 minutes
3app/ root moduleECR force_delete, secrets recovery_window_in_days = 0 to leave no residue; ALB/NAT deletion takes several minutes
4bootstrap/ (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
5leftover scanby tag + EIP/ENI/snapshots/log groups/ECR

Comparison with lesson 3 Azure

AzureAWS
catch-all cleanupaz group delete -n rg-tf-labno resource-group-level deletion; rely on destroy + tag scans
cost groupingresource groups / tagscost allocation tags (must be activated) / accounts
strongest isolationsubscriptionsaccounts (sandbox accounts for labs; close the whole account if necessary)
Common misconceptions① “Setting ECS desired_count to 0 stops the costs” — NAT, ALB and public IPs are still billed by the hour. ② “If Tag Editor finds nothing, everything was deleted cleanly” — resources that do not support tags, and resources not covered by default_tags (such as ENIs created by a service), will not appear; just-deleted resources may still briefly show in the tagging API. ③ “It is fine to delete bootstrap first” — the app's state lives in the bucket; once the bucket is gone, you can no longer manage (delete) the app's resources with Terraform.

Diagram: composition of the hourly bill (excluding EKS)

≈ 0.12 USD/hour NAT gateway ≈ 0.050 (42%) ALB ≈ 0.025–0.035 Fargate ≈ 0.027 IPv4 ≈ 0.015 · per-GB NAT processing fees, cross-AZ transfer, ALB LCUs and log ingestion are usage-based and not shown above · Secrets Manager and KMS are billed monthly; prorated per hour they are small, but they keep running until deleted · Forgetting to delete over a weekend (60 hours) ≈ 7 USD; forgetting for a month ≈ 87 USD; adding EKS adds another +73 USD/month · Prices are approximate as of 2026-11; check the AWS Pricing Calculator for specifics
Figure 8-1: the bulk of the lab bill is hourly-billed network components, not compute

Diagram: cleanup order and verification

① K8s LB/PVCkubectl delete ② eks/terraform destroy ③ app/terraform destroy ④ bootstrap/state bucket + KMS ⑤ Leftover scantagging API + targeted commands Verify each step: the destroy output should read “Destroy complete! Resources: N destroyed.”, with N matching the number of entries in state list If any step fails → go back to the module 7 troubleshooting tree; do not skip it
Figure 8-2: delete bootstrap last; the leftover scan is part of cleanup, not optional

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.

Run duration: 2 hours
Number of NAT gateways: 1
Number of Fargate tasks (0.25 vCPU/0.5 GB): 2

Cost and cleanup commands

CommandPurposeNotes
infracost breakdown --path .Estimate monthly costrequires an Infracost API key (free sign-up); offline, use terraform show -json plan and pass it to Infracost
terraform state list | wc -lRecord the resource count before destroycompare with the destroy output
terraform plan -destroyPreview deletioncheck whether bootstrap would be deleted by mistake
aws resourcegroupstaggingapi get-resourcesfind leftovers by tag--tag-filters Key=Project,Values=myapp-tf-lab
aws ce get-cost-and-usageCheck actual costsbilling 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)

(optional) Estimate the current app's monthly cost with Infracost:
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
Record and destroy app:
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
destroy bootstrap (final step):
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.

Run leftover scan:
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.

Check the bill the next day: in 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').

Command-line tasks
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//'
Scenario analysis
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

▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · 15 min · review of the Terraform lifecycle (including destroy), good for review after class

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–80s
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.
or get a quiz score of ≥ 70%

Command cheat sheet

Terraform on AWS: authentication, state, networking, ECS, IAM, EKS, troubleshooting, cleanup
aws 6.73.0Terraform 1.17

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 keywordCategoryFirst actionModule
No valid credential sources / SSO session has expiredcredential chainaws sso login, check AWS_PROFILEM1
InvalidClientTokenIdcredential chainenv | grep AWS_ look for leftover static keysM1
AWS account ID not allowedguardrailswitch to the correct profileM1
Error acquiring the state lock + PreconditionFailedstate lockcheck the .tflock holder → after confirming, force-unlockM2
kms:Decrypt AccessDenied (during init)IAMKMS key policy + caller permissionsM2
InvalidSubnet.ConflictNetworkingcheck cidrsubnet netnumM3
ResourceInitializationError ... i/o timeoutNetworkingprivate subnet outbound (NAT/endpoints) and SG outboundM3/M4
CannotPullContainerErrorimagetag/region/architectureM4
Target.FailedHealthChecksapplication/networkpath, listening address, SG referencesM4
unable to retrieve secret from asmIAMexecution role GetSecretValueM5
Invalid use of ephemeral valueTerraformswitch to *_wo argumentM5
Unsupported argument "cluster_name"module versioncompare against eks v21 input namesM6
DependencyViolationdependenciesfind ENIs by SG/subnet, delete the occupantM7
explicit deny in a service control policyIAM (organization)contact the platform team; it is not a role problemM7
RequestLimitExceededthrottling-parallelism=5, split the stateM7
BucketNotEmpty / RepositoryNotEmptyExceptioncleanupforce_destroy/force_delete apply firstM8

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

Deliver myapp to AWS with Terraform: VPC + ECS Fargate + ALB + ECR + Secrets Manager; destroy after acceptance
After class ≈ 45 minCost ≈ 0.12 USD/hour, about 0.3 USD for the whole run
Scenario myapp needs a demo environment launched on AWS ca-central-1. Requirements: all infrastructure is managed by Terraform; state is stored in an encrypted, versioned S3 bucket with native locking; the application runs in private subnets across two AZs and is reachable only through the ALB; images come from a private ECR; application secrets come from Secrets Manager and must not appear in state; the execution role follows least privilege; all resources carry the 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.
Preparation (modules 0, 1)
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 amd64
bootstrap state bucket (module 2): copy the bootstrap/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
Networking and security groups (module 3): 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"
ECR and image (module 4)
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.0
secrets, IAM, ECS, ALB (modules 4, 5): secrets.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
Acceptance checks
# 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=0
(Bonus) rolling release and rollback: push myapp: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).
Destroy and leftover check (module 8)
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.

Acceptance checklist

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

Sources for the technical facts in this lesson (verified: 2026-11-15)
TopicVerification resultSources (accessed 2026-11-15)
Terraform CLILatest v1.17.2 (2026-11-11); 1.17 adds -minimal-refresh, Policy GA; ephemeral resources 1.10, write-only arguments 1.11Terraform CHANGELOG
aws provider version6.73.0 (released 2026-11-11)Registry(API /v1/providers/hashicorp/aws)
resource-level regionSince 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-onlyEnhanced Region Support
Authentication order and retriesprovider arguments → environment variables → shared credentials → shared config → container credentials → instance profile; max_retries default 25; retry_mode standard/adaptiveAWS Provider docs
S3 backenduse_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 gatewayavailability_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 modeaws_nat_gateway
Community modulesvpc 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.1terraform-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 falseterraform-aws-eks README
EKS versionsstandard 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-01EKS 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_woprovider docs source code · secretsmanager_secret_version
ECS / Fargateawsvpc, CPU/memory combinations, circuit breaker, task execution roleECS on Fargate · execution role
PricingNAT, ALB, Fargate, public IPv4 (0.005 USD/hour), EKS (0.10 USD/hour standard support) and similar figures are all approximateVPC 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.