You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改脚本仅删除12个月以上的孤立EBS快照而非AMI快照

How to Delete Only Orphaned EBS Snapshots Older Than 12 Months

Got it, let's tweak your script so it only removes orphaned snapshots (those not associated with any AMI) that are over 12 months old—leaving snapshots linked to AMIs untouched.

The Problem with the Original Script

Your current code deletes every snapshot older than 365 days, regardless of whether it's tied to an AMI. This is risky because AMIs rely on their underlying snapshots to exist, and deleting those could break your AMIs entirely.

Revised Script

import boto
import datetime
from dateutil import parser
from boto import ec2

# Replace these with your actual AWS details
REGION = "REGION-NAME"
ACCOUNT_NUMBER = "16-DIGIT-AWS-ACCOUNT-NUMBER"

# Connect to your EC2 region
connection = ec2.connect_to_region(REGION)

# Step 1: Collect all snapshot IDs linked to your AMIs
ami_associated_snapshots = set()
all_your_amis = connection.get_all_images(owners=[ACCOUNT_NUMBER])

for ami in all_your_amis:
    # Loop through each block device mapping in the AMI
    for device_entry in ami.block_device_mapping.values():
        # Only add snapshots that are actually attached to the AMI
        if hasattr(device_entry, 'snapshot_id') and device_entry.snapshot_id:
            ami_associated_snapshots.add(device_entry.snapshot_id)

# Step 2: Calculate the 12-month cutoff date
twelve_months_ago = datetime.datetime.now() - datetime.timedelta(days=365)

# Step 3: Process snapshots - delete only orphaned & old ones
all_snapshots = connection.get_all_snapshots(owner=ACCOUNT_NUMBER)

for snapshot in all_snapshots:
    snapshot_creation_date = parser.parse(snapshot.start_time).date()
    # Check two critical conditions: snapshot is old enough, AND not linked to any AMI
    if snapshot_creation_date <= twelve_months_ago.date() and snapshot.id not in ami_associated_snapshots:
        print(f"Deleting orphaned snapshot: {snapshot.id} (Tags: {snapshot.tags})")
        # Uncomment the line below to actually delete (test with print statements first!)
        # connection.delete_snapshot(snapshot.id)
    else:
        # Optional: Add clarity on why we're skipping the snapshot
        if snapshot.id in ami_associated_snapshots:
            print(f"Skipping {snapshot.id} - linked to an existing AMI")
        else:
            print(f"Skipping {snapshot.id} - less than 12 months old")

print("Snapshot processing complete!")

Key Changes Explained

  • AMI Snapshot Collection: We first gather every snapshot ID that's part of your AMIs. This creates a "safe list" of snapshots we never want to delete.
  • Orphan Check: For each snapshot, we verify it's not in the safe list before considering deletion.
  • Safety Guard: I left the delete line commented out—run the script first to confirm which snapshots it targets, then uncomment once you're confident it won't break anything.
  • Clearer Logging: Added messages explaining why snapshots are skipped, so you can easily validate the script's behavior.

Quick Notes

  • Ensure your AWS credentials (via environment variables, ~/.boto config, or IAM role) have permissions for ec2:DescribeSnapshots, ec2:DescribeImages, and ec2:DeleteSnapshot.
  • If you work with shared AMIs, adjust the get_all_images call if needed—but the script currently only checks your own AMIs, which covers most common use cases.

内容的提问来源于stack exchange,提问作者user11503765

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:46:25