packer-cn/post-processor/vsphere-template/step_create_folder.go

76 lines
1.8 KiB
Go
Raw Normal View History

package vsphere_template
2017-07-09 14:56:39 -04:00
import (
"context"
"fmt"
"path"
2017-07-09 14:56:39 -04:00
"github.com/hashicorp/packer/packer"
"github.com/mitchellh/multistep"
2017-07-27 16:55:47 -04:00
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/object"
2017-07-09 14:56:39 -04:00
)
2017-07-18 23:10:05 -04:00
type stepCreateFolder struct {
2017-07-09 14:56:39 -04:00
Folder string
}
2017-07-18 23:10:05 -04:00
func (s *stepCreateFolder) Run(state multistep.StateBag) multistep.StepAction {
2017-07-09 14:56:39 -04:00
ui := state.Get("ui").(packer.Ui)
2017-07-27 16:55:47 -04:00
cli := state.Get("client").(*govmomi.Client)
dcPath := state.Get("dcPath").(string)
2017-07-09 14:56:39 -04:00
if s.Folder != "" {
ui.Say("Creating or checking destination folders...")
base := path.Join(dcPath, "vm")
fullPath := path.Join(base, s.Folder)
2017-07-27 16:55:47 -04:00
si := object.NewSearchIndex(cli.Client)
2017-07-09 14:56:39 -04:00
var folders []string
var err error
2017-07-27 16:55:47 -04:00
var ref object.Reference
2017-07-18 23:10:05 -04:00
// 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
2017-07-27 16:55:47 -04:00
// The iteration ends when we find an existing path otherwise it throws error
2017-07-09 14:56:39 -04:00
for {
ref, err = si.FindByInventoryPath(context.Background(), fullPath)
2017-07-09 14:56:39 -04:00
if err != nil {
2017-07-27 16:55:47 -04:00
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if ref == nil {
dir, folder := path.Split(fullPath)
fullPath = path.Clean(dir)
2017-07-27 16:55:47 -04:00
if fullPath == dcPath {
err = fmt.Errorf("vSphere base path %s not found", base)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
2017-07-09 14:56:39 -04:00
}
folders = append(folders, folder)
2017-07-09 14:56:39 -04:00
} else {
break
}
}
2017-07-27 16:55:47 -04:00
root := ref.(*object.Folder)
2017-07-09 14:56:39 -04:00
for i := len(folders) - 1; i >= 0; i-- {
ui.Message(fmt.Sprintf("Creating folder: %v", folders[i]))
2017-07-18 23:10:05 -04:00
root, err = root.CreateFolder(context.Background(), folders[i])
if err != nil {
2017-07-09 14:56:39 -04:00
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
}
return multistep.ActionContinue
}
2017-07-18 23:10:05 -04:00
func (s *stepCreateFolder) Cleanup(multistep.StateBag) {}