Skip to content

Instantly share code, notes, and snippets.

@jubel-han
Created June 24, 2019 09:59
Show Gist options
  • Save jubel-han/2275f985b74d21adc785690c07097e63 to your computer and use it in GitHub Desktop.
Save jubel-han/2275f985b74d21adc785690c07097e63 to your computer and use it in GitHub Desktop.
Inspecting if the docker image with specified tag exists from docker hub registry
#!/bin/bash
# INPUT:
# ENV Variables:
# DOCKER_USERNAME
# DOCKER_PASSWORD
# IMAGE_NAME
# IMAGE_TAG
# OUTPUT:
# MESSAGE:
# "true" Indicating the images with specified tag exists
# "false, error: xxxx" Indicating the images does not existing or retrieving image failed.
# Validating if the required envs already injected to the shell
[ -z ${DOCKER_USERNAME} ] && echo "false, ENV VAR 'DOCKER_USERNAME' does not exists" && exit
[ -z ${DOCKER_PASSWORD} ] && echo "false, ENV VAR 'DOCKER_PASSWORD' does not exists" && exit
[ -z ${IMAGE_NAME} ] && echo "false, ENV VAR 'IMAGE_NAME' does not exists" && exit
[ -z ${IMAGE_TAG} ] && echo "false, ENV VAR 'IMAGE_TAG' does not exists" && exit
data_json='{"username": "'${DOCKER_USERNAME}'", "password": "'${DOCKER_PASSWORD}'"}'
login_url="https://hub.docker.com/v2/users/login/"
image_url="https://hub.docker.com/v2/repositories/${IMAGE_NAME}/tags/${IMAGE_TAG}/"
# Getting and validating the JWT token
token_resp=$(curl -s -X POST -H "Content-Type: application/json" -d "${data_json}" $login_url)
token_key=$(echo $token_resp|awk -F '"' '{print $2}')
token_value=$(echo $token_resp|awk -F '"' '{print $4}')
[ ${token_key} != token ] && echo "false, error: Got the invalid login response ${token_resp}" && exit
# Retrieving and validating the image status
image_resp=$(curl -sI -H "Authentication: JWT $token_value" $image_url)
image_status=$(echo ${image_resp}|grep -c '200 OK'||:)
[ ${image_status} -eq 0 ] && echo "false, error: Image does not exists or getting image failed ${image_resp}" && exit
echo "true"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment