Skip to content

Instantly share code, notes, and snippets.

@af-inet
Last active February 22, 2019 16:30
Show Gist options
  • Select an option

  • Save af-inet/ad1a6dee9d5825350987eec935f5c8cf to your computer and use it in GitHub Desktop.

Select an option

Save af-inet/ad1a6dee9d5825350987eec935f5c8cf to your computer and use it in GitHub Desktop.
delete untagged images from ecr
#!/usr/bin/env python
#
# https://boto3.readthedocs.io/en/latest/reference/services/ecr.html
#
import argparse
import json
import boto3
client = boto3.client("ecr")
def parse_args():
parser = argparse.ArgumentParser(
description='deletes untagged images from ECR (dry run by default)')
parser.add_argument('name',
type=str,
help='ECR repository name')
parser.add_argument('-f', '--force',
action='store_true',
help='actually delete untagged the images from ECR')
return parser.parse_args()
def list_untagged_images(args):
response = client.list_images(
repositoryName=args.name,
maxResults=1000,
filter={
'tagStatus': 'UNTAGGED'
}
)
print(json.dumps(response, indent=2))
return response
def delete_images(args, imageIds):
response = client.batch_delete_image(
repositoryName=args.name,
imageIds=imageIds
)
print(json.dumps(response, indent=2))
def main():
args = parse_args()
if not args.force:
list_untagged_images(args)
print("[*] dry-run. run with [-f --force] to actually delete images.")
else:
response = list_untagged_images(args)
if len(response['imageIds']) > 0:
delete_images(args, response['imageIds'])
print("[*] deleted %s images." % len(response['imageIds']))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment