github.phpd.cn/hashicorp/packer@v1.3.2/builder/openstack/step_source_image_info.go (about) 1 package openstack 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "github.com/gophercloud/gophercloud/openstack/imageservice/v2/images" 9 "github.com/gophercloud/gophercloud/pagination" 10 "github.com/hashicorp/packer/helper/multistep" 11 "github.com/hashicorp/packer/packer" 12 ) 13 14 type StepSourceImageInfo struct { 15 SourceImage string 16 SourceImageName string 17 SourceImageOpts images.ListOpts 18 SourceMostRecent bool 19 } 20 21 func (s *StepSourceImageInfo) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 22 config := state.Get("config").(*Config) 23 ui := state.Get("ui").(packer.Ui) 24 25 if s.SourceImage != "" { 26 state.Put("source_image", s.SourceImage) 27 28 return multistep.ActionContinue 29 } 30 31 client, err := config.imageV2Client() 32 33 if s.SourceImageName != "" { 34 s.SourceImageOpts = images.ListOpts{ 35 Name: s.SourceImageName, 36 } 37 } 38 39 log.Printf("Using Image Filters %v", s.SourceImageOpts) 40 image := &images.Image{} 41 err = images.List(client, s.SourceImageOpts).EachPage(func(page pagination.Page) (bool, error) { 42 i, err := images.ExtractImages(page) 43 if err != nil { 44 return false, err 45 } 46 47 switch len(i) { 48 case 1: 49 *image = i[0] 50 return false, nil 51 default: 52 if s.SourceMostRecent { 53 *image = i[0] 54 return false, nil 55 } 56 return false, fmt.Errorf( 57 "Your query returned more than one result. Please try a more specific search, or set most_recent to true. Search filters: %v", 58 s.SourceImageOpts) 59 } 60 }) 61 62 if err != nil { 63 err := fmt.Errorf("Error querying image: %s", err) 64 state.Put("error", err) 65 ui.Error(err.Error()) 66 return multistep.ActionHalt 67 } 68 69 if image.ID == "" { 70 err := fmt.Errorf("No image was found matching filters: %v", s.SourceImageOpts) 71 state.Put("error", err) 72 ui.Error(err.Error()) 73 return multistep.ActionHalt 74 } 75 76 ui.Message(fmt.Sprintf("Found Image ID: %s", image.ID)) 77 78 state.Put("source_image", image.ID) 79 return multistep.ActionContinue 80 } 81 82 func (s *StepSourceImageInfo) Cleanup(state multistep.StateBag) { 83 // No cleanup required for backout 84 }