Created
June 6, 2018 14:30
-
-
Save andyhd/6bbd09a26764013d78bfc9a8ebf07512 to your computer and use it in GitHub Desktop.
Prune EBS Snapshots refactor
This file contains 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
package main | |
import ( | |
"fmt" | |
"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/aws/aws-sdk-go/service/sts" | |
"log" | |
"os" | |
"strconv" | |
"time" | |
) | |
var ( | |
clientSession = session.Must(session.NewSession()) | |
ec2Connection = ec2.New(clientSession) | |
stsConnection = sts.New(clientSession) | |
) | |
type tag struct { | |
key string | |
value string | |
} | |
func main() { | |
numDays := ensureInt(os.Getenv("DAYS_OLD")) | |
maxAge := time.Hour * 24 * time.Duration(numDays) | |
snapshots := getEbsSnapshots(tag{ | |
os.Getenv("SNAPSHOT_TAG_KEY"), | |
os.Getenv("SNAPSHOT_TAG_VALUE"), | |
}) | |
for _, snapshot := range snapshots { | |
if snapshot.StartTime.Add(maxAge).Before(time.Now()) { | |
prune(snapshot) | |
} | |
} | |
} | |
func ensureInt(s string) int { | |
value, err := strconv.Atoi(s) | |
if err != nil { | |
log.Panic(err) | |
} | |
return value | |
} | |
func getEbsSnapshots(tag tag) []*ec2.Snapshot { | |
params := ec2.DescribeSnapshotsInput{ | |
Filters: []*ec2.Filter{ | |
makeFilter("owner-id", getOwnerId()), | |
}, | |
} | |
if tag.key != "" { | |
params.Filters = append(params.Filters, makeFilter( | |
fmt.Sprintf("tag:%s", tag.key), | |
tag.value, | |
)) | |
} | |
output, err := ec2Connection.DescribeSnapshots(¶ms) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return output.Snapshots | |
} | |
func getOwnerId() string { | |
output, err := stsConnection.GetCallerIdentity(&sts.GetCallerIdentityInput{}) | |
if err != nil { | |
log.Panic(err) | |
} | |
return *output.Account | |
} | |
func makeFilter(name string, value string) *ec2.Filter { | |
return &ec2.Filter{ | |
Name: aws.String(name), | |
Values: []*string{aws.String(value)}, | |
} | |
} | |
func prune(snapshot *ec2.Snapshot) { | |
_, err := ec2Connection.DeleteSnapshot(&ec2.DeleteSnapshotInput{ | |
SnapshotId: aws.String(*snapshot.SnapshotId), | |
}) | |
if err != nil { | |
log.Printf("Error while pruning snapshot %s: %s", snapshot.SnapshotId, err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment