Skip to content

Instantly share code, notes, and snippets.

@Johannestegner
Last active November 12, 2020 13:56
Show Gist options
  • Save Johannestegner/af4754606b56fc7c5eeee21ee6717049 to your computer and use it in GitHub Desktop.
Save Johannestegner/af4754606b56fc7c5eeee21ee6717049 to your computer and use it in GitHub Desktop.
A small script to fetch latest pushed tags from docker hub.
#!/usr/bin/env python
# LICENSE: MIT
# (c) - Johannes Tegner
import json, sys, urllib.request
help_str = """Docker image tag fetcher.
Fetches latest tags from a public docker v2 registry api such as docker hub.
How to use:
python %cmd% image-name [registry-uri] [count]
Examples:
python %cmd% jitesoft/node-base https://registry.hub.docker.com/v2 3
# Returns the 3 latest tags of jitesoft/node-base on docker hub.
python %cmd% jitesoft/node-base
# Will do as the above, as default registry is docker hub, and default count is 3.
"""
if len(sys.argv) == 1:
print(help_str.replace('%cmd%', sys.argv[0]))
sys.exit(1)
if len(sys.argv) < 2:
sys.stderr.write('No image passed')
sys.exit(5)
registry = 'https://registry.hub.docker.com/v2'
if len(sys.argv) >= 3:
registry = str(sys.argv[2])
output_count = 3
if len(sys.argv) >= 4:
output_count = int(sys.argv[3])
def get_json (uri):
with urllib.request.urlopen(uri) as res:
return json.loads(res.read())
image = sys.argv[1]
base_uri = 'https://registry.hub.docker.com/v2/repositories/'
image_uri = base_uri + image + '/tags'
# How many tags are there?
count_data = get_json(image_uri)
count = count_data['count']
# Now fetch all the tags!
full_data = get_json(image_uri + '?page_size=' + str(count))
# With the full data we find all the amd64 tags (as I know that there is _always_ an amd64 tag).
tag_set = full_data['results'] # This is an array.
unique_shas = {}
for tag in tag_set:
for image in tag['images']:
if image['architecture'] == 'amd64':
unique_shas[ (image['digest']) ] = { "date": tag['tag_last_pushed'], "tags": [] }
for sha in unique_shas:
# For each sha, get all images that have it...
for tag in tag_set:
for image in tag['images']:
if image['architecture'] == 'amd64' and image['digest'] == sha:
unique_shas[sha]['tags'].append(tag['name'])
all_tags = unique_shas.values()
all_tags = sorted(all_tags, key=lambda tag: tag['date'], reverse=True)
for tag in all_tags[0:output_count]:
print(', '.join(tag['tags']))
@Johannestegner
Copy link
Author

Johannestegner commented Nov 12, 2020

Test it!

curl -SsL https://gist.githubusercontent.com/Johannestegner/af4754606b56fc7c5eeee21ee6717049/raw/latest_tags.py | python3 - jitesoft/node

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment