Skip to Content
Cloud Engineering Academy
0. Orientation & a Safe Learning Environment

Teardown discipline: find anything still costing money

Tag every lab resource, destroy it with the same tool that created it, and run a cross-Region checklist so nothing keeps billing.

beginnerโฑ 45 min๐ŸŸข FreeCLF-C02SOA-C03

Assumes: .NET 10 LTS ยท AWS CLI v2 ยท CDK CLI 2.1148 ยท SAM CLI 1.172 ยท Terraform 1.17 ยท aws-nuke 3.69 ยท Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Apply the course tagging convention (Project=cea-lab, Lab=<id>, Owner, DeleteAfter) automatically from the CLI, CDK and Terraform.
  • Tear down a lab with the tool that created it: cdk destroy, sam delete, terraform destroy, aws cloudformation delete-stack.
  • Run the "find anything still costing money" checklist across all Regions using Cost Explorer, Bills, Tag Editor, Resource Explorer and the Resource Groups Tagging API.
  • Decide when an automated cleanup tool such as aws-nuke is appropriate, and run it safely (dedicated sandbox, dry run first).

Prerequisites

Why this matters in banking

In a bank, "orphaned" resources are not only a cost problem. An unused but running database still holds data that must be protected, backed up, patched and included in audits; a forgotten public IP is attack surface; an old snapshot of a test database may contain data that should have been deleted under a retention policy or a GDPR erasure request. Teams that can prove what they deleted, and find what they did not, pass audits faster. Inventory and clean-up are security controls.

The idea in plain language

Teardown discipline means: everything you create in a study session is deleted in that same session, using the same tool that created it, and then you check that nothing is left.

Three ideas make this easy:

  1. Create with IaC. If CDK, SAM, Terraform or CloudFormation created it, one command removes it.
  2. Tag everything. Tags are labels (key = value) you attach to resources. With a consistent tag you can find every lab resource in every Region.
  3. Check the bill, not your memory. Cost Explorer and the Bills page show what AWS is actually charging for, including things you forgot you created.

Analogy: Closing a bank branch at night. You do not trust memory that the vault is shut โ€” you follow the closing checklist, walk every room, and the alarm system confirms it. Tags are the inventory stickers on every piece of equipment; Cost Explorer is the next morning's report of what used electricity overnight.

What problem each tool solves

ToolFinds or removesCostLimitations
cdk destroy / sam delete / terraform destroy / delete-stackExactly what that tool createdFreeMisses anything created by hand or by a service on your behalf (log groups, snapshots, ENIs); some resources have retain policies
Cost ExplorerWhich services, Regions and usage types are costing moneyConsole free; API USD 0.01 per requestData lags up to a day
Billing โ†’ BillsMonth-to-date charges by service and RegionFreeAlso lags; shows charges, not resource IDs
Tag EditorTagged resources across all Regions in one searchFreeOnly supported resource types; untagged resources need a different search
AWS Resource ExplorerSearch all resources, including untagged (tag:none)No additional chargeMust be turned on (an aggregator index) first
aws resourcegroupstaggingapi get-resourcesTagged (or previously tagged) resources in one Region per callFreeDoes not return untagged resources; loop over Regions
aws-nuke (third party, MIT)Deletes almost everything in an accountFreeExtremely destructive; only for a dedicated sandbox account

Microsoft / Azure comparison

You know (Azure)AWS equivalentWhat's different
Delete the resource groupcdk destroy / terraform destroy / delete the CloudFormation stackAWS has no resource-group-level delete for everything; stacks are the closest unit
Azure tags + tag inheritance via PolicyTags + CDK Tags.Of(...), Terraform default_tags, tag policies (Module 15)Tags do not inherit from a container by default
Azure Resource Graph ExplorerAWS Resource ExplorerResource Explorer needs an index turned on per account
Cost Management โ†’ Cost analysisCost ExplorerGroup by service, Region, usage type, tag
Azure Resource Mover / scripts to purge subscriptionsaws-nuke (community tool)Not an AWS product; no official "empty this account" button

Architecture

Step-by-step implementation

