Write a Python script that cleans up ECR images older than 30 days, keeping the 10 newest.
AdvancedHands-onPython for DevOps
Answer
from datetime import datetime, timedelta, timezone
import boto3
ecr = boto3.client("ecr")
repo, keep, cutoff = "myapp", 10, datetime.now(timezone.utc) - timedelta(days=30)
images = []
for page in ecr.get_paginator("describe_images").paginate(repositoryName=repo):
images.extend(page["imageDetails"])
images.sort(key=lambda i: i["imagePushedAt"], reverse=True)
doomed = [{"imageDigest": i["imageDigest"]}
for i in images[keep:] if i["imagePushedAt"] < cutoff]
for chunk in (doomed[i:i + 100] for i in range(0, len(doomed), 100)):
ecr.batch_delete_image(repositoryName=repo, imageIds=chunk)
print(f"deleted {len(doomed)} images")
Key trick → batch_delete_image accepts at most 100 IDs per call, hence the chunking. Say in the interview that an ECR lifecycle policy does this natively; the script is for custom rules such as "never delete what's deployed".
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate