Boto3:如何从 ECR 获取最新的 docker 镜像?

Mig*_*ejo 4 python amazon-web-services docker boto3 amazon-ecr

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

import boto3

registry_name = 'some_registry_name_in_aws'

client = boto3.client('ecr')

response = client.describe_images(
    repositoryName=registry_name,
)
Run Code Online (Sandbox Code Playgroud)

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

Mig*_*ejo 5

长话短说

您需要使用分页器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 = paginator.paginate(repositoryName=registry_name)
filter_iterator = iterator.search(jmespath_expression)
result = list(filter_iterator)[0]
result
>>>
'latest_image_tag'
Run Code Online (Sandbox Code Playgroud)

解释

阅读 cli描述图像文档后发现

描述图像是一个分页操作。

并且可以使用get_paginatorboto3方法为您提供特定方法的分页操作。

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

Boto3 Jmespath实现不支持日期过滤

所以,你需要转换imagePushedAt为 string 'sort_by(imageDetails, &to_string(imagePushedAt))[-1].imageTags'

  • 这种方法效果很好,但要注意排序是按页进行的。对于包含超过 100 个图像的 ECR 注册表,您应该指定较大的 PageSize 以避免重复结果(每页一个):`iterator = client_paginator.paginate(repositoryName=registry_name, PaginationConfig={'PageSize': 1000})` (4认同)