Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 65a94f9

Browse filesBrowse files
Create cleanup_old_ami_v3.py
1 parent 78dd06b commit 65a94f9
Copy full SHA for 65a94f9

1 file changed

+34Lines changed: 34 additions & 0 deletions

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
Expand file treeCollapse file tree
Open diff view settings
Collapse file
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import boto3
2+
from datetime import datetime
3+
from dateutil.parser import parse
4+
5+
# Set the tag key and value to use for filtering AMIs
6+
tag_key = "my-tag-key"
7+
tag_value = "my-tag-value"
8+
9+
# Set the maximum number of days to keep an AMI
10+
max_age_days = 2
11+
12+
# Connect to EC2 using the default profile
13+
client = boto3.client("ec2")
14+
15+
# Get a list of all the AMIs with the specified tag
16+
my_ami = client.describe_images(
17+
Owners=["self"],
18+
Filters=[
19+
{
20+
"Name": f"tag:{tag_key}",
21+
"Values": [tag_value]
22+
}
23+
]
24+
)["Images"]
25+
26+
# Loop through the list of AMIs and delete any that are older than the maximum age
27+
for ami in my_ami:
28+
creation_date = parse(ami["CreationDate"]).replace(tzinfo=None)
29+
ami_id = ami["ImageId"]
30+
age_in_days = (datetime.now() - creation_date).days
31+
print(f"Checking AMI {ami_id} with age {age_in_days} days")
32+
if age_in_days > max_age_days:
33+
client.deregister_image(ImageId=ami_id)
34+
print(f"Deleted AMI {ami_id} with age {age_in_days} days")

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.