2019-11-01 17:17:10 -04:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2020-01-15 04:28:14 -05:00
|
|
|
"context"
|
2019-11-01 17:17:10 -04:00
|
|
|
"fmt"
|
|
|
|
"log"
|
2020-01-15 04:28:14 -05:00
|
|
|
"time"
|
2019-11-01 17:17:10 -04:00
|
|
|
|
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
2020-10-29 06:57:14 -04:00
|
|
|
"github.com/hashicorp/packer/builder/amazon/common/awserrors"
|
2020-11-12 17:44:02 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/retry"
|
2019-11-01 17:17:10 -04:00
|
|
|
)
|
|
|
|
|
2019-11-12 15:27:47 -05:00
|
|
|
// DestroyAMIs deregisters the AWS machine images in imageids from an active AWS account
|
2019-11-01 17:17:10 -04:00
|
|
|
func DestroyAMIs(imageids []*string, ec2conn *ec2.EC2) error {
|
|
|
|
resp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{
|
|
|
|
ImageIds: imageids,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error describing AMI: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Deregister image by name.
|
|
|
|
for _, i := range resp.Images {
|
2020-01-15 04:28:14 -05:00
|
|
|
|
|
|
|
ctx := context.TODO()
|
|
|
|
err = retry.Config{
|
|
|
|
Tries: 11,
|
|
|
|
ShouldRetry: func(err error) bool {
|
2020-10-29 06:57:14 -04:00
|
|
|
return awserrors.Matches(err, "UnauthorizedOperation", "")
|
2020-01-15 04:28:14 -05:00
|
|
|
},
|
|
|
|
RetryDelay: (&retry.Backoff{InitialBackoff: 200 * time.Millisecond, MaxBackoff: 30 * time.Second, Multiplier: 2}).Linear,
|
|
|
|
}.Run(ctx, func(ctx context.Context) error {
|
|
|
|
_, err := ec2conn.DeregisterImage(&ec2.DeregisterImageInput{
|
|
|
|
ImageId: i.ImageId,
|
|
|
|
})
|
|
|
|
return err
|
2019-11-01 17:17:10 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error deregistering existing AMI: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
log.Printf("Deregistered AMI id: %s", *i.ImageId)
|
|
|
|
|
|
|
|
// Delete snapshot(s) by image
|
|
|
|
for _, b := range i.BlockDeviceMappings {
|
|
|
|
if b.Ebs != nil && aws.StringValue(b.Ebs.SnapshotId) != "" {
|
2020-01-16 08:38:46 -05:00
|
|
|
|
|
|
|
err = retry.Config{
|
|
|
|
Tries: 11,
|
|
|
|
ShouldRetry: func(err error) bool {
|
2020-10-29 06:57:14 -04:00
|
|
|
return awserrors.Matches(err, "UnauthorizedOperation", "")
|
2020-01-16 08:38:46 -05:00
|
|
|
},
|
|
|
|
RetryDelay: (&retry.Backoff{InitialBackoff: 200 * time.Millisecond, MaxBackoff: 30 * time.Second, Multiplier: 2}).Linear,
|
|
|
|
}.Run(ctx, func(ctx context.Context) error {
|
|
|
|
_, err := ec2conn.DeleteSnapshot(&ec2.DeleteSnapshotInput{
|
|
|
|
SnapshotId: b.Ebs.SnapshotId,
|
|
|
|
})
|
|
|
|
return err
|
2019-11-01 17:17:10 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error deleting existing snapshot: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
log.Printf("Deleted snapshot: %s", *b.Ebs.SnapshotId)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|