Adopt the tagging convention

Every resource you create in a lab gets these tags:

KeyExamplePurpose
Projectcea-labFinds all course resources
Labm03-fargateFinds one lab's resources
Owneralex.learnerWho to ask (matters in shared accounts)
DeleteAfter2026-11-18When it is safe to remove

Tag keys and values are case-sensitive; pick a spelling and never vary it.

Apply tags automatically

Program.cs (CDK app)
using Amazon.CDK;

var app = new App();
var stack = new Stack(app, "CeaLabM03", new StackProps
{
    Env = new Amazon.CDK.Environment { Region = "us-east-1" },
});

// Tags.Of applies the tag to every taggable resource in the scope.
Tags.Of(app).Add("Project", "cea-lab");
Tags.Of(app).Add("Lab", "m03-fargate");
Tags.Of(app).Add("Owner", "alex.learner");
Tags.Of(app).Add("DeleteAfter", "2026-11-18");

app.Synth();

Destroy with the creating tool

# CDK: destroys every stack in the app (asks for confirmation).
cdk destroy --all --profile learn-sandbox

# SAM: deletes the stack and, by default, asks about the artifacts bucket contents.
sam delete --stack-name cea-lab-m03-hello --profile learn-sandbox --region us-east-1

# Terraform: shows the plan of what will be destroyed, then asks to confirm.
terraform destroy

# Plain CloudFormation:
aws cloudformation delete-stack --stack-name cea-lab-m02-vpc --profile learn-sandbox
aws cloudformation wait stack-delete-complete --stack-name cea-lab-m02-vpc --profile learn-sandbox

Then confirm nothing is half-deleted:

aws cloudformation list-stacks --profile learn-sandbox `
  --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE DELETE_FAILED ROLLBACK_COMPLETE `
  --query "StackSummaries[].[StackName,StackStatus]" --output table

DELETE_FAILED usually means something blocks deletion โ€” a non-empty S3 bucket, an ENI still attached, or a resource with a Retain policy. Fix the blocker and delete again.

Run the "find anything still costing money" checklist

Work through this list with the learn-sandbox profile (and learn-billing for billing pages):

  • CloudFormation: no lab stacks left; none in DELETE_FAILED (every Region you used).
  • Tag search across Regions: Console โ†’ Resource Groups & Tag Editor โ†’ Tag Editor โ†’ Regions All regions, Resource types All supported resource types, tag Project = cea-lab โ†’ Search resources. Expect zero results after teardown.
  • Untagged search: Console โ†’ Resource Explorer (turn it on once with an aggregator index in us-east-1) โ†’ search tag:none and look for anything you recognise from today.
  • Hourly suspects (check each in us-east-1 and eu-west-2): VPC โ†’ NAT gateways; EC2 โ†’ Load balancers; EC2 โ†’ Instances; RDS โ†’ Databases; EC2 โ†’ Elastic IPs; EC2 โ†’ Volumes with state available; EC2 โ†’ Snapshots (owned by me).
  • Monthly suspects: KMS โ†’ Customer managed keys; Secrets Manager โ†’ Secrets; CloudWatch โ†’ Log groups sorted by stored bytes, retention not "Never expire".
  • Bills: Billing and Cost Management โ†’ Bills โ†’ current month โ†’ charges by service and by Region. Any Region other than us-east-1 and eu-west-2 is a red flag.
  • Next day โ€” Cost Explorer: daily granularity, last 7 days, group by Service, then by Region, then by Usage type. Yesterday's cost should be close to zero.

Script the tag search across Regions

Find-LabResources.ps1
param(
    [string]$Profile = "learn-sandbox",
    [string]$TagKey = "Project",
    [string]$TagValue = "cea-lab"
)

