/
ami.go
102 lines (86 loc) · 2.48 KB
/
ami.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package resources
import (
"context"
awsgo "github.com/aws/aws-sdk-go/aws"
"github.com/gruntwork-io/cloud-nuke/util"
commonTelemetry "github.com/gruntwork-io/go-commons/telemetry"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/gruntwork-io/cloud-nuke/config"
"github.com/gruntwork-io/cloud-nuke/logging"
"github.com/gruntwork-io/cloud-nuke/report"
"github.com/gruntwork-io/cloud-nuke/telemetry"
"github.com/gruntwork-io/go-commons/errors"
)
// Returns a formatted string of AMI Image ids
func (ami *AMIs) getAll(c context.Context, configObj config.Config) ([]*string, error) {
params := &ec2.DescribeImagesInput{
Owners: []*string{awsgo.String("self")},
}
output, err := ami.Client.DescribeImages(params)
if err != nil {
return nil, errors.WithStackTrace(err)
}
var imageIds []*string
for _, image := range output.Images {
createdTime, err := util.ParseTimestamp(image.CreationDate)
if err != nil {
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,
}) {
imageIds = append(imageIds, image.ImageId)
}
}
return imageIds, nil
}
// Deletes all AMI
func (ami *AMIs) nukeAll(imageIds []*string) error {
if len(imageIds) == 0 {
logging.Debugf("No AMI to nuke in region %s", ami.Region)
return nil
}
logging.Debugf("Deleting all AMI in region %s", ami.Region)
deletedCount := 0
for _, imageID := range imageIds {
params := &ec2.DeregisterImageInput{
ImageId: imageID,
}
_, err := ami.Client.DeregisterImage(params)
// Record status of this resource
e := report.Entry{
Identifier: aws.StringValue(imageID),
ResourceType: "Amazon Machine Image (AMI)",
Error: err,
}
report.Record(e)
if err != nil {
logging.Debugf("[Failed] %s", err)
telemetry.TrackEvent(commonTelemetry.EventContext{
EventName: "Error Nuking AMI",
}, map[string]interface{}{
"region": ami.Region,
})
} else {
deletedCount++
logging.Debugf("Deleted AMI: %s", *imageID)
}
}
logging.Debugf("[OK] %d AMI(s) terminated in %s", deletedCount, ami.Region)
return nil
}