generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 86
Add support for cleaning ECR images in aws-janitor #235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ConnorJC3
wants to merge
1
commit into
kubernetes-sigs:master
Choose a base branch
from
ConnorJC3:add-ecr-janitor
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+256
−12
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,231 @@ | ||
| /* | ||
| Copyright 2025 The Kubernetes Authors. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package resources | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "slices" | ||
| "time" | ||
|
|
||
| "github.com/aws/aws-sdk-go-v2/aws" | ||
| "github.com/aws/aws-sdk-go-v2/service/ecr" | ||
| "github.com/aws/aws-sdk-go-v2/service/ecr/types" | ||
|
|
||
| "github.com/sirupsen/logrus" | ||
| ) | ||
|
|
||
| type ContainerImages struct{} | ||
|
|
||
| //nolint:gocognit // Just over the complexity threshold and splitting would make it less readable | ||
| func (ContainerImages) MarkAndSweep(opts Options, set *Set) error { | ||
| logger := logrus.WithField("options", opts) | ||
| if len(opts.CleanEcrRepositories) == 0 { | ||
| logger.Info("No ECR reposotories to clean provided, skipping ECR") | ||
| return nil | ||
| } | ||
|
|
||
| svc := ecr.NewFromConfig(*opts.Config, func(opt *ecr.Options) { | ||
| opt.Region = opts.Region | ||
| }) | ||
| inp := &ecr.DescribeRepositoriesInput{ | ||
| RegistryId: aws.String(opts.Account), | ||
| } | ||
|
|
||
| // DescribeImages requires a repository name, so we first must crawl all repositories | ||
| err := DescribeRepositoriesPages(svc, inp, func(repos *ecr.DescribeRepositoriesOutput) error { | ||
| for _, repo := range repos.Repositories { | ||
| if !slices.Contains(opts.CleanEcrRepositories, *repo.RepositoryName) { | ||
| continue | ||
| } | ||
|
|
||
| // BatchDeleteImage can only be called per-repo, so describe all the images in a repo, delete them, and repeat | ||
| var toDelete []*image | ||
| imageInp := &ecr.DescribeImagesInput{ | ||
| RegistryId: repo.RegistryId, | ||
| RepositoryName: repo.RepositoryName, | ||
| } | ||
|
|
||
| imagesErr := DescribeImagesPages(svc, imageInp, func(images *ecr.DescribeImagesOutput) error { | ||
| for _, ecrImage := range images.ImageDetails { | ||
| i := image{ | ||
| Registry: *ecrImage.RegistryId, | ||
| Region: opts.Region, | ||
| Repository: *ecrImage.RepositoryName, | ||
| Digest: *ecrImage.ImageDigest, | ||
| } | ||
|
|
||
| // ECR repos cannot have tags, so pass an empty object | ||
| if !set.Mark(opts, i, ecrImage.ImagePushedAt, Tags{}) { | ||
| continue | ||
| } | ||
| toDelete = append(toDelete, &i) | ||
| } | ||
| return nil | ||
| }, false /* continue on error */) | ||
| if imagesErr != nil { | ||
| logrus.Warningf("failed to get page: %v", imagesErr) | ||
| } | ||
|
|
||
| deleteReq := &ecr.BatchDeleteImageInput{ | ||
| RegistryId: repo.RegistryId, | ||
| RepositoryName: repo.RepositoryName, | ||
| ImageIds: []types.ImageIdentifier{}, | ||
| } | ||
| for n, image := range toDelete { | ||
| deleteReq.ImageIds = append(deleteReq.ImageIds, types.ImageIdentifier{ | ||
| ImageDigest: aws.String(image.Digest), | ||
| }) | ||
|
|
||
| // 100 images max: https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_BatchDeleteImage.html | ||
| // If we've reached 100 images, or this is the last item in the toDelete slice, make the call to the AWS API | ||
| if len(deleteReq.ImageIds) == 100 || n == len(toDelete)-1 { | ||
| logger.Warningf("%s: deleting %d images", *repo.RepositoryArn, len(deleteReq.ImageIds)) | ||
| if !opts.DryRun { | ||
| result, err := svc.BatchDeleteImage(context.TODO(), deleteReq) | ||
|
|
||
| if err != nil { | ||
| logger.Warningf("%s: delete API call failed: %v", *repo.RepositoryArn, err) | ||
| } else if len(result.Failures) > 0 { | ||
| logger.Warningf("%s: some images failed to delete: %T", *repo.RepositoryArn, result.Failures) | ||
ConnorJC3 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| // After making delete call, reset to an empty set of images | ||
| deleteReq.ImageIds = []types.ImageIdentifier{} | ||
| } | ||
| } | ||
| } | ||
| return nil | ||
| }, false /* continue on error */) | ||
| if err != nil { | ||
| logrus.Warningf("failed to get page: %v", err) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (ContainerImages) ListAll(opts Options) (*Set, error) { | ||
| set := NewSet(0) | ||
| if len(opts.CleanEcrRepositories) == 0 { | ||
| return set, nil | ||
| } | ||
| svc := ecr.NewFromConfig(*opts.Config, func(opt *ecr.Options) { | ||
| opt.Region = opts.Region | ||
| }) | ||
| inp := &ecr.DescribeRepositoriesInput{ | ||
| RegistryId: aws.String(opts.Account), | ||
| } | ||
|
|
||
| err := DescribeRepositoriesPages(svc, inp, func(repos *ecr.DescribeRepositoriesOutput) error { | ||
| for _, repo := range repos.Repositories { | ||
| if !slices.Contains(opts.CleanEcrRepositories, *repo.RepositoryName) { | ||
| continue | ||
| } | ||
|
|
||
| imageInp := &ecr.DescribeImagesInput{ | ||
| RegistryId: repo.RegistryId, | ||
| RepositoryName: repo.RepositoryName, | ||
| } | ||
|
|
||
| err := DescribeImagesPages(svc, imageInp, func(images *ecr.DescribeImagesOutput) error { | ||
| now := time.Now() | ||
| for _, ecrImage := range images.ImageDetails { | ||
| key := image{ | ||
| Registry: *ecrImage.RegistryId, | ||
| Region: opts.Region, | ||
| Repository: *ecrImage.RepositoryName, | ||
| Digest: *ecrImage.ImageDigest, | ||
| }.ResourceKey() | ||
|
|
||
| set.firstSeen[key] = now | ||
| } | ||
| return nil | ||
| }, true /* fail on error */) | ||
|
|
||
| if err != nil { | ||
| return err | ||
| } | ||
| } | ||
| return nil | ||
| }, true /* fail on error */) | ||
|
|
||
| return set, err | ||
| } | ||
|
|
||
| //nolint:nestif // Ifs are small and nesting cannot be reasonably avoided | ||
| func DescribeRepositoriesPages(svc *ecr.Client, input *ecr.DescribeRepositoriesInput, pageFunc func(repos *ecr.DescribeRepositoriesOutput) error, failOnError bool) error { | ||
| paginator := ecr.NewDescribeRepositoriesPaginator(svc, input) | ||
|
|
||
| for paginator.HasMorePages() { | ||
| page, err := paginator.NextPage(context.TODO()) | ||
| if err != nil { | ||
| logrus.Warningf("failed to get page: %v", err) | ||
| if failOnError { | ||
| return err | ||
| } | ||
| } else { | ||
| err = pageFunc(page) | ||
| if err != nil { | ||
| logrus.Warningf("pageFunc failed: %v", err) | ||
| if failOnError { | ||
| return err | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| //nolint:nestif // Ifs are small and nesting cannot be reasonably avoided | ||
| func DescribeImagesPages(svc *ecr.Client, input *ecr.DescribeImagesInput, pageFunc func(images *ecr.DescribeImagesOutput) error, failOnError bool) error { | ||
| paginator := ecr.NewDescribeImagesPaginator(svc, input) | ||
|
|
||
| for paginator.HasMorePages() { | ||
| page, err := paginator.NextPage(context.TODO()) | ||
| if err != nil { | ||
| logrus.Warningf("failed to get page: %v", err) | ||
| if failOnError { | ||
| return err | ||
| } | ||
| } else { | ||
| err = pageFunc(page) | ||
| if err != nil { | ||
| logrus.Warningf("pageFunc failed: %v", err) | ||
| if failOnError { | ||
| return err | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| type image struct { | ||
| Registry string | ||
| Region string | ||
| Repository string | ||
| Digest string | ||
| } | ||
|
|
||
| // Images don't have an ARN, only repositories do, so we use our own custom key format | ||
| func (i image) ARN() string { | ||
| return i.ResourceKey() | ||
| } | ||
|
|
||
| func (i image) ResourceKey() string { | ||
| return fmt.Sprintf("%s:%s/%s:%s", i.Registry, i.Region, i.Repository, i.Digest) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.