Skip to content

Instantly share code, notes, and snippets.

@ryangraham
Created February 12, 2021 19:34
Show Gist options
  • Save ryangraham/8147663979a40700163c335f41634465 to your computer and use it in GitHub Desktop.
Save ryangraham/8147663979a40700163c335f41634465 to your computer and use it in GitHub Desktop.
Purge all images from an ECR repository so it can be deleted cleanly
#!/usr/bin/env python3
import argparse
import boto3
def get_account_id():
sts = boto3.client('sts')
identity = sts.get_caller_identity()
account_id = identity["Account"]
return account_id
def get_image_ids(account_id, repo_name):
ecr = boto3.client('ecr')
response = ecr.describe_images(
registryId=account_id,
repositoryName=repo_name
)
image_details = response['imageDetails']
image_id = lambda image_detail: {'imageDigest': image_detail['imageDigest']}
image_ids = [image_id(image_detail) for image_detail in image_details]
return image_ids
def delete_images(account_id, repo_name, image_ids):
ecr = boto3.client('ecr')
response = ecr.batch_delete_image(
registryId=account_id,
repositoryName=repo_name,
imageIds=image_ids
)
print(response)
def main(repo_name):
account_id = get_account_id()
image_ids = get_image_ids(account_id, repo_name)
delete_images(account_id, repo_name, image_ids)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('repo_name')
args = parser.parse_args()
main(args.repo_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment