github.com/rothwerx/packer@v0.9.0/builder/amazon/common/step_pre_validate.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/aws/aws-sdk-go/aws"
     7  	"github.com/aws/aws-sdk-go/service/ec2"
     8  	"github.com/mitchellh/multistep"
     9  	"github.com/mitchellh/packer/packer"
    10  )
    11  
    12  // StepPreValidate provides an opportunity to pre-validate any configuration for
    13  // the build before actually doing any time consuming work
    14  //
    15  type StepPreValidate struct {
    16  	DestAmiName     string
    17  	ForceDeregister bool
    18  }
    19  
    20  func (s *StepPreValidate) Run(state multistep.StateBag) multistep.StepAction {
    21  	ui := state.Get("ui").(packer.Ui)
    22  	if s.ForceDeregister {
    23  		ui.Say("Force Deregister flag found, skipping prevalidating AMI Name")
    24  		return multistep.ActionContinue
    25  	}
    26  
    27  	ec2conn := state.Get("ec2").(*ec2.EC2)
    28  
    29  	ui.Say("Prevalidating AMI Name...")
    30  	resp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{
    31  		Filters: []*ec2.Filter{&ec2.Filter{
    32  			Name:   aws.String("name"),
    33  			Values: []*string{aws.String(s.DestAmiName)},
    34  		}}})
    35  
    36  	if err != nil {
    37  		err := fmt.Errorf("Error querying AMI: %s", err)
    38  		state.Put("error", err)
    39  		ui.Error(err.Error())
    40  		return multistep.ActionHalt
    41  	}
    42  
    43  	if len(resp.Images) > 0 {
    44  		err := fmt.Errorf("Error: name conflicts with an existing AMI: %s", *resp.Images[0].ImageId)
    45  		state.Put("error", err)
    46  		ui.Error(err.Error())
    47  		return multistep.ActionHalt
    48  	}
    49  
    50  	return multistep.ActionContinue
    51  }
    52  
    53  func (s *StepPreValidate) Cleanup(multistep.StateBag) {}