【问题标题】:Boto3: How to get newest docker image from ECR?Boto3:如何从 ECR 获取最新的 docker 镜像?
【发布时间】:2022-03-30 10:23:49
【问题描述】:

我想使用 boto3 从 ECR 获取最新的 Docker 映像。目前我正在使用来自ecr 客户端的describe_images 方法,我得到了一个带有imageDetails 的字典

import boto3

registry_name = 'some_registry_name_in_aws'

client = boto3.client('ecr')

response = client.describe_images(
    repositoryName=registry_name,
)

有一个使用aws-clisolution,但文档没有描述任何可以传递给describe_images--query 参数。那么,如何使用 boto3 从 ECR 获取最新的 docker 镜像?

【问题讨论】:

    标签: python amazon-web-services docker boto3 amazon-ecr


    【解决方案1】:

    TL;DR

    您需要在describe_imagesJMESPath 表达式上使用分页器

    import boto3
    
    registry_name = 'some_registry_name_in_aws'
    jmespath_expression = 'sort_by(imageDetails, &to_string(imagePushedAt))[-1].imageTags'
    
    client = boto3.client('ecr')
    
    paginator = client.get_paginator('describe_images')
    
    iterator = client_paginator.paginate(repositoryName=registry_name)
    filter_iterator = iterator.search(jmespath_expression)
    result = list(filter_iterator)[0]
    result
    >>>
    'latest_image_tag'
    

    说明

    阅读 cli describe-images 文档后发现

    describe-images 是一个分页操作。

    boto3 可以通过get_paginator 方法为您提供对特定方法的分页操作。

    但是,如果您尝试直接应用 JMESPath 表达式 'sort_by(imageDetails,& imagePushedAt)[-1].imageTags[0]',则会收到错误消息,因为来自 imagePushedAt 的结果是 datetime.datetime 对象并且根据此 answer

    Boto3 Jmespath 实现不支持日期过滤

    所以,您需要将imagePushedAt 转换为字符串'sort_by(imageDetails, &to_string(imagePushedAt))[-1].imageTags'

    【讨论】:

    • 这很好用,但要注意排序是按页面应用的。对于包含超过 100 个图像的 ECR 注册表,您应该指定更大的 PageSize 以避免重复结果(每页一个):iterator = client_paginator.paginate(repositoryName=registry_name, PaginationConfig={'PageSize': 1000})
    猜你喜欢
    • 2018-04-02
    • 2022-11-18
    • 2016-11-11
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2022-10-14
    • 2021-04-08
    相关资源
    最近更新 更多