File: step_source_image_info.go

package info (click to toggle)
packer 1.3.4%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 8,324 kB
  • sloc: python: 619; sh: 557; makefile: 111
file content (84 lines) | stat: -rw-r--r-- 2,020 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package openstack

import (
	"context"
	"fmt"
	"log"

	"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
	"github.com/gophercloud/gophercloud/pagination"
	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

type StepSourceImageInfo struct {
	SourceImage      string
	SourceImageName  string
	SourceImageOpts  images.ListOpts
	SourceMostRecent bool
}

func (s *StepSourceImageInfo) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
	config := state.Get("config").(*Config)
	ui := state.Get("ui").(packer.Ui)

	if s.SourceImage != "" {
		state.Put("source_image", s.SourceImage)

		return multistep.ActionContinue
	}

	client, err := config.imageV2Client()

	if s.SourceImageName != "" {
		s.SourceImageOpts = images.ListOpts{
			Name: s.SourceImageName,
		}
	}

	log.Printf("Using Image Filters %v", s.SourceImageOpts)
	image := &images.Image{}
	err = images.List(client, s.SourceImageOpts).EachPage(func(page pagination.Page) (bool, error) {
		i, err := images.ExtractImages(page)
		if err != nil {
			return false, err
		}

		switch len(i) {
		case 1:
			*image = i[0]
			return false, nil
		default:
			if s.SourceMostRecent {
				*image = i[0]
				return false, nil
			}
			return false, fmt.Errorf(
				"Your query returned more than one result. Please try a more specific search, or set most_recent to true. Search filters: %v",
				s.SourceImageOpts)
		}
	})

	if err != nil {
		err := fmt.Errorf("Error querying image: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	if image.ID == "" {
		err := fmt.Errorf("No image was found matching filters: %v", s.SourceImageOpts)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Message(fmt.Sprintf("Found Image ID: %s", image.ID))

	state.Put("source_image", image.ID)
	return multistep.ActionContinue
}

func (s *StepSourceImageInfo) Cleanup(state multistep.StateBag) {
	// No cleanup required for backout
}