# Regions enabled for this account.
$regions = aws ec2 describe-regions --profile $Profile --query "Regions[].RegionName" --output text
foreach ($region in $regions -split "\s+") {
    # Calls to Regions blocked by the SCP fail; report and continue.
    $arns = aws resourcegroupstaggingapi get-resources --profile $Profile --region $region `
        --tag-filters "Key=$TagKey,Values=$TagValue" `
        --query "ResourceTagMappingList[].ResourceARN" --output text 2>$null
    if ($LASTEXITCODE -ne 0) { Write-Host "$region : not accessible (SCP or disabled Region)"; continue }
    if ($arns) { Write-Host "$region :"; $arns -split "\s+" | ForEach-Object { Write-Host "  $_" } }
}

Remember the limits: get-resources only returns resources that are tagged (or were tagged once โ€” those show an empty tag list), and only in the Region you call. Untagged resources need Resource Explorer or the per-service console checks.

AWS Console instructions

  • CloudFormation โ†’ Stacks (filter: Active / Deleted failed)
  • Resource Groups & Tag Editor โ†’ Tag Editor โ†’ Find resources to tag (Regions: All regions)
  • Resource Explorer โ†’ Settings โ†’ Turn on / Create aggregator index, then the search bar (tag:none, tag.key:Project)
  • Billing and Cost Management โ†’ Bills (charges by service, charges by Region)
  • Billing and Cost Management โ†’ Cost Explorer (Date range: last 7 days; Granularity: Daily; Group by: Service / Region / Usage type)

AWS CLI

# All resources tagged Project=cea-lab in us-east-1.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --region us-east-1 --profile learn-sandbox

# Hourly suspects in one Region.
aws ec2 describe-nat-gateways --filter Name=state,Values=available --query "NatGateways[].NatGatewayId" --profile learn-sandbox
aws elbv2 describe-load-balancers --query "LoadBalancers[].LoadBalancerName" --profile learn-sandbox
aws rds describe-db-instances --query "DBInstances[].[DBInstanceIdentifier,DBInstanceStatus]" --profile learn-sandbox
aws ec2 describe-addresses --query "Addresses[].[PublicIp,AssociationId]" --profile learn-sandbox
aws ec2 describe-volumes --filters Name=status,Values=available --query "Volumes[].[VolumeId,Size]" --profile learn-sandbox
aws ec2 describe-snapshots --owner-ids self --query "Snapshots[].[SnapshotId,VolumeSize,StartTime]" --profile learn-sandbox

# Customer managed KMS keys (AWS managed keys are free to hold).
aws kms list-keys --query "Keys[].KeyId" --profile learn-sandbox

# Log groups without a retention setting (they never expire).
aws logs describe-log-groups --query "logGroups[?retentionInDays==null].logGroupName" --profile learn-sandbox

# Yesterday's cost by service (Cost Explorer API: USD 0.01 per request; run from the management account).
aws ce get-cost-and-usage --time-period Start=2026-11-16,End=2026-11-17 --granularity DAILY `
  --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE --profile learn-billing

aws kms list-keys lists both AWS managed and customer managed keys; use aws kms describe-key --key-id <id> and check KeyManager = CUSTOMER to find the ones that cost money.

Infrastructure as Code

The tagging snippets in step 2 are the IaC part of this lesson. The key principle: the stack is the unit of deletion. Design each lab as one stack (or one Terraform root module) so one command removes it.

Complete code

Find-LabResources.ps1 above is complete and runnable. Save it to your learning-journal repository and run:

pwsh ./Find-LabResources.ps1 -Profile learn-sandbox

(Use powershell instead of pwsh if you only have Windows PowerShell 5.1.)

Code explained line by line

  1. param(...) โ€” the profile and tag are parameters, so the same script works for any lab or account.
  2. aws ec2 describe-regions ... --output text โ€” lists the Regions enabled for the account as space-separated text.
  3. foreach ($region in $regions -split "\s+") โ€” loops over each Region; tags are Regional, so you must ask each one.
  4. aws resourcegroupstaggingapi get-resources --tag-filters ... โ€” returns ARNs of resources with that tag in that Region.
  5. 2>$null and $LASTEXITCODE -ne 0 โ€” Regions blocked by your SCP return an access-denied error; the script reports them instead of stopping.
  6. $arns -split "\s+" โ€” prints one ARN per line so you can copy them into a delete command.

The optional heavy tool: aws-nuke

aws-nuke (MIT licence, version 3.69.1 released 2026-11-05) scans an account and deletes nearly every resource it finds. It is useful when a sandbox has become a mess. It is also the fastest way to destroy something you cared about.

Only in a dedicated sandbox account โ€” never anywhere else

Never point aws-nuke at a management account, a work account, an account with data you want to keep, or any account shared with other people. Run a dry run first and read every line of the output. Deletion is permanent: there is no undo for deleted S3 objects, KMS keys after their waiting period, or databases without snapshots.

Its own safety features (from the project's documentation): it only lists resources unless you pass --no-dry-run; it asks you to type the account alias twice; it refuses to run if the account has no alias or the alias contains prod; the config must contain a blocklist with at least one account ID, and the target account must be listed explicitly.

nuke-config.yaml
regions:
  - global
  - us-east-1
  - eu-west-2

# Accounts that must never be nuked. Put your MANAGEMENT account here.
blocklist:
  - "444455556666"

accounts:
  "111122223333": # cea-sandbox
    filters:
      # Keep the roles that let you (and the management account) sign in.
      IAMRole:
        - type: glob
          value: "AWSReservedSSO_*"
        - "OrganizationAccountAccessRole"
      IAMRolePolicyAttachment:
        - type: glob
          value: "AWSReservedSSO_*"
        - type: glob
          value: "OrganizationAccountAccessRole -> *"

Resource type names and filter syntax change between releases โ€” confirm them with aws-nuke resource-types and aws-nuke explain-config โš  VERIFY before relying on this file.

# The account needs an alias (globally unique, must not contain "prod").
aws iam create-account-alias --account-alias cea-sandbox-alex-learner --profile learn-sandbox

# aws-nuke reads standard AWS environment variables; export short-lived SSO credentials into this shell only.
aws configure export-credentials --profile learn-sandbox --format powershell | Invoke-Expression

# 1) Dry run: lists what WOULD be removed. Read all of it.
aws-nuke run --config nuke-config.yaml

# 2) Only if the dry run is exactly what you expect:
aws-nuke run --config nuke-config.yaml --no-dry-run

# Close the shell afterwards so the exported credentials disappear.

Whether aws-nuke reads sso-session profiles directly via --profile is not documented clearly โš  VERIFY; exporting temporary credentials into one shell avoids the question.

A safer alternative for a hopelessly messy sandbox: close it from the management account (aws organizations close-account) and create a fresh one. Closed accounts enter a post-closure period before permanent deletion, and Organizations limits how many accounts you can close in a period โš  VERIFY the current quota.

Security considerations

  • Teardown is also data protection: delete lab data, snapshots and log groups you no longer need, and never put real personal data in a lab in the first place.
  • Least privilege for cleanup: the tag-search and checklist commands need only read permissions; deleting needs write. In a bank, automated cleanup runs under a dedicated role with an approval step.
  • aws configure export-credentials puts live keys in your shell's environment; use one dedicated shell and close it afterwards.

โš  Learning shortcut โ€” not for production

Manual checklists and a personal aws-nuke config are fine for one learner. Banks enforce tagging with tag policies and SCPs that deny untagged creation, run scheduled inventory with AWS Config and Resource Explorer, and delete non-production resources through approved, logged automation. Module 15 covers the governed version.

Banking use case

"Harbour Bank" (fictional) requires CostCentre, DataClassification and Owner tags on every resource; an SCP denies creating EC2, RDS and S3 resources without them. A nightly job queries Resource Explorer for resources in sandbox accounts whose DeleteAfter date has passed, posts a list to each owner, and deletes them 48 hours later unless the owner extends the date. Quarterly, auditors sample deleted resources and check the CloudTrail Delete* events match the job's log โ€” evidence that test data containing fictional customer records was removed on schedule.

Common mistakes

  • Deleting resources by hand that IaC created โ†’ drift; the next terraform destroy fails โ†’ always destroy with the creating tool.
  • Checking only your default Region โ†’ resources hide elsewhere โ†’ use Tag Editor with All regions, and read Bills by Region.
  • Assuming cdk destroy removed everything โ†’ log groups, retained buckets and snapshots survive โ†’ run the checklist after every destroy.
  • Trusting the tag search alone โ†’ it misses untagged resources โ†’ add Resource Explorer tag:none.
  • Running aws-nuke without reading the dry run โ†’ it removes your sign-in roles or data โ†’ filter Identity Center roles and read every line.
  • Stopping instead of deleting โ†’ stopped EC2 instances still bill for EBS volumes and public IPv4; stopped RDS instances restart after 7 days.

Troubleshooting

SymptomLikely causeFix
Stack stuck in DELETE_FAILEDNon-empty S3 bucket, attached ENI, dependency outside the stackRead the stack Events, remove the blocker, delete again
cdk destroy asks nothing and does nothingWrong profile or Region; stack name mismatchcdk list --profile learn-sandbox; check env
Tag Editor shows nothing but you are still billedResource is untagged, or the charge is for storage (snapshots, logs)Resource Explorer tag:none; Cost Explorer by usage type
Cost Explorer still shows cost the day after teardownData lag, or monthly charges (KMS key, secret) proratedCheck again tomorrow; look at usage type to identify it
aws-nuke aborts: "no alias"Account alias not setaws iam create-account-alias
aws-nuke aborts: account in blocklistYou targeted a protected accountCheck you are using the sandbox credentials

Cost and cleanup

Cost: USD 0 โ€” the checklist only reads data (a few Cost Explorer API calls at USD 0.01 each if you use the CLI). If you created a test bucket in step 2:

aws s3 rb s3://cea-lab-m01-alex-20261117 --force --profile learn-sandbox

Exercises

  • ๐ŸŸข Guided: Create a tagged S3 bucket and a tagged SQS queue in us-east-1 with the CLI, find both with Find-LabResources.ps1 and in Tag Editor, delete them, and confirm both searches return nothing.
  • ๐ŸŸก Challenge: Write a CDK (C#) app with one stack containing a bucket and a queue, with the four course tags applied by Tags.Of(app). Deploy, find with Tag Editor, cdk destroy, and explain why the bucket might survive if it contains objects (look at RemovalPolicy and AutoDeleteObjects).
  • ๐Ÿ”ด Live problem: It is the 20th of the month. Bills shows USD 4.10 under "Elastic Compute Cloud" in eu-west-2, but Tag Editor finds nothing tagged Project=cea-lab there and the EC2 Instances page is empty. Find the cause.

Assignment

Add Find-LabResources.ps1 and a docs/teardown-checklist.md (your own wording of the checklist) to your learning-journal repository. From now on, every lab entry in your journal ends with "Teardown checked: date, tool used, cost the next day".

Solutions

Knowledge check

Interview questions

  • "How do you keep non-production AWS costs under control?" โ€” Everything through IaC so environments can be destroyed and recreated; mandatory tags enforced by policy; budgets and anomaly alerts per account; scheduled shutdown or TTL-based cleanup; a weekly review of Cost Explorer by service and usage type.
  • "How would you find every resource a project created across all Regions?" โ€” Tag search (Tag Editor or the Resource Groups Tagging API per Region), Resource Explorer for untagged resources, CloudFormation stack resources, and Cost Explorer by usage type to catch anything billing that the inventory missed.

Certification practice

Completion checklist

  • My IaC templates apply Project, Lab, Owner and DeleteAfter tags automatically
  • I can destroy a lab with CDK, SAM, Terraform and CloudFormation commands
  • I ran the full checklist once and found nothing billing
  • Resource Explorer is turned on with an aggregator index
  • I understand when (not) to use aws-nuke

Key takeaways

  • Tear down in the same session, with the same tool that created the resources.
  • Consistent tags turn "what's still running?" into a query across Regions.
  • Tag searches miss untagged resources โ€” combine them with Resource Explorer and Cost Explorer usage types.
  • The bill is the source of truth: check Cost Explorer the next day.
  • aws-nuke is a last resort for a dedicated sandbox, always after a dry run.

Further reading

Independent learning resource โ€” not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page