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