2015-06-12 14:05:15 -04:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
|
|
|
)
|
|
|
|
|
|
|
|
type StepDeregisterAMI struct {
|
2016-11-30 16:28:34 -05:00
|
|
|
ForceDeregister bool
|
|
|
|
ForceDeleteSnapshot bool
|
|
|
|
AMIName string
|
2015-06-12 14:05:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StepDeregisterAMI) Run(state multistep.StateBag) multistep.StepAction {
|
|
|
|
ec2conn := state.Get("ec2").(*ec2.EC2)
|
|
|
|
ui := state.Get("ui").(packer.Ui)
|
|
|
|
|
2016-11-30 16:28:34 -05:00
|
|
|
// Check for force deregister
|
2015-06-12 14:05:15 -04:00
|
|
|
if s.ForceDeregister {
|
|
|
|
resp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{
|
2016-11-01 17:08:04 -04:00
|
|
|
Filters: []*ec2.Filter{{
|
2015-06-12 14:05:15 -04:00
|
|
|
Name: aws.String("name"),
|
|
|
|
Values: []*string{aws.String(s.AMIName)},
|
|
|
|
}}})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error creating AMI: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
2016-11-30 16:28:34 -05:00
|
|
|
// Deregister image(s) by name
|
2015-06-12 14:05:15 -04:00
|
|
|
for _, i := range resp.Images {
|
|
|
|
_, err := ec2conn.DeregisterImage(&ec2.DeregisterImageInput{
|
2015-08-17 20:44:01 -04:00
|
|
|
ImageId: i.ImageId,
|
2015-06-12 14:05:15 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error deregistering existing AMI: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
2015-08-17 20:44:01 -04:00
|
|
|
ui.Say(fmt.Sprintf("Deregistered AMI %s, id: %s", s.AMIName, *i.ImageId))
|
2016-11-30 16:28:34 -05:00
|
|
|
|
|
|
|
// Delete snapshot(s) by image
|
|
|
|
if s.ForceDeleteSnapshot {
|
|
|
|
for _, b := range i.BlockDeviceMappings {
|
|
|
|
if b.Ebs != nil {
|
|
|
|
_, err := ec2conn.DeleteSnapshot(&ec2.DeleteSnapshotInput{
|
|
|
|
SnapshotId: b.Ebs.SnapshotId,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error deleting existing snapshot: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
ui.Say(fmt.Sprintf("Deleted snapshot: %s", *b.Ebs.SnapshotId))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-06-12 14:05:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StepDeregisterAMI) Cleanup(state multistep.StateBag) {
|
|
|
|
}
|