我如何过滤过去一周中创建的ECR图像

发布于 2025-02-11 14:13:06 字数 850 浏览 2 评论 0原文

我使用的是Boto3 API,但如果具有更高的灵活性,则可以使用CLI开放。

client = boto3.session.Session(profile_name="prod").client("ecr", region_name="us-east-1")
response = client.describe_images(repositoryName=repository_name)

我过去要做的是上面做的,然后使用排序(响应[“ ImageTails”],key = lambda x:x [“ imagePushedat”])。但是,我只得到90个回复,想知道​​这是否是内部限制。

我看到有一个过滤器参数到describe_images,我试图通过执行以下操作来进行此错误:*** botocore.exceptions.paramvalidationerror :参数验证失败:过滤器中未知参数:“名称”,必须是:tagstatus未知参数之一:“值”,必须是:tagstatus

import datetime

date_filter = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d")
filter={"Name": "imagePushedAt", "Values": [date_filter+"*"]}
response = client.describe_images(repositoryName=repository_name, filter=filter)

关于如何过滤ECR映像的任何想法?

I am using the boto3 api, but open to using CLI if it gives any more flexibility.

client = boto3.session.Session(profile_name="prod").client("ecr", region_name="us-east-1")
response = client.describe_images(repositoryName=repository_name)

What I used to do is do above and just filter on date by using sorted(response["imageDetails"], key=lambda x: x["imagePushedAt"]). However, I am only getting 90 responses, and wondering if this is an internal limit.

I see that there is a filter argument to describe_images and I tried to do it by doing the following but get the error: *** botocore.exceptions.ParamValidationError: Parameter validation failed: Unknown parameter in filter: "Name", must be one of: tagStatus Unknown parameter in filter: "Values", must be one of: tagStatus

import datetime

date_filter = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d")
filter={"Name": "imagePushedAt", "Values": [date_filter+"*"]}
response = client.describe_images(repositoryName=repository_name, filter=filter)

Any thoughts on how to filter ECR images?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哀由 2025-02-18 14:13:06

当您查看(ecr.describe_images)的boto3文档时几件事:

  • 可选nextToken参数
  • 可选maxResults参数

nextToken用于迭代并获得其他结果。默认情况下,该功能限制为每批100个结果,尽管您可以将其推到1000个。如果(或何时)您的存储库中有超过1000张图像,则无法避免使用分页支持,las。

您可以使用client.get_paginator()方法(如果需要)。不过,下面我正在建立您已经开始的基础。

您在文档中注意到的另一件事是filter参数,这确实是相当有限的。

您提到找到90张图像,这表明您在上周前的前100张图像中有10张图像。

这是一种方法迭代所有图像,并检查其中每个图像的imagePushedat

#!/usr/bin/env python3

import boto3
import datetime

my_profile = "prod"
my_region  = "us-east-1"
my_repo    = <repository_name>

date_threshold = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d")
print("date threshold = {}".format(date_threshold))

batch = 0
image = 0
total = 0
client = boto3.session.Session(profile_name=my_profile).client("ecr", region_name=my_region)
nextToken = {}
while True:
    response = client.describe_images(repositoryName=my_repo, **nextToken)
    batch = batch + 1
    print("Batch {}:".format(batch))
    for entry in response["imageDetails"]:
        total = total + 1
        if entry["imagePushedAt"].strftime("%Y-%m-%d") >= date_threshold:
            image = image + 1
            print("  Image #{}/{}: {} pushed at {}".format(image, total, entry["imageDigest"], entry["imagePushedAt"]))
    if "nextToken" in response:
        nextToken = { "nextToken": response["nextToken"] }
    else:
        break

print("Done - {} batch(es), {} images match out of {}".format(batch, image, total))

如果您想一次批量超过默认值100,则您可以添加maxResults descript_images()呼叫中的参数。

希望有帮助!

When you look at the BOTO3 documentation for (ecr.describe_images)[https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ecr.html#ECR.Client.describe_images], you will see a few things:

  • An optional nextToken parameter
  • An optional maxResults parameter

The nextToken is used to iterate and get additional batches of results. The function is limited to 100 results per batch by default, though you can push that up to 1000 if you want. If (or when) you have more than 1000 images in your repository you can't avoid using the pagination support, alas.

You can use the client.get_paginator() approach, if you prefer. Below, I'm building on top of what you already started with, though.

The other thing you'll note in the documentation is the filter parameter, which is indeed fairly limited as you noticed.

You mentioned finding 90 images, which suggests that you had 10 images from before the last week, in those first 100 images.

Here's one way to iterate over all images, and checking the imagePushedAt of each of them:

#!/usr/bin/env python3

import boto3
import datetime

my_profile = "prod"
my_region  = "us-east-1"
my_repo    = <repository_name>

date_threshold = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d")
print("date threshold = {}".format(date_threshold))

batch = 0
image = 0
total = 0
client = boto3.session.Session(profile_name=my_profile).client("ecr", region_name=my_region)
nextToken = {}
while True:
    response = client.describe_images(repositoryName=my_repo, **nextToken)
    batch = batch + 1
    print("Batch {}:".format(batch))
    for entry in response["imageDetails"]:
        total = total + 1
        if entry["imagePushedAt"].strftime("%Y-%m-%d") >= date_threshold:
            image = image + 1
            print("  Image #{}/{}: {} pushed at {}".format(image, total, entry["imageDigest"], entry["imagePushedAt"]))
    if "nextToken" in response:
        nextToken = { "nextToken": response["nextToken"] }
    else:
        break

print("Done - {} batch(es), {} images match out of {}".format(batch, image, total))

If you would like to go in batches of more than the default 100 at a time, you can add that maxResults parameter in the describe_images() call.

Hope that helps!

百善笑为先 2025-02-18 14:13:06

我的python非常生锈,但我最近也有同样的要求。依靠chatgpt开始(因此在蛇案中混合)。我想要根据日期上传到回购的最后一个X ECR图像。 Boto3似乎在这里有一些差距(或者至少很明显我可以轻松地将这种过滤器指定为输入)。

def getLastEcrImages(ecrCli, repoName, numToFetch):
    response = ecrCli.describe_images(repositoryName=repoName)
    image_details = response['imageDetails']
    sorted_images = sorted(image_details, key=lambda k: k['imagePushedAt'], reverse=True)[:numToFetch]
    image_tags = [(image['imageTags'][0], image['imagePushedAt'].strftime('%Y-%m-%d %H:%M:%S')) for image in sorted_images]
    return image_tags

在我的情况下,我将最终的对象列表转换为一个简单的菜单,用户刚刚选择了一个。

My Python is pretty rusty but I had this same requirement recently. Leaned on ChatGPT a bit to get started (hence the mixed in snake case). I wanted the last x ECR images uploaded to a repo based on date. Boto3 seems to have a bit of a gap here (or at least it wasn't obvious that I could just easily specify such a filter as the input).

def getLastEcrImages(ecrCli, repoName, numToFetch):
    response = ecrCli.describe_images(repositoryName=repoName)
    image_details = response['imageDetails']
    sorted_images = sorted(image_details, key=lambda k: k['imagePushedAt'], reverse=True)[:numToFetch]
    image_tags = [(image['imageTags'][0], image['imagePushedAt'].strftime('%Y-%m-%d %H:%M:%S')) for image in sorted_images]
    return image_tags

In my case I converted the resulting list of objects to a simple menu where the user just picked one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文