Skip to content

Instantly share code, notes, and snippets.

@mthalman
Created October 27, 2022 16:17
Show Gist options
  • Save mthalman/210ecbf7d4f4a6e97a04f2c5e7dcc393 to your computer and use it in GitHub Desktop.
Save mthalman/210ecbf7d4f4a6e97a04f2c5e7dcc393 to your computer and use it in GitHub Desktop.
Check if image is built on latest base image

Linux

myImage="<insert-my-image-digest>"
baseImage="<insert-base-image-tag>"

function isBuiltOnLatestBaseImage() {
    echo "Pulling $myImage"
    docker pull $myImage

    local os=$(docker inspect $myImage | jq -r .[0].Os)
    local arch=$(docker inspect $myImage | jq -r .[0].Architecture)

    echo "Getting manifest of $baseImage"
    local baseTagManifest=$(docker manifest inspect $baseImage)
    local mediaType=$(echo $baseTagManifest | jq -r .mediaType)

    local basePullImage=""
    # If the .NET image is a multi-arch tag, we need to get the digest of the underlying image with the matching platform.
    if [[ $mediaType == *"list"* ]]; then
        echo "Resolving multi-arch tag $baseImage to matching platform"
        baseImageDigest=$(echo $baseTagManifest | jq -rc ".manifests[] | select(any(.platform; .os == \"$os\" and .architecture == \"$arch\" )) | .digest")
        
        if [[ -z $baseImageDigest ]]; then
            echo
            echo "ERROR: Could not find a matching platform for the given image." >&2
            return 1
        fi

        # If the image name contains a tag separater, replace the tag with the digest; otherwise, append the digest
        if [[ $baseImage == *":"* ]]; then
            basePullImage="${baseImage%:*}@${baseImageDigest}"
        else
            basePullImage="$baseImage@$baseImageDigest"
        fi
    else
        basePullImage=$baseImage
    fi

    echo "Pulling $basePullImage"
    docker pull $basePullImage
    local baseImageOs=$(docker inspect $basePullImage | jq -r .[0].Os)
    local baseImageArch=$(docker inspect $basePullImage | jq -r .[0].Architecture)

    if [[ $os != $baseImageOs || $arch != $baseImageArch ]]; then
        echo
        echo "ERROR: The given image is not built on the same platform as the .NET base image." >&2
        return 1
    fi

    echo "Comparing image layers"
    local lastLayer=$(docker inspect $basePullImage | jq -r .[0].RootFS.Layers[-1])
    result=$(if docker inspect $myImage | jq -r .[0].RootFS.Layers | grep -q $lastLayer; then echo "True"; else echo "False"; fi)
    echo
    echo "Result: $result"
}
isBuiltOnLatestBaseImage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment