Skip to content

Commit

Permalink
Skip AWS Managed AMIs
Browse files Browse the repository at this point in the history
  • Loading branch information
james03160927 committed Aug 25, 2023
1 parent 9f06d35 commit e6020b2
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
15 changes: 15 additions & 0 deletions aws/resources/ami.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package resources

import (
"strings"
"time"

awsgo "github.com/aws/aws-sdk-go/aws"
Expand Down Expand Up @@ -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,
Expand Down
46 changes: 46 additions & 0 deletions aws/resources/ami_test.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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()
Expand Down

0 comments on commit e6020b2

Please sign in to comment.