Tuesday 29 September 2020

Docker tagging using REST API

Adding additional tags to the image will be a common process in the CICD world, the additional tags would be something like the build number, test result, etc.,

When adding multiple tags it will be very heavy if we are doing the tagging locally and then pushing the tagged image to the server. So instead of doing like that, we can use the docker HTTP REST API which will be lighting fast tagging and will add the tag to the remote docker repository

Below is the example of tagging an image in a remote repository using python

def addAssociatedTag(imageName, tag, associatedTag, bearerToken):
    header = {'Authorization': ''}
    header['Authorization'] = 'Bearer ' + bearerToken
    header['Accept'] = 'application/vnd.docker.distribution.manifest.v2+json'
    res = requests.get(
            url="https://docker.io/v2/" + imageName + "/manifests/" + tag,
            headers=header)
    print('Retrieved the metifests status is ' + str(res.status_code))   
    # Add the associated tag by passing the same manifests
    header['Accept'] = '*'
    res = requests.request(
            "PUT",
            url="https://docker.io/v2/" + imageName + "/manifests/" + associatedTag,
            headers=header,
            data=res.content)      
    response_status = res.status_code
    print('Adding associated tag for ' + imageName + ':' + tag + ' with ' + imageName + ':' + associatedTag + ' is = ' + str(response_status))
    return response_status

In the above, the setting the 'Accept' header is very important while getting the manifests. If we do not set it to 'application/vnd.docker.distribution.manifest.v2+json'then we will have the default 'application/json' which will not be correct when we use the content for adding the associated tags and we will get below error

{
    "errors": [
        {
            "code": "MANIFEST_LAYER_UNKNOWN",
            "message": "blob unknown to registry",
            "detail": {
                "digest": "sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4"
            }
        }
    ]
}


Details about other docker REST APIs are in https://github.com/venkatesh-mohanram/continuous-learning/blob/master/docker/httpapiv2.md

No comments:

Post a Comment