Skip to content

Instantly share code, notes, and snippets.

@lyuma
Created September 4, 2020 14:46
Show Gist options
  • Save lyuma/6459f943caf0de1a943ca625ee8422ff to your computer and use it in GitHub Desktop.
Save lyuma/6459f943caf0de1a943ca625ee8422ff to your computer and use it in GitHub Desktop.
Copies an image tag on DockerHub to another tag (such as latest)
#!/bin/bash
# Thanks to:
# https://dille.name/blog/2018/09/20/how-to-tag-docker-images-without-pulling-them/
# https://hub.docker.com/support/doc/how-do-i-authenticate-with-the-v2-api
# https://gist.github.com/alexanderilyin/8cf68f85b922a7f1757ae3a74640d48a
# for all the help.
# TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'"$(cat ~/.docker/config.json | cut -d\" -f8)"'", "password": "'"$(cat ~/.docker/config.json | cut -d\" -f12)"'"}' https://hub.docker.com/v2/users/login/ | cut -d\" -f4)
# "Authorization: JWT $TOKEN"
set -e
REPOSITORY="$1"
AUTH_DOMAIN="auth.docker.io"
AUTH_SERVICE="registry.docker.io"
AUTH_SCOPE="repository:$REPOSITORY:pull,push"
AUTH_OFFLINE_TOKEN="1"
AUTH_CLIENT_ID="shell"
# Requires a .docker/config.json file in your home directory.
TOKEN=$(curl -v -X GET -u $(cat ~/.docker/config.json | cut -d\" -f8):$(cat ~/.docker/config.json | cut -d\" -f12) "https://${AUTH_DOMAIN}/token?service=${AUTH_SERVICE}&scope=${AUTH_SCOPE}&offline_token=${AUTH_OFFLINE_TOKEN}&client_id=${AUTH_CLIENT_ID}" | cut -d\" -f4)
# TODO: jq -r '.token' , But jq isn't installed on my machine....
REGISTRY_NAME="registry-1.docker.io"
TAG_OLD="$2"
TAG_NEW="$3"
CONTENT_TYPE="application/vnd.docker.distribution.manifest.v2+json"
if [[ ! "$REPOSITORY" || ! "$TAG_OLD" || ! "$TAG_NEW" ]]; then
echo "Assumes hub.docker.com authentication" >&2
echo "Usage: $0 REPOSITORY TAG_OLD TAG_NEW " >&2
echo "EXMAPLE: $0 someuser/mypkg v1.0 latest " >&2
exit 1
fi
curl -v -s -H "Authorization: Bearer $TOKEN" -H "Accept: ${CONTENT_TYPE}" "https://${REGISTRY_NAME}/v2/${REPOSITORY}/tags/list"
MANIFEST=$(curl -s -H "Authorization: Bearer $TOKEN" -H "Accept: ${CONTENT_TYPE}" "https://${REGISTRY_NAME}/v2/${REPOSITORY}/manifests/${TAG_OLD}")
curl -s -H "Authorization: Bearer $TOKEN" -X PUT -H "Content-Type: ${CONTENT_TYPE}" -d "${MANIFEST}" "https://${REGISTRY_NAME}/v2/${REPOSITORY}/manifests/${TAG_NEW}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment