forked from gruntwork-io/cloud-nuke
/
snapshot.go
64 lines (51 loc) · 1.67 KB
/
snapshot.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
package aws
import (
"time"
awsgo "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/gruntwork-io/cloud-nuke/logging"
"github.com/gruntwork-io/gruntwork-cli/errors"
)
// Returns a formatted string of Snapshot snapshot ids
func getAllSnapshots(session *session.Session, region string, excludeAfter time.Time) ([]*string, error) {
svc := ec2.New(session)
params := &ec2.DescribeSnapshotsInput{
OwnerIds: []*string{awsgo.String("self")},
}
output, err := svc.DescribeSnapshots(params)
if err != nil {
return nil, errors.WithStackTrace(err)
}
var snapshotIds []*string
for _, snapshot := range output.Snapshots {
if excludeAfter.After(*snapshot.StartTime) {
snapshotIds = append(snapshotIds, snapshot.SnapshotId)
}
}
return snapshotIds, nil
}
// Deletes all Snapshots
func nukeAllSnapshots(session *session.Session, snapshotIds []*string) error {
svc := ec2.New(session)
if len(snapshotIds) == 0 {
logging.Logger.Infof("No Snapshots to nuke in region %s", *session.Config.Region)
return nil
}
logging.Logger.Infof("Deleting all Snapshots in region %s", *session.Config.Region)
var deletedSnapshotIDs []*string
for _, snapshotID := range snapshotIds {
params := &ec2.DeleteSnapshotInput{
SnapshotId: snapshotID,
}
_, err := svc.DeleteSnapshot(params)
if err != nil {
logging.Logger.Errorf("[Failed] %s", err)
} else {
deletedSnapshotIDs = append(deletedSnapshotIDs, snapshotID)
logging.Logger.Infof("Deleted Snapshot: %s", *snapshotID)
}
}
logging.Logger.Infof("[OK] %d Snapshot(s) terminated in %s", len(deletedSnapshotIDs), *session.Config.Region)
return nil
}