Skip to content

Instantly share code, notes, and snippets.

@robv8r
Last active November 3, 2023 14:11
Show Gist options
  • Save robv8r/fa66f5e0fdf001f425fe9facf2db6d49 to your computer and use it in GitHub Desktop.
Save robv8r/fa66f5e0fdf001f425fe9facf2db6d49 to your computer and use it in GitHub Desktop.
List Docker Image Tags using bash
#!/usr/bin/env bash
# Gets all tags for a given docker image.
# Examples:
# retrieve all tags for a single library
# docker-tags "library/redis" | jq --raw-output '.[]'
# retrieve all tags for multiple libraries
# docker-tags "library/mongo" "library/redis" "microsoft/nanoserver" "microsoft/dotnet" | jq --raw-output '.[]'
# retrieve first 10 tags for multiple libraries
# docker-tags "library/mongo" "library/redis" "microsoft/nanoserver" "microsoft/dotnet" | jq --raw-output '.[][0:9]'
docker-tags() {
arr=("$@")
for item in "${arr[@]}";
do
tokenUri="https://auth.docker.io/token"
data=("service=registry.docker.io" "scope=repository:$item:pull")
token="$(curl --silent --get --data-urlencode ${data[0]} --data-urlencode ${data[1]} $tokenUri | jq --raw-output '.token')"
listUri="https://registry-1.docker.io/v2/$item/tags/list"
authz="Authorization: Bearer $token"
result="$(curl --silent --get -H "Accept: application/json" -H "Authorization: Bearer $token" $listUri | jq --raw-output '.')"
echo $result
done
}
@tripleee
Copy link

tripleee commented Jul 3, 2023

arr=("$@")
for item in "${arr[@]}";

This is just a clumsy and memory-squandering way to say for item in "$@";

images=($@)
for image in "${images[@]}"; do

This adds a quoting error (you want "$@", always, not a bare $@).

@dkebler
Copy link

dkebler commented Oct 4, 2023

Thx for this script. I used a bit of jq/sort/sed to get the version number of the "latest" tag like so. Given that an image can have many tags going way back one probably needs to know apriori which major version is the "latest" and supply that.

docker_latest_image() {
    image=$1
    major=${2:-1}
    tokenUri="https://auth.docker.io/token"
    data=("service=registry.docker.io" "scope=repository:$image:pull")
    token="$(curl --silent --get --data-urlencode ${data[0]} --data-urlencode ${data[1]} $tokenUri | jq --raw-output '.token')"
    listUri="https://registry-1.docker.io/v2/$image/tags/list"
    curl --silent --get -H "Accept: application/json" -H "Authorization: Bearer $token" $listUri \
    | jq --raw-output ".tags[] | select(. | startswith(\"$major.\"))" | sort -V | sed -n \$p
   }
docker_latest_image  library/alpine 3
3.18.4

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