What counts as an orphaned AWS resource, and why is 'unattached' not proof of waste?
An orphaned resource is infrastructure that keeps billing after the workload it served has moved on. Two of the most common examples are EBS volumes left in the available state after an instance is terminated or a volume is detached, and load balancers that still exist after their targets were drained or their DNS records were repointed. Both bill whether or not anything uses them. EBS charges for provisioned capacity, and load balancers charge for every hour they run.
Teams run sweeps for three reasons. The first is cost: these charges recur every month and rarely appear in any team's budget. The second is clutter: stale resources make inventories, audits and incident response slower to read. The third is security surface: an internet-facing load balancer with a forgotten listener, or a volume holding old customer data, is exposure that no one is watching. The work usually falls to backend and platform engineers. They have the account access and the context to judge what a resource was for.
This article's core rule is that available status and low traffic are signals to investigate, not evidence to delete. A detached volume may hold the only copy of a database someone moved off an instance during a migration. A load balancer that sees a few requests a month may front a disaster-recovery path, a partner webhook or a quarterly batch job. Deleting either produces a false positive that costs far more than the resource ever did.
How do you find unattached EBS volumes with the AWS CLI?
The starting point is a single call per region: aws ec2 describe-volumes --filters Name=status,Values=available. The available status means the volume exists but is not attached to any instance. Add a --query expression such as Volumes[].{ID:VolumeId,Size:Size,Type:VolumeType,Created:CreateTime,Tags:Tags} so the output contains only what you need for triage. Size and type let you estimate cost. Creation time and tags help you find the owner.
Results are regional. A call against us-east-1 says nothing about eu-west-1, and abandoned volumes often sit in regions nobody looks at. Build a region list with aws ec2 describe-regions --query 'Regions[].RegionName' --output text, or use the shorter list of regions your organization actually uses, and loop over it with --region. The CLI follows pagination tokens automatically by default. If you use an SDK, --max-items, or --no-paginate, you have to handle NextToken yourself. Otherwise a large account returns a partial list that looks complete.
An available status alone tells you very little. Before you treat a volume as abandoned, check three things:
- Creation date. A volume created last week is more likely mid-migration than forgotten. Note that
CreateTimeis when the volume was created, not when it was detached. The API does not return a detach timestamp. - Tags. Missing
Name, owner, or stack tags suggest manual creation or a failed teardown. Tags that point to a live service suggest someone may still need the volume. - Detach events. If CloudTrail is enabled, search for
DetachVolumeevents withaws cloudtrail lookup-events. A detach made two days ago by a deployment role looks like maintenance. If no detach appears within event history's 90-day window, the volume has likely been unattached for months.
#!/usr/bin/env bash
# List unattached EBS volumes in every enabled region, then show any
# DetachVolume events CloudTrail still holds (90-day event history).
set -euo pipefail
# describe-regions returns only regions enabled for this account.
# Replace with a fixed list, e.g. "us-east-1 eu-west-1", if you prefer.
REGIONS=$(aws ec2 describe-regions --query 'Regions[].RegionName' --output text)
for region in $REGIONS; do
# The CLI follows NextToken automatically. Do not add --no-paginate
# or --max-items here, or large accounts return a partial list.
aws ec2 describe-volumes --region "$region" \
--filters Name=status,Values=available \
--query 'Volumes[].[VolumeId,Size,VolumeType,CreateTime,Tags[?Key==`Name`].Value | [0]]' \
--output text |
while read -r vol size type created name; do
echo "$region $vol ${size}GiB $type created=$created name=$name"
# CreateTime is creation, not detach time, so ask CloudTrail when
# the volume was detached and by whom. lookup-events accepts one
# lookup attribute, so filter on the volume ID and match the event
# name in --query. lookup-events is rate limited, so expect this to
# be slow on accounts with many volumes.
aws cloudtrail lookup-events --region "$region" \
--lookup-attributes AttributeKey=ResourceName,AttributeValue="$vol" \
--query 'Events[?EventName==`DetachVolume`].[EventTime,Username]' \
--output text < /dev/null |
sed 's/^/ detached: /'
# No "detached:" line means no detach in the last 90 days. The volume
# was never attached, or it was detached before that window.
done
done
A Bash loop that lists available (unattached) EBS volumes with size, type, creation time and Name tag across all enabled regions, then looks up recent DetachVolume events in CloudTrail for each volume.
How do you tell whether a load balancer is actually idle?
Load balancers need two checks: a structural one (does anything sit behind it?) and a behavioural one (does traffic reach it?). Either check alone produces false positives.
For ALBs and NLBs, list target groups per load balancer with aws elbv2 describe-target-groups --load-balancer-arn, then run aws elbv2 describe-target-health on each. A load balancer whose target groups have no registered targets, or only unhealthy ones, is a candidate. An empty target group does not prove the ALB is idle. An ALB can serve fixed responses or redirects from listener rules with no targets at all, for example an HTTP-to-HTTPS redirect for a legacy domain. For Classic Load Balancers, aws elb describe-load-balancers shows the registered instances directly. An empty Instances list is the structural signal.
Then confirm with CloudWatch:
| Load balancer type | Structural check | Traffic metric (namespace) |
|---|---|---|
| Application (ALB) | describe-target-health shows no registered or healthy targets |
RequestCount (AWS/ApplicationELB) |
| Network (NLB) | describe-target-health shows no registered or healthy targets |
ProcessedBytes, NewFlowCount, ActiveFlowCount (AWS/NetworkELB) |
| Classic | No instances in describe-load-balancers output |
RequestCount for HTTP listeners. EstimatedProcessedBytes for TCP (AWS/ELB) |
The observation window determines whether the result means anything. A quarterly reconciliation job, a month-end export, a disaster-recovery endpoint or a seasonal campaign looks idle across a 14-day window. CloudWatch keeps 5-minute datapoints for about 63 days and hourly datapoints for about 15 months, so you can query hourly sums across a full year. Pick the lookback period deliberately. Record it in the cleanup ticket, for example "zero RequestCount, hourly sum, 90 days." That way, if something breaks later, the reviewer can see exactly what evidence the decision rested on.
#!/usr/bin/env bash
# Structural + behavioural idle check for one ALB. Requires GNU date (Linux).
set -euo pipefail
LB_ARN="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/legacy-web/50dc6c495c0c9188"
LOOKBACK_DAYS=365 # chosen to cover quarterly and seasonal jobs; record this in the ticket
# 1. Structural: what sits behind the ALB?
TG_ARNS=$(aws elbv2 describe-target-groups --load-balancer-arn "$LB_ARN" \
--query 'TargetGroups[].TargetGroupArn' --output text)
[ -z "$TG_ARNS" ] && echo "No target groups attached"
for TG_ARN in $TG_ARNS; do
STATES=$(aws elbv2 describe-target-health --target-group-arn "$TG_ARN" \
--query 'TargetHealthDescriptions[].TargetHealth.State' --output text)
echo "$TG_ARN -> ${STATES:-<no registered targets>}"
done
# Empty target groups are not proof: listeners may serve redirects or fixed responses.
aws elbv2 describe-listeners --load-balancer-arn "$LB_ARN" \
--query 'Listeners[].[Port,DefaultActions[0].Type]' --output text
# 2. Behavioural: RequestCount over the lookback window.
# The CloudWatch dimension is the ARN suffix after 'loadbalancer/', e.g. app/legacy-web/50dc...
DIMENSION="${LB_ARN#*:loadbalancer/}"
# Daily sums keep a 365-day query under the 1,440-datapoint limit per call.
aws cloudwatch get-metric-statistics \
--namespace AWS/ApplicationELB --metric-name RequestCount \
--dimensions Name=LoadBalancer,Value="$DIMENSION" \
--start-time "$(date -u -d "${LOOKBACK_DAYS} days ago" +%Y-%m-%dT%H:%M:%SZ)" \
--end-time "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--period 86400 --statistics Sum \
--query 'Datapoints[].Sum' --output text \
| tr '\t' '\n' \
| awk -v d="$LOOKBACK_DAYS" '$1 > 0 {total += $1; days++}
END {printf "Requests in last %s days: %d (days with traffic: %d)\n", d, total, days}'
A bash script that checks an ALB's target groups and listener actions, then sums daily RequestCount from CloudWatch over an explicit 365-day lookback window.
Who owns this resource? Ownership checks before any cleanup
Detection tells you a resource looks unused. It doesn't tell you who will be paged if you're wrong. Run an enrichment step before anything reaches a deletion list.
Read the tags first. Look for owner, team, environment and cost-center, or whatever keys your organization enforces. A volume tagged environment=dr that sits unattached may be a disaster-recovery standby that is working as designed.
Check whether IaC manages it. CloudFormation adds an aws:cloudformation:stack-name tag to the resources it creates and propagates tags to. You can also pass a volume or load balancer ID to describe-stack-resources as the physical resource ID. For Terraform, search your state files for the resource ID. If you delete a managed resource by hand, the next apply will either recreate it or fail. Remove it through the owning code instead.
Trace inbound references to load balancers. Search Route 53, and any external DNS provider, for records that point at the load balancer's DNS name. Also check hardcoded hostnames in client configs and partner allowlists. Zero traffic over the lookback window doesn't help if a failover record routes to this load balancer only during an outage.
Untagged and unmatched resources go to a review queue, not to deletion. Post the queue to a channel, set a deadline for someone to claim each item, and record who looked at it.
The pipeline:
detect -> enrich/ownership -> review queue -> tag pending-deletion -> snapshot/export -> delete via IaC or console
Chasing owners is slow. A single small volume may cost less per month than the time an engineer spends tracking down who created it. Batch the review by account or team, and put the effort into the expensive items first.
#!/usr/bin/env bash
# Ownership enrichment for one EBS volume and one ALB/NLB before cleanup.
# Read-only: this script only reports. Deletion happens later in the pipeline.
set -euo pipefail
VOL_ID="vol-0abc123def4567890"
LB_ARN="arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/web-legacy/50dc6c495c0c9188"
TF_DIR="./infra/prod" # a Terraform root module you want to search
# 1. Tags: owner/team/environment/cost-center, plus aws:cloudformation:* if CFN made it.
aws ec2 describe-volumes --volume-ids "$VOL_ID" \
--query 'Volumes[0].Tags' --output table
# 2. CloudFormation membership by physical ID. A ValidationError means no stack owns it.
aws cloudformation describe-stack-resources --physical-resource-id "$VOL_ID" \
--query 'StackResources[0].StackName' --output text 2>/dev/null \
|| echo "no CloudFormation stack for $VOL_ID"
# 3. Terraform: search the remote/local state of this root module for the ID.
if (cd "$TF_DIR" && terraform state pull) | grep -q "$VOL_ID"; then
echo "$VOL_ID is in Terraform state under $TF_DIR: remove it in code, not by hand"
fi
# 4. Inbound DNS: find Route 53 records (alias or CNAME) that mention the LB's DNS name.
LB_DNS=$(aws elbv2 describe-load-balancers --load-balancer-arns "$LB_ARN" \
--query 'LoadBalancers[0].DNSName' --output text | tr '[:upper:]' '[:lower:]')
for zone in $(aws route53 list-hosted-zones --query 'HostedZones[].Id' --output text); do
aws route53 list-resource-record-sets --hosted-zone-id "${zone##*/}" \
--query "ResourceRecordSets[?contains(to_string(@), '${LB_DNS}')].[Name,Type,Failover]" \
--output text
done
# Any hit here, including a SECONDARY failover record, means the LB is not safe to delete.
# External DNS providers, client configs and partner allowlists still need a manual check.
A read-only bash check that prints a volume's tags, looks up CloudFormation and Terraform ownership, and lists Route 53 records pointing at a load balancer before anything is queued for deletion.
How do you make cleanup reversible?
Every deletion should have a way back for a fixed period. A cleanup that cannot be undone will stall the first time someone objects.
Before deletion
- Snapshot each EBS volume and tag the snapshot with the source volume ID, the original tags, and an expiry date. A snapshot lets you restore a volume if an owner appears late. It does not bring back the original volume ID, so anything that referenced that ID must be updated after a restore.
- Tag the resource as pending deletion with a date, for example
cleanup:delete-after=<date>, and notify the owner or team channel you identified in the previous step. The tag makes the intent visible to anyone who looks at the resource, even if they missed the message. - Export load balancer configuration. Save the output of
aws elbv2 describe-listenersanddescribe-rules, plus the target groups, certificates, and security groups. Rebuilding path rules and TLS settings from memory is where restores fail. - Delete IaC-managed resources through Terraform or CloudFormation. If you delete one manually, the state file still expects it to exist. The next apply may recreate it, or it may fail on dependencies that no longer exist. Either way, the team that owns the stack has to repair drift they did not cause.
Retention trade-off
Snapshots cost less per GB than volumes, but they are not free. Without an enforced expiry, such as a Data Lifecycle Manager policy or a scheduled job that reads the expiry tag, your safety net becomes the next category of orphans.
Sweep in the same pass
- Snapshots whose source volume no longer exists
- Unassociated Elastic IPs, which are billed while idle
- Target groups with no registered targets or no attached load balancer
#!/usr/bin/env bash
# Reversible prep: snapshot and tag a volume, then export ALB config before any delete.
set -euo pipefail
VOLUME_ID="vol-0abc123def4567890"
LB_ARN="arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/legacy-web/50dc6c495c0c9188"
EXPIRES=$(date -u -d '+30 days' +%F) # GNU date; the retention window
OUT="cleanup-backup/$(date -u +%F)"
mkdir -p "$OUT"
# Keep the volume's original tags so a restore can reapply them.
aws ec2 describe-volumes --volume-ids "$VOLUME_ID" \
--query 'Volumes[0].Tags' > "$OUT/$VOLUME_ID-tags.json"
# Snapshot with source ID and expiry so a lifecycle job can find and expire it.
SNAP_ID=$(aws ec2 create-snapshot --volume-id "$VOLUME_ID" \
--description "pre-cleanup backup of $VOLUME_ID" \
--tag-specifications "ResourceType=snapshot,Tags=[{Key=cleanup:source-volume,Value=$VOLUME_ID},{Key=cleanup:expires,Value=$EXPIRES}]" \
--query SnapshotId --output text)
aws ec2 wait snapshot-completed --snapshot-ids "$SNAP_ID"
# Mark intent on the volume itself; delete only after this date passes.
aws ec2 create-tags --resources "$VOLUME_ID" \
--tags "Key=cleanup:delete-after,Value=$EXPIRES"
# Export load balancer, listeners, rules and target groups for a rebuild.
aws elbv2 describe-load-balancers --load-balancer-arns "$LB_ARN" > "$OUT/lb.json"
aws elbv2 describe-listeners --load-balancer-arn "$LB_ARN" > "$OUT/listeners.json"
aws elbv2 describe-target-groups --load-balancer-arn "$LB_ARN" > "$OUT/target-groups.json"
for L in $(aws elbv2 describe-listeners --load-balancer-arn "$LB_ARN" \
--query 'Listeners[].ListenerArn' --output text); do
NAME=$(basename "$L")
aws elbv2 describe-rules --listener-arn "$L" > "$OUT/rules-$NAME.json"
aws elbv2 describe-listener-certificates --listener-arn "$L" > "$OUT/certs-$NAME.json"
done
echo "Snapshot $SNAP_ID expires $EXPIRES; LB config saved to $OUT"
This script snapshots an EBS volume with source and expiry tags, tags the volume as pending deletion, and exports the load balancer's listeners, rules, certificates and target groups so the cleanup can be reversed.
How much will cleanup actually save, and what does it cost in engineering time?
Illustrative estimate (assumed numbers, not a benchmark). Use per-GB prices from your own pricing page, because volume type and region change them.
- Unattached capacity found: 4,000 GB (assumed)
- Volume price: $0.08 per GB-month (assumed)
- Safety snapshots: 1,500 GB stored at $0.05 per GB-month (assumed)
Net monthly saving = (unattached GB × volume price) − (snapshot GB × snapshot price) = (4,000 × 0.08) − (1,500 × 0.05) = 320 − 75 = $245/month
Snapshots store written blocks, not provisioned size, so they are often smaller than the volume. Check the actual snapshot size before you rely on that. The saving grows once your retention policy expires those snapshots.
That $245 covers only the accounts and regions you scanned. Suppose a sweep covered two of twelve accounts and one of several enabled regions. The report still says "waste removed," and that reads as "waste solved." Publish coverage next to the dollar figure: accounts scanned out of total, and regions scanned out of enabled.
Engineering time is the other side of the ledger. Use payback months = (hours spent × loaded hourly cost) ÷ net monthly saving. Ownership chasing usually dominates the first sweep. Later sweeps cost far less because tagging gaps are already fixed.
| Cost driver | First manual sweep | Scheduled repeat sweep |
|---|---|---|
| Finding candidates | Ad hoc, per account | Runs automatically across the account list |
| Ownership chasing | High: untagged legacy resources | Low: only new untagged resources |
| Script maintenance | None yet | Ongoing: API changes, new accounts |
| Coverage confidence | Often partial | Measurable on every run |
Scheduled automation pays off when new orphans keep appearing at a steady rate. If they appear rarely, script maintenance can cost more than the waste it finds.
What are the alternatives to home-grown scripts, and when should you avoid automated deletion?
If you would rather not maintain scripts, AWS's own cost and recommendation tooling can surface low-utilization volumes and load balancers. Scripts give you full control and a transparent definition of "idle". In return, you have to handle every region, every account, API pagination, and credential rotation yourself. Native tools need less work, but their thresholds may not match yours. A load balancer that serves a quarterly batch job can look idle to them while being essential to you.
| Approach | Strength | Main risk |
|---|---|---|
| Home-grown script | Your own idle definition, auditable logic | Silent gaps when a region or account is missed |
| Native recommendations | Little setup, maintained by AWS | Generic thresholds, limited context |
| Fully automated deletion | No backlog builds up | One bad rule destroys data at scale |
| Report, then approve | A human checks context before anything irreversible | Reports go stale if nobody owns them |
Many teams automate detection and tagging but keep a human approval step before deletion. Detection is cheap to get wrong. Deletion is not.
Avoid aggressive cleanup in two situations:
- Large or poorly tagged estates. Ownership can't be inferred reliably, so "unknown" and "unused" become indistinguishable.
- DR and compliance resources. Standby volumes and failover load balancers are idle by design, and retention rules may require you to keep them.
Prevention reduces how often you have to clean up at all:
- Required tags. Enforce owner and purpose tags with tag policies or IaC linting, so orphans arrive already labelled with an owner.
- Deliberate delete-on-termination settings. Set this explicitly on instance volumes rather than inheriting defaults.
- Scheduled detection queries. Run them on a schedule and send each report directly to the tagged owner, not to a shared channel nobody reads.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to find unused aws resources, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.