From e6020b219075d240fee9fc1f67c0ce75a6490a04 Mon Sep 17 00:00:00 2001 From: James Kwon Date: Thu, 24 Aug 2023 22:11:30 -0400 Subject: [PATCH] Skip AWS Managed AMIs --- aws/resources/ami.go | 15 +++++++++++++ aws/resources/ami_test.go | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/aws/resources/ami.go b/aws/resources/ami.go index ff84a1d2d..018976ce7 100644 --- a/aws/resources/ami.go +++ b/aws/resources/ami.go @@ -1,6 +1,7 @@ package resources import ( + "strings" "time" awsgo "github.com/aws/aws-sdk-go/aws" @@ -34,6 +35,20 @@ func (ami *AMIs) getAll(configObj config.Config) ([]*string, error) { return nil, err } + // Check if the image has a tag that indicates AWS management + isAWSManaged := false + for _, tag := range image.Tags { + if *tag.Key == "aws-managed" && *tag.Value == "true" { + isAWSManaged = true + break + } + } + + // Skip AWS managed images and images created by AWS Backup + if isAWSManaged || strings.HasPrefix(*image.Name, "AwsBackup") { + continue + } + if configObj.AMI.ShouldInclude(config.ResourceValue{ Name: image.Name, Time: &createdTime, diff --git a/aws/resources/ami_test.go b/aws/resources/ami_test.go index c42af9663..a9d944af2 100644 --- a/aws/resources/ami_test.go +++ b/aws/resources/ami_test.go @@ -1,6 +1,7 @@ package resources import ( + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/gruntwork-io/cloud-nuke/config" "github.com/gruntwork-io/cloud-nuke/telemetry" @@ -27,6 +28,51 @@ func (m mockedAMI) DeregisterImage(input *ec2.DeregisterImageInput) (*ec2.Deregi return &m.DeregisterImageOutput, nil } +func TestAMIGetAll_SkipAWSManaged(t *testing.T) { + telemetry.InitTelemetry("cloud-nuke", "") + t.Parallel() + + testName := "test-ami" + testImageId1 := "test-image-id1" + testImageId2 := "test-image-id2" + now := time.Now() + acm := AMIs{ + Client: mockedAMI{ + DescribeImagesOutput: ec2.DescribeImagesOutput{ + Images: []*ec2.Image{ + { + ImageId: &testImageId1, + Name: &testName, + CreationDate: awsgo.String(now.Format("2006-01-02T15:04:05.000Z")), + Tags: []*ec2.Tag{ + { + Key: aws.String("aws-managed"), + Value: aws.String("true"), + }, + }, + }, + { + ImageId: &testImageId2, + Name: aws.String("AwsBackup_Test"), + CreationDate: awsgo.String(now.Format("2006-01-02T15:04:05.000Z")), + Tags: []*ec2.Tag{ + { + Key: aws.String("aws-managed"), + Value: aws.String("true"), + }, + }, + }, + }, + }, + }, + } + + amis, err := acm.getAll(config.Config{}) + assert.NoError(t, err) + assert.NotContains(t, awsgo.StringValueSlice(amis), testImageId1) + assert.NotContains(t, awsgo.StringValueSlice(amis), testImageId2j) +} + func TestAMIGetAll(t *testing.T) { telemetry.InitTelemetry("cloud-nuke", "") t.Parallel()