If you look after an AWS account that is a year or more old, a small scheduled AWS Lambda function can find the leftovers you still pay for and clean them up safely. Lambda runs your code for you, with no server to manage. These orphans build up without anyone noticing. Disks (EBS volumes) outlive the servers they belonged to, old backups (snapshots) stay after their database is gone, and a build pipeline keeps every machine image (AMI) it ever made. AWS Trusted Advisor, the account-review tool in AWS Support, flags some of them but never deletes anything. The setup below fills that gap with one Lambda that runs weekly. It tags each orphan first, sends a notice through Amazon SNS (Simple Notification Service), and deletes only what is still tagged 14 days later. Anything your team tags cleanup-exempt=true is left alone.
What’s happening
AWS does not garbage-collect for you. When you delete an EC2 instance, the attached EBS volumes are deleted by default — unless someone unchecked “Delete on Termination” at launch, which the AWS console used to default to false. The volume becomes an orphan. When you delete an RDS instance, the final snapshot is taken if you said so, but every previous manual snapshot is left behind. When a CI pipeline produces a new AMI on every build, the AMIs accumulate and their backing snapshots accumulate.
Trusted Advisor’s “Low Utilization” and “Idle Resources” checks catch some of this — unattached EBS volumes, idle ELBs, low-utilization RDS instances. The free tier has a subset; Business Support unlocks the full set. The check runs on a weekly cadence and produces a list. It does not delete anything.
The right architecture is:
- Trusted Advisor (where available) for the standard idle checks — unattached EBS, idle ELBs, low-utilization EC2 — exported via the Support API.
- A custom Lambda for what Trusted Advisor misses — orphaned snapshots, expired AMIs, dangling EIPs, idle NAT gateways, leftover CloudWatch alarms.
- A tag-based opt-out mechanism so the team can mark legitimate “looks idle but is intentional” resources with
cleanup-exempt=true. - A two-stage workflow — first run marks orphans with a
cleanup-mark-datetag and posts a Slack notification; second run, two weeks later, deletes anything still marked.
The two-stage gating is what makes the automation safe in practice. A one-shot “delete anything that looks orphaned” script will eventually delete a snapshot someone needed. The two-week window between mark and delete gives the team time to opt out.
How to verify
Before deploying the Lambda, run the queries manually on a representative account to size the cleanup.
# Unattached EBS volumes
aws ec2 describe-volumes \
--filters Name=status,Values=available \
--query 'Volumes[].[VolumeId,Size,CreateTime]' \
--output table
# Snapshots older than 90 days whose source volume no longer exists
aws ec2 describe-snapshots --owner-ids self \
--query 'Snapshots[?StartTime<=`'$(date -u -v-90d +%Y-%m-%d)'`].[SnapshotId,VolumeId,StartTime]' \
--output text | while read snap vol date; do
aws ec2 describe-volumes --volume-ids "$vol" >/dev/null 2>&1 \
|| echo "ORPHAN_SNAP: $snap (was $vol, $date)"
done
# AMIs older than 90 days not in use by any running instance
running_amis=$(aws ec2 describe-instances --query 'Reservations[].Instances[].ImageId' --output text | sort -u)
aws ec2 describe-images --owners self \
--query 'Images[?CreationDate<=`'$(date -u -v-90d +%Y-%m-%d)'`].[ImageId,Name,CreationDate]' \
--output text | while read ami name date; do
if ! echo "$running_amis" | grep -q "$ami"; then
echo "ORPHAN_AMI: $ami ($name, $date)"
fi
done
# Elastic IPs not attached to anything
aws ec2 describe-addresses \
--query 'Addresses[?!AssociationId][AllocationId,PublicIp]' \
--output table
# Load balancers with no targets registered
aws elbv2 describe-target-groups --query 'TargetGroups[].TargetGroupArn' --output text | \
while read tg; do
count=$(aws elbv2 describe-target-health --target-group-arn "$tg" --query 'length(TargetHealthDescriptions)')
[ "$count" = "0" ] && echo "EMPTY_TG: $tg"
done
The output of these queries on a typical 18-month-old account is sobering. Run them once before automating; the manual run sets the expectation for what the Lambda will find.
The fix
Deploy a single Lambda triggered by EventBridge on a weekly cron. The function handles all resource types in one pass.
# cleanup-orphans/lambda_function.py
import boto3
import os
from datetime import datetime, timedelta, timezone
ec2 = boto3.client('ec2')
elbv2 = boto3.client('elbv2')
cw = boto3.client('cloudwatch')
sns = boto3.client('sns')
MARK_TAG = 'cleanup-mark-date'
EXEMPT_TAG = 'cleanup-exempt'
GRACE_DAYS = 14
SNS_TOPIC = os.environ['SNS_TOPIC_ARN']
def is_exempt(tags):
return any(t.get('Key') == EXEMPT_TAG and t.get('Value', '').lower() == 'true' for t in (tags or []))
def find_mark(tags):
for t in (tags or []):
if t.get('Key') == MARK_TAG:
return datetime.fromisoformat(t['Value'])
return None
def mark_resource(resource_id, resource_type):
today = datetime.now(timezone.utc).strftime('%Y-%m-%d')
ec2.create_tags(Resources=[resource_id], Tags=[{'Key': MARK_TAG, 'Value': today}])
return f"MARKED {resource_type} {resource_id}"
def process_unattached_volumes():
actions = []
vols = ec2.describe_volumes(Filters=[{'Name': 'status', 'Values': ['available']}])['Volumes']
for v in vols:
if is_exempt(v.get('Tags')):
continue
mark = find_mark(v.get('Tags'))
if mark is None:
actions.append(mark_resource(v['VolumeId'], 'EBS'))
elif datetime.now(timezone.utc) - mark > timedelta(days=GRACE_DAYS):
ec2.delete_volume(VolumeId=v['VolumeId'])
actions.append(f"DELETED EBS {v['VolumeId']}")
return actions
def process_orphan_snapshots():
actions = []
cutoff = datetime.now(timezone.utc) - timedelta(days=90)
paginator = ec2.get_paginator('describe_snapshots')
pages = paginator.paginate(OwnerIds=['self'])
for page in pages:
for s in page['Snapshots']:
if s['StartTime'] > cutoff:
continue
if is_exempt(s.get('Tags')):
continue
try:
ec2.describe_volumes(VolumeIds=[s['VolumeId']])
continue # source volume still exists
except ec2.exceptions.ClientError:
pass
mark = find_mark(s.get('Tags'))
if mark is None:
actions.append(mark_resource(s['SnapshotId'], 'snapshot'))
elif datetime.now(timezone.utc) - mark > timedelta(days=GRACE_DAYS):
ec2.delete_snapshot(SnapshotId=s['SnapshotId'])
actions.append(f"DELETED snapshot {s['SnapshotId']}")
return actions
def process_orphan_amis():
actions = []
cutoff = datetime.now(timezone.utc) - timedelta(days=90)
instances = ec2.describe_instances()
used_amis = {i['ImageId'] for r in instances['Reservations'] for i in r['Instances']}
images = ec2.describe_images(Owners=['self'])['Images']
for img in images:
created = datetime.fromisoformat(img['CreationDate'].replace('Z', '+00:00'))
if created > cutoff:
continue
if img['ImageId'] in used_amis:
continue
if is_exempt(img.get('Tags')):
continue
mark = find_mark(img.get('Tags'))
if mark is None:
ec2.create_tags(Resources=[img['ImageId']], Tags=[{'Key': MARK_TAG, 'Value': datetime.now(timezone.utc).strftime('%Y-%m-%d')}])
actions.append(f"MARKED AMI {img['ImageId']}")
elif datetime.now(timezone.utc) - mark > timedelta(days=GRACE_DAYS):
ec2.deregister_image(ImageId=img['ImageId'])
# also delete the backing snapshots
for mapping in img.get('BlockDeviceMappings', []):
snap = mapping.get('Ebs', {}).get('SnapshotId')
if snap:
ec2.delete_snapshot(SnapshotId=snap)
actions.append(f"DEREGISTERED AMI {img['ImageId']} and deleted backing snapshots")
return actions
def process_unassociated_eips():
actions = []
addrs = ec2.describe_addresses()['Addresses']
for a in addrs:
if 'AssociationId' in a:
continue
if is_exempt(a.get('Tags')):
continue
mark = find_mark(a.get('Tags'))
if mark is None and 'AllocationId' in a:
ec2.create_tags(Resources=[a['AllocationId']], Tags=[{'Key': MARK_TAG, 'Value': datetime.now(timezone.utc).strftime('%Y-%m-%d')}])
actions.append(f"MARKED EIP {a.get('PublicIp')}")
elif mark is not None and datetime.now(timezone.utc) - mark > timedelta(days=GRACE_DAYS):
ec2.release_address(AllocationId=a['AllocationId'])
actions.append(f"RELEASED EIP {a.get('PublicIp')}")
return actions
def process_empty_target_groups():
actions = []
tgs = elbv2.describe_target_groups()['TargetGroups']
for tg in tgs:
health = elbv2.describe_target_health(TargetGroupArn=tg['TargetGroupArn'])
if len(health['TargetHealthDescriptions']) > 0:
continue
actions.append(f"EMPTY target group {tg['TargetGroupName']} — notify owner, do not auto-delete")
return actions
def lambda_handler(event, context):
actions = []
actions += process_unattached_volumes()
actions += process_orphan_snapshots()
actions += process_orphan_amis()
actions += process_unassociated_eips()
actions += process_empty_target_groups()
if actions:
sns.publish(
TopicArn=SNS_TOPIC,
Subject=f"Weekly orphan cleanup: {len(actions)} action(s)",
Message="\n".join(actions),
)
return { 'actions': len(actions) }
A few rules baked into this design:
Never auto-delete load balancers or target groups. ELBs are network entry points; deleting one breaks DNS in ways the cleanup script cannot anticipate. The Lambda reports empty target groups but does not act on them — that goes through a human.
The grace period is per-resource, not global. Each resource gets its own 14-day window starting from when it was first marked. A resource newly marked this week is not deleted next week.
SNS, not Slack, from the Lambda. SNS is the AWS-native pattern, fan-out to Slack happens in a downstream subscription (chat-bot, lambda-to-webhook, whatever the org uses). Keeps the cleanup Lambda free of Slack tokens.
Tag exemption is the escape hatch. Anyone on the team can tag a resource cleanup-exempt=true and the Lambda will leave it alone forever. Document it in the team runbook so people know how to keep something the script flagged.
Deploy the Lambda with an IAM role limited to the actions in the script — ec2:DescribeVolumes, ec2:DeleteVolume, ec2:CreateTags, etc. — never * on EC2. EventBridge fires it weekly. The first run produces a longer Slack message; by the fourth run the message is short and the bill has noticeably shifted.
Stack Harbor builds and operates this kind of housekeeping automation as part of Managed Cloud Ops. If your account is carrying a long tail of orphans and nobody has time to chase them, book a cleanup engagement.