github.com/vijayrajah/packer@v1.3.2/post-processor/vsphere-template/step_create_folder.go (about) 1 package vsphere_template 2 3 import ( 4 "context" 5 "fmt" 6 "path" 7 8 "github.com/hashicorp/packer/helper/multistep" 9 "github.com/hashicorp/packer/packer" 10 "github.com/vmware/govmomi" 11 "github.com/vmware/govmomi/object" 12 ) 13 14 type stepCreateFolder struct { 15 Folder string 16 } 17 18 func (s *stepCreateFolder) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 19 ui := state.Get("ui").(packer.Ui) 20 cli := state.Get("client").(*govmomi.Client) 21 dcPath := state.Get("dcPath").(string) 22 23 ui.Message("Creating or checking destination folders...") 24 25 base := path.Join(dcPath, "vm") 26 fullPath := path.Join(base, s.Folder) 27 si := object.NewSearchIndex(cli.Client) 28 29 var folders []string 30 var err error 31 var ref object.Reference 32 33 // We iterate over the path starting with full path 34 // If we don't find it, we save the folder name and continue with the previous path 35 // The iteration ends when we find an existing path otherwise it throws error 36 for { 37 ref, err = si.FindByInventoryPath(context.Background(), fullPath) 38 if err != nil { 39 state.Put("error", err) 40 ui.Error(err.Error()) 41 return multistep.ActionHalt 42 } 43 44 if ref == nil { 45 dir, folder := path.Split(fullPath) 46 fullPath = path.Clean(dir) 47 48 if fullPath == dcPath { 49 err = fmt.Errorf("vSphere base path %s not found", base) 50 state.Put("error", err) 51 ui.Error(err.Error()) 52 return multistep.ActionHalt 53 } 54 55 folders = append(folders, folder) 56 } else { 57 break 58 } 59 } 60 61 if root, ok := ref.(*object.Folder); ok { 62 for i := len(folders) - 1; i >= 0; i-- { 63 ui.Message(fmt.Sprintf("Creating folder: %v", folders[i])) 64 65 root, err = root.CreateFolder(context.Background(), folders[i]) 66 if err != nil { 67 state.Put("error", err) 68 ui.Error(err.Error()) 69 return multistep.ActionHalt 70 } 71 72 fullPath = path.Join(fullPath, folders[i]) 73 } 74 root.SetInventoryPath(fullPath) 75 state.Put("folder", root) 76 } else { 77 err = fmt.Errorf("folder not found: '%v'", ref) 78 state.Put("error", err) 79 ui.Error(err.Error()) 80 return multistep.ActionHalt 81 } 82 83 return multistep.ActionContinue 84 } 85 86 func (s *stepCreateFolder) Cleanup(multistep.StateBag) {}