Skip to content

Instantly share code, notes, and snippets.

@massenz
Created August 10, 2017 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save massenz/ff4775c0c56e8685c14881898c594c37 to your computer and use it in GitHub Desktop.
Save massenz/ff4775c0c56e8685c14881898c594c37 to your computer and use it in GitHub Desktop.
List all Docker images in a Shell-friendly format (optionally, JSON too)
#!/usr/bin/env python
#
# Created by M. Massenzio (c) 2017.
# The output of `docker images` is easy on the eye, but not
# terribly helpful if you want to pipe it into further shell
# commands; and using `cut` only gets you so far (in fact,
# not very far at all).
#
# This script emits the list of Docker images on your system
# in a format that is suitable for piping to further commands,
# (probably, with a `grep` in there, to pick only the one(s)
# you seek) and additional tooling.
#
# There are two optional arguments: `--json` and `--id` if you
# need, respectively, the output to be well-formed JSON, or
# just the images' IDs.
#
# Example:
# ./grep-images.py
#
# massenz/kafka:0.10.1.1
# cassandra:3.7
# cassandra:latest
# mongo:latest
# massenz/spark:2.0.0
# massenz/voldemort:1.10.14
# ...
import itertools
import json
import sh
import sys
is_json = '--json' in sys.argv
only_ids = '--id' in sys.argv
images_cmd = sh.docker('images')
lines = images_cmd.stdout.decode().splitlines()
images = list()
keys = lines[0].split()
keys.remove('IMAGE')
for img in lines[1:]:
if not img.startswith('<none>'):
if only_ids:
print(img.split()[2])
else:
images.append(dict(itertools.zip_longest(keys[:3], img.split()[:3])))
if not only_ids:
if is_json:
print(json.dumps(images, indent=4))
else:
for img in images:
print("{rep}:{tag}".format(rep=img['REPOSITORY'], tag=img['TAG']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment