Esempio 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
}
Esempio n. 2
0
// Snapshots is a wrapper for (*ec2.EC2).DescribeSnapshotsPages.
//
// If call succeeds but no snapshots were found, it returns non-nil
// *NotFoundError error.
func (c *Client) Snapshots() ([]*ec2.Snapshot, error) {
	var snapshots []*ec2.Snapshot
	var params ec2.DescribeSnapshotsInput
	if c.MaxResults != 0 {
		params.MaxResults = aws.Int64(c.MaxResults)
	}
	var page int
	err := c.EC2.DescribeSnapshotsPages(&params, func(resp *ec2.DescribeSnapshotsOutput, _ bool) bool {
		page++
		c.Log.Debug("received %d snapshots (page=%d)", len(resp.Snapshots), page)
		snapshots = append(snapshots, resp.Snapshots...)
		return true
	})
	if err != nil {
		return nil, awsError(err)
	}
	if len(snapshots) == 0 {
		return nil, newNotFoundError("Snapshot", errors.New("no snapshots found"))
	}
	return snapshots, nil
}