Home > Enterprise >  trying to print output from an ECR image with python boto3
trying to print output from an ECR image with python boto3

Time:01-15

I am trying to print output from an ECR image with python boto3. I can get it to print out the imageDigest, but would like to add the imageTag. Can anyone think of a way to add the imageTag? Everyway I have tried has errored out.

import json
import boto3


def get_reponames():
    client = boto3.client('ecr')
    reponames = [repo['repositoryName'] for repo in client.describe_repositories()['repositories']]

    return reponames


def get_imageids(prepo):
    client = boto3.client('ecr')
    imageids = [img['imageDigest'] for img in client.list_images(repositoryName=prepo,)['imageIds']]

    return imageids


def lambda_handler(event, context):
    
    output = get_reponames()
    for rn in output:
        print(rn)
        outputii = get_imageids(rn)
        for ii in outputii:
            print(ii)
    
    return {
        'body': json.dumps("hello world")
    }

I'll post the output for list_images below. The above code works to display imageDigest, but I want to add imageTag too.

{
    'imageIds': [
        {
            'imageDigest': 'sha256:764f63476bdff6d83a09ba2a818f0d35757063724a9ac3ba5019c56f74ebf42a',
            'imageTag': 'precise',
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}

CodePudding user response:

Your get_imageids function only return imageDigest so you can not access it on lambda_handler function. You need to return imageTag as well to read it on lambda_handler

import json
import boto3


def get_reponames():
    client = boto3.client('ecr')
    reponames = [repo['repositoryName'] for repo in client.describe_repositories()['repositories']]

    return reponames


def get_imageids(prepo):
    client = boto3.client('ecr')
    imageids = [
        {"digest": img['imageDigest'], "tag": img.get('imageTag', None)} for img in
        client.list_images(repositoryName=prepo, )['imageIds']
    ]

    return imageids


def lambda_handler(event, context):
    output = get_reponames()
    for rn in output:
        print(rn)
        outputii = get_imageids(rn)
        for ii in outputii:
            print(f"digest : {ii['digest']}, tag: {ii['tag']}")

    return {
        'body': json.dumps("hello world")
    }

  • Related