Skip to content

Instantly share code, notes, and snippets.

@JokerQyou
Last active September 29, 2017 07:28
Show Gist options
  • Save JokerQyou/8aabf36ab8d1638e794ac57dcb154920 to your computer and use it in GitHub Desktop.
Save JokerQyou/8aabf36ab8d1638e794ac57dcb154920 to your computer and use it in GitHub Desktop.
Wtf is with these docker registry clients, I just want to delete an image.

Usage:

python delete_docker_image.py 192.168.2.1:5000/hello-world:latest --delete-layers
# coding: utf-8
import logging
import sys
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
chandler = logging.StreamHandler(stream=sys.stdout)
chandler.setLevel(logging.DEBUG)
logger.addHandler(chandler)
def delete_layer(host, name, sha):
result = requests.delete(
'{host}/v2/{name}/blobs/{sha}'.format(host=host, name=name, sha=sha),
headers={
'Accept': 'application/vnd.docker.distribution.manifest.v2+json',
}
)
logger.info(u'删除层 %s - %s: %s', name, sha, (u'成功' if result.status_code == 202 else u'失败'))
def delete_image_ref(host, name, ref_id):
result = requests.delete(
'{host}/v2/{name}/manifests/{ref_id}'.format(host=host, name=name, ref_id=ref_id),
headers={
'Accept': 'application/vnd.docker.distribution.manifest.v2+json',
}
)
logger.info(u'删除镜像 %s (%s): %s', name, ref_id, (u'成功' if result.status_code == 202 else u'失败'))
def delete_image(host, name, tag, delete_layers=False):
# Get layer list
layer_list_result = requests.get(
'{host}/v2/{name}/manifests/{tag}'.format(host=host, name=name, tag=tag),
headers={
'Accept': 'application/vnd.docker.distribution.manifest.v2+json',
}
)
layer_list = layer_list_result.json()['layers']
# Get image ref id
ref_id = layer_list_result.headers['Docker-Content-Digest']
# Delete image ref
delete_image_ref(host, name, ref_id)
if delete_layers:
# Delete each layer
for layer in layer_list:
delete_layer(host, name, layer['digest'])
if __name__ == '__main__':
image = sys.argv[-2]
delete_layers = sys.argv[-1] == '--delete-layers'
# Parse image
# 192.168.2.1:5000/image_name:image_tag
_left, tag = image.rsplit(':', 1)
host, name = _left.rsplit('/', 1)
host = 'http://{}'.format(host)
delete_image(host, name, tag, delete_layers=delete_layers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment