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.
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
- Cost guardrails โ alerts are your safety net; this lesson is the habit that keeps them quiet.
- Tooling setup on Windows โ CLI profiles
learn-sandboxandlearn-billing.
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:
- Create with IaC. If CDK, SAM, Terraform or CloudFormation created it, one command removes it.
- Tag everything. Tags are labels (key = value) you attach to resources. With a consistent tag you can find every lab resource in every Region.
- 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
| Tool | Finds or removes | Cost | Limitations |
|---|---|---|---|
cdk destroy / sam delete / terraform destroy / delete-stack | Exactly what that tool created | Free | Misses anything created by hand or by a service on your behalf (log groups, snapshots, ENIs); some resources have retain policies |
| Cost Explorer | Which services, Regions and usage types are costing money | Console free; API USD 0.01 per request | Data lags up to a day |
| Billing โ Bills | Month-to-date charges by service and Region | Free | Also lags; shows charges, not resource IDs |
| Tag Editor | Tagged resources across all Regions in one search | Free | Only supported resource types; untagged resources need a different search |
| AWS Resource Explorer | Search all resources, including untagged (tag:none) | No additional charge | Must be turned on (an aggregator index) first |
aws resourcegroupstaggingapi get-resources | Tagged (or previously tagged) resources in one Region per call | Free | Does not return untagged resources; loop over Regions |
| aws-nuke (third party, MIT) | Deletes almost everything in an account | Free | Extremely destructive; only for a dedicated sandbox account |
Microsoft / Azure comparison
| You know (Azure) | AWS equivalent | What's different |
|---|---|---|
| Delete the resource group | cdk destroy / terraform destroy / delete the CloudFormation stack | AWS has no resource-group-level delete for everything; stacks are the closest unit |
| Azure tags + tag inheritance via Policy | Tags + CDK Tags.Of(...), Terraform default_tags, tag policies (Module 15) | Tags do not inherit from a container by default |
| Azure Resource Graph Explorer | AWS Resource Explorer | Resource Explorer needs an index turned on per account |
| Cost Management โ Cost analysis | Cost Explorer | Group by service, Region, usage type, tag |
| Azure Resource Mover / scripts to purge subscriptions | aws-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:
| Key | Example | Purpose |
|---|---|---|
Project | cea-lab | Finds all course resources |
Lab | m03-fargate | Finds one lab's resources |
Owner | alex.learner | Who to ask (matters in shared accounts) |
DeleteAfter | 2026-11-18 | When it is safe to remove |
Tag keys and values are case-sensitive; pick a spelling and never vary it.
Apply tags automatically
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-sandboxThen 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 tableDELETE_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:noneand 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
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-billingaws 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
param(...)โ the profile and tag are parameters, so the same script works for any lab or account.aws ec2 describe-regions ... --output textโ lists the Regions enabled for the account as space-separated text.foreach ($region in $regions -split "\s+")โ loops over each Region; tags are Regional, so you must ask each one.aws resourcegroupstaggingapi get-resources --tag-filters ...โ returns ARNs of resources with that tag in that Region.2>$nulland$LASTEXITCODE -ne 0โ Regions blocked by your SCP return an access-denied error; the script reports them instead of stopping.$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.
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-credentialsputs 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 destroyfails โ 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 destroyremoved 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
| Symptom | Likely cause | Fix |
|---|---|---|
Stack stuck in DELETE_FAILED | Non-empty S3 bucket, attached ENI, dependency outside the stack | Read the stack Events, remove the blocker, delete again |
cdk destroy asks nothing and does nothing | Wrong profile or Region; stack name mismatch | cdk list --profile learn-sandbox; check env |
| Tag Editor shows nothing but you are still billed | Resource 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 teardown | Data lag, or monthly charges (KMS key, secret) prorated | Check again tomorrow; look at usage type to identify it |
| aws-nuke aborts: "no alias" | Account alias not set | aws iam create-account-alias |
| aws-nuke aborts: account in blocklist | You targeted a protected account | Check 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-sandboxExercises
- ๐ข Guided: Create a tagged S3 bucket and a tagged SQS queue in us-east-1 with the CLI, find both with
Find-LabResources.ps1and 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 atRemovalPolicyandAutoDeleteObjects). - ๐ด 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-labthere 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
Both resources appear in the script output under us-east-1 and in Tag Editor. After aws s3 rb and aws sqs delete-queue, the script prints nothing for us-east-1. The tagging API may briefly still list a deleted resource; if it shows an empty tag list later, it is a "previously tagged" record, not a live resource. Why: tags make discovery a query instead of a memory test.
CDK's default RemovalPolicy for S3 buckets is RETAIN, so cdk destroy leaves the bucket (and its cost) behind. For labs, set RemovalPolicy = RemovalPolicy.DESTROY and AutoDeleteObjects = true on the bucket so CDK empties and deletes it. Why: CDK protects stateful resources by default โ sensible in production, a cost trap in labs.
"Elastic Compute Cloud" charges without instances usually come from EBS volumes (state available), EBS snapshots, Elastic IPs / public IPv4 addresses or a NAT Gateway (billed under EC2 in many views). Use Cost Explorer filtered to eu-west-2 and EC2, grouped by usage type: EBS:VolumeUsage.gp3, EBS:SnapshotUsage, PublicIPv4:IdleAddress or NatGateway-Hours will point to the culprit. These resources were probably created by a wizard that did not apply your tags. Delete them and add an untagged-resource check to your routine. Why: billing usage types identify resources that tag searches cannot.
Knowledge check
Answer: The tool tracks what it created (stack or state file). Deleting by hand causes drift, leaves dependencies behind, and makes the next destroy fail.
Answer: Untagged resources (and anything outside the Region you called). Use Resource Explorer with tag:none for untagged resources.
Answer: Dry run by default (--no-dry-run needed to delete), the account must have an alias that does not contain prod and you must type it to confirm, and the config needs a blocklist with at least one account plus the target account listed explicitly.
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
A CloudOps engineer must identify all resources across all Regions in an account that belong to a project tagged Project=Payments. The solution must not require a script. What should the engineer use?
A. AWS Cost Explorer grouped by service B. Tag Editor in AWS Resource Groups, searching all Regions for the tag C. Amazon CloudWatch Logs Insights D. AWS Trusted Advisor
Answer: B. Tag Editor searches tagged resources across Regions in the console. A shows costs, not resource lists. C queries logs. D reports best-practice checks, not a tag inventory.
A learner's bill shows charges in a Region they do not remember using. Which tool shows the breakdown of charges by Region and usage type over recent days?
A. AWS Cost Explorer B. AWS Pricing Calculator C. AWS Artifact D. AWS Health Dashboard
Answer: A. Cost Explorer can group daily costs by Region and usage type. The Pricing Calculator estimates future costs; Artifact provides compliance reports; the Health Dashboard reports service events.
Completion checklist
- My IaC templates apply
Project,Lab,OwnerandDeleteAftertags 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.
Zero-cost local practice
Practise AWS APIs on your own PC with AWS Emulator, LocalStack, DynamoDB Local, SAM local, Testcontainers and docker compose โ and know exactly what local emulation cannot prove.
Microsoft-to-AWS overview
A first map from the Microsoft and Azure services you know to their AWS equivalents, plus the five mindset differences that matter most.