summaryrefslogtreecommitdiff
path: root/vendor/github.com/mitchellh/packer/post-processor/vsphere-template/step_create_folder.go
blob: a0e64827538b83fac02c982dcd88d86f2ab2e9e5 (plain)
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
85
86
package vsphere_template

import (
	"context"
	"fmt"
	"path"

	"github.com/hashicorp/packer/packer"
	"github.com/mitchellh/multistep"
	"github.com/vmware/govmomi"
	"github.com/vmware/govmomi/object"
)

type stepCreateFolder struct {
	Folder string
}

func (s *stepCreateFolder) Run(state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)
	cli := state.Get("client").(*govmomi.Client)
	dcPath := state.Get("dcPath").(string)

	ui.Message("Creating or checking destination folders...")

	base := path.Join(dcPath, "vm")
	fullPath := path.Join(base, s.Folder)
	si := object.NewSearchIndex(cli.Client)

	var folders []string
	var err error
	var ref object.Reference

	// We iterate over the path starting with full path
	// If we don't find it, we save the folder name and continue with the previous path
	// The iteration ends when we find an existing path otherwise it throws error
	for {
		ref, err = si.FindByInventoryPath(context.Background(), fullPath)
		if err != nil {
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		if ref == nil {
			dir, folder := path.Split(fullPath)
			fullPath = path.Clean(dir)

			if fullPath == dcPath {
				err = fmt.Errorf("vSphere base path %s not found", base)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}

			folders = append(folders, folder)
		} else {
			break
		}
	}

	if root, ok := ref.(*object.Folder); ok {
		for i := len(folders) - 1; i >= 0; i-- {
			ui.Message(fmt.Sprintf("Creating folder: %v", folders[i]))

			root, err = root.CreateFolder(context.Background(), folders[i])
			if err != nil {
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}

			fullPath = path.Join(fullPath, folders[i])
		}
		root.SetInventoryPath(fullPath)
		state.Put("folder", root)
	} else {
		err = fmt.Errorf("folder not found: '%v'", ref)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	return multistep.ActionContinue
}

func (s *stepCreateFolder) Cleanup(multistep.StateBag) {}