Ejemplo n.º 1
0
func PurgeSnapshots(svc *ec2.EC2) error {

	dsi := ec2.DescribeSnapshotsInput{}

	filter := &ec2.Filter{}
	filterName := "tag:" + PurgeAllowKey
	filter.Name = &filterName
	value := "true"
	filter.Values = []*string{&value}
	dsi.Filters = append(dsi.Filters, filter)

	dso, err := svc.DescribeSnapshots(&dsi)
	if err != nil {
		return fmt.Errorf("describeSnapshots error, %s", err)
	}

	purgeCount := 0
	for _, snapshot := range dso.Snapshots {
		var paVal string
		var found bool

		if paVal, found = getTagValue(PurgeAfterKey, snapshot.Tags); !found {
			log.Printf("snapshot ID %s has tag '%s' but does not have a '%s' tag. Skipping purge...", *snapshot.SnapshotId, PurgeAllowKey, PurgeAfterKey)
			continue
		}

		pa, err := time.Parse(PurgeAfterFormat, paVal)
		if err != nil {
			return err
		}

		if pa.Before(time.Now()) {
			deli := ec2.DeleteSnapshotInput{}
			deli.SnapshotId = snapshot.SnapshotId

			_, err := svc.DeleteSnapshot(&deli)
			if err != nil {
				return fmt.Errorf("error purging Snapshot ID %s, err %s", *snapshot.SnapshotId, err)
			}
			log.Printf("snapshot ID '%s' purged, size %d GiB\n", *snapshot.SnapshotId, *snapshot.VolumeSize)
			purgeCount++
		}
	}

	log.Printf("%d snapshots purged\n", purgeCount)

	return nil
}
func deleteOldSnapshots(svc *ec2.EC2, days int) {
	output, err := svc.DescribeSnapshots(&ec2.DescribeSnapshotsInput{Filters: []*ec2.Filter{
		{
			Name: aws.String("description"),
			Values: []*string{
				aws.String(descriptionPrefix + "-*"),
			},
		},
	}})
	if err != nil {
		fmt.Printf("%T(%v)", err, err)
		os.Exit(-1)
	}
	time := time.Now().AddDate(0, 0, -1*days)
	for _, snapshot := range output.Snapshots {
		if snapshot.StartTime.Before(time) {
			svc.DeleteSnapshot(&ec2.DeleteSnapshotInput{SnapshotId: snapshot.SnapshotId})
		}
	}
}