Skip to content

Commit

Permalink
refactor: use ui.Sayf and ui.Errorf
Browse files Browse the repository at this point in the history
Updated `packer-plugin-sdk` to v0.5.4.

Updated instances of the following to take advantage of changes in `packer-plugin-sdk` v0.5.3 and later.

- `ui.Say(fmt.Errorf(` to `ui.Sayf(`
- `ui.Error(fmt.Errorf(` to `ui.Errorf(`

Updates messaging to be more consistent, where applicable.

Signed-off-by: Ryan Johnson <[email protected]>
  • Loading branch information
tenthirtyam committed Jun 19, 2024
1 parent 09e95dc commit 228ec9e
Show file tree
Hide file tree
Showing 16 changed files with 144 additions and 170 deletions.
8 changes: 4 additions & 4 deletions builder/vsphere/common/step_boot_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (s *StepBootCommand) Run(ctx context.Context, state multistep.StateBag) mul

// Wait the for the vm to boot.
if int64(s.Config.BootWait) > 0 {
ui.Say(fmt.Sprintf("Waiting %s for boot...", s.Config.BootWait.String()))
ui.Sayf("Waiting %s for boot...", s.Config.BootWait.String())
select {
case <-time.After(s.Config.BootWait):
break
Expand All @@ -76,7 +76,7 @@ func (s *StepBootCommand) Run(ctx context.Context, state multistep.StateBag) mul
port,
s.VMName,
}
ui.Say(fmt.Sprintf("HTTP server is working at http://%v:%v/", ip, port))
ui.Sayf("HTTP server is working at http://%v:%v/", ip, port)
}

var keyAlt, keyCtrl, keyShift bool
Expand All @@ -103,8 +103,8 @@ func (s *StepBootCommand) Run(ctx context.Context, state multistep.StateBag) mul
})
if err != nil {
// retry once if error
ui.Error(fmt.Errorf("error typing a boot command (code, down) `%d, %t`: %w", code, down, err).Error())
ui.Say("trying key input again")
ui.Errorf("error typing a boot command (code, down) `%d, %t`: %v", code, down, err)
ui.Say("Trying key input again...")
time.Sleep(s.Config.BootGroupInterval)
_, err = vm.TypeOnKeyboard(driver.KeyInput{
Scancode: code,
Expand Down
6 changes: 3 additions & 3 deletions builder/vsphere/common/step_download.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (s *StepDownload) Run(ctx context.Context, state multistep.StateBag) multis
// If the local cache overwrite flag is set to true, delete the file and download the
// ISO file again.
if s.LocalCacheOverwrite {
ui.Say(fmt.Sprintf("Overwriting %s in local cache...", filename))
ui.Sayf("Overwriting %s in local cache...", filename)
// Delete the file from the local cache.
if err := os.Remove(targetPath); err != nil {
state.Put("error", fmt.Errorf("error overwriting file in local cache: %w", err))
Expand All @@ -102,15 +102,15 @@ func (s *StepDownload) Run(ctx context.Context, state multistep.StateBag) multis
if s.LocalCacheOverwrite {
log.Println("The local cache overwrite flag is set to true. Files will also be overwritten in the remote cache datastore to ensure consistency.")
}
ui.Say(fmt.Sprintf("Overwriting %s in remote cache %s...", filename, remoteDirectory))
ui.Sayf("Overwriting %s in remote cache %s...", filename, remoteDirectory)
// Delete the file from the remote cache datastore.
if err := ds.Delete(remotePath); err != nil {
state.Put("error", fmt.Errorf("error overwriting file in remote cache: %w", err))
return multistep.ActionHalt
}
} else {
// Skip the download step if the file exists in the local cache.
ui.Say(fmt.Sprintf("Skipping download, %s already exists in the local cache...", filename))
ui.Sayf("Skipping download, %s already exists in the local cache...", filename)
state.Put(s.ResultKey, targetPath)
state.Put("SourceImageURL", source)
return multistep.ActionContinue
Expand Down
24 changes: 12 additions & 12 deletions builder/vsphere/common/step_export.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
}

if len(unknown) > 0 {
ui.Error(fmt.Sprintf("unknown export options %s", strings.Join(unknown, ",")))
ui.Errorf("unknown export options %s", strings.Join(unknown, ","))
}
}

Expand All @@ -311,7 +311,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
file := i.File()

// Download the virtual machine image in Open Virtualization Format.
ui.Say(fmt.Sprintf("Downloading %s...", file.Path))
ui.Sayf("Downloading %s...", file.Path)
size, err := s.Download(ctx, lease, i)
if err != nil {
state.Put("error", err)
Expand All @@ -322,7 +322,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
file.Size = size

// Export the virtual machine image in Open Virtualization Format.
ui.Say(fmt.Sprintf("Exporting %s...", file.Path))
ui.Sayf("Exporting %s...", file.Path)
cdp.OvfFiles = append(cdp.OvfFiles, file)
}

Expand Down Expand Up @@ -351,7 +351,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
}

// Write the Open Virtualization Format descriptor.
ui.Say(fmt.Sprintf("Writing OVF descriptor %s...", s.Name+".ovf"))
ui.Sayf("Writing OVF descriptor %s...", s.Name+".ovf")
_, err = io.WriteString(w, desc.OvfDescriptor)
if err != nil {
state.Put("error", errors.Wrap(err, "unable to write ovf descriptor"))
Expand All @@ -369,7 +369,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
}

// Create a manifest file with the specified hash algorithm.
ui.Say(fmt.Sprintf("Writing %s manifest %s...", strings.ToUpper(s.Manifest), s.Name+".mf"))
ui.Sayf("Writing %s manifest %s...", strings.ToUpper(s.Manifest), s.Name+".mf")
s.addHash(filepath.Base(target), h)

file, err = os.Create(filepath.Join(s.OutputDir, s.Name+".mf"))
Expand All @@ -393,7 +393,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
// Check the export format to determine if the image should be converted.
switch s.Format {
case "", "ovf":
ui.Say(fmt.Sprintf("Completed export to Open Virtualization Format (OVF): %s", s.Name+".ovf"))
ui.Sayf("Completed export to Open Virtualization Format (OVF): %s", s.Name+".ovf")
return multistep.ActionContinue
case "ova":
ovftool := getOvftool()
Expand All @@ -403,7 +403,7 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
if s.Force {
_, err := os.Stat(ovaTarget)
if err == nil {
ui.Say(fmt.Sprintf("Force export enabled; removing existing OVA file: %s...", s.Name+".ova"))
ui.Sayf("Force export enabled; removing existing OVA file: %s...", s.Name+".ova")
err := os.Remove(ovaTarget)
if err != nil {
state.Put("error", errors.Wrap(err, "unable to remove existing ova file"))
Expand Down Expand Up @@ -438,25 +438,25 @@ func (s *StepExport) Run(ctx context.Context, state multistep.StateBag) multiste
// Removes the .vmdk files.
for _, file := range cdp.OvfFiles {
absPath := filepath.Join(s.OutputDir, file.Path)
ui.Say(fmt.Sprintf("Removing %s...", file.Path))
ui.Sayf("Removing %s...", file.Path)
err := os.Remove(absPath)
if err != nil {
ui.Say(fmt.Sprintf("Unable to remove file %s: %s", file.Path, err))
ui.Sayf("Unable to remove file %s: %s", file.Path, err)
}
}

// Removes the .mf, .ovf, .nvram, and .log files.
for _, ext := range []string{".mf", ".ovf", ".nvram", ".log"} {
filePath := filepath.Join(s.OutputDir, s.Name+ext)
ui.Say(fmt.Sprintf("Removing %s...", s.Name+ext))
ui.Sayf("Removing %s...", s.Name+ext)
err := os.Remove(filePath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
ui.Say(fmt.Sprintf("Unable to remove file %s: %s", s.Name+ext, err))
ui.Sayf("Unable to remove file %s: %s", s.Name+ext, err)
}
}

ui.Say("Completed removing intermediate files.")
ui.Say(fmt.Sprintf("Completed export to Open Virtualization Archive (OVA): %s", s.Name+".ova"))
ui.Sayf("Completed export to Open Virtualization Archive (OVA): %s", s.Name+".ova")
}
return multistep.ActionContinue
}
Expand Down
12 changes: 6 additions & 6 deletions builder/vsphere/common/step_import_to_content_library.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func (s *StepImportToContentLibrary) Run(_ context.Context, state multistep.Stat
vm := state.Get("vm").(*driver.VirtualMachineDriver)
var err error

ui.Say("Clear boot order...")
ui.Say("Clearing boot order...")
err = vm.SetBootOrder([]string{"-"})
if err != nil {
state.Put("error", err)
Expand All @@ -153,8 +153,8 @@ func (s *StepImportToContentLibrary) Run(_ context.Context, state multistep.Stat
if s.ContentLibConfig.Ovf {
vmTypeLabel = "VM OVF"
}
ui.Say(fmt.Sprintf("Importing %s template %s to Content Library '%s' as the item '%s' with the description '%s'...",
vmTypeLabel, s.ContentLibConfig.Name, s.ContentLibConfig.Library, s.ContentLibConfig.Name, s.ContentLibConfig.Description))
ui.Sayf("Importing %s template %s to Content Library '%s' as the item '%s' with the description '%s'...",
vmTypeLabel, s.ContentLibConfig.Name, s.ContentLibConfig.Library, s.ContentLibConfig.Name, s.ContentLibConfig.Description)

if s.ContentLibConfig.Ovf {
err = s.importOvfTemplate(vm)
Expand All @@ -163,7 +163,7 @@ func (s *StepImportToContentLibrary) Run(_ context.Context, state multistep.Stat
}

if err != nil {
ui.Error(fmt.Sprintf("Failed to import template %s: %s", s.ContentLibConfig.Name, err.Error()))
ui.Errorf("Failed to import template %s: %s", s.ContentLibConfig.Name, err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
Expand All @@ -176,7 +176,7 @@ func (s *StepImportToContentLibrary) Run(_ context.Context, state multistep.Stat
// For HCP Packer metadata, save the content library item UUID in state.
itemUuid, err := vm.FindContentLibraryItemUUID(s.ContentLibConfig.Library, s.ContentLibConfig.Name)
if err != nil {
ui.Error(fmt.Sprintf("Failed to get content library item uuid: %s", err.Error()))
ui.Errorf("Failed to get content library item uuid: %s", err.Error())
state.Put("error", err)
return multistep.ActionHalt
} else {
Expand All @@ -186,7 +186,7 @@ func (s *StepImportToContentLibrary) Run(_ context.Context, state multistep.Stat
// For HCP Packer metadata, save the content library datastore name in state.
datastores, err := vm.FindContentLibraryTemplateDatastoreName(s.ContentLibConfig.Library)
if err != nil {
ui.Error(fmt.Sprintf("Failed to get content library datastore name: %s", err.Error()))
ui.Errorf("Failed to get content library datastore name: %s", err.Error())
state.Put("error", err)
return multistep.ActionHalt
} else {
Expand Down
14 changes: 7 additions & 7 deletions builder/vsphere/common/step_remote_upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,23 +92,23 @@ func (s *StepRemoteUpload) uploadFile(path string, d driver.Driver, ui packersdk
// If the remote cache overwrite flag is set to true, delete the file and download the
// ISO file again.
if s.RemoteCacheOverwrite {
ui.Say(fmt.Sprintf("Overwriting %s in remote cache %s...", filename, remoteDirectory))
ui.Sayf("Overwriting %s in remote cache %s...", filename, remoteDirectory)
// Delete the file from the remote cache datastore.
if err := ds.Delete(remotePath); err != nil {
return "", fmt.Errorf("error overwriting file in remote cache: %w", err)
}
} else {
// Skip the download step if the remote cache overwrite flag is not set.
ui.Say(fmt.Sprintf("Skipping upload, %s already exists in remote cache...", fullRemotePath))
ui.Sayf("Skipping upload, %s already exists in remote cache...", fullRemotePath)
return fullRemotePath, nil
}
}

ui.Say(fmt.Sprintf("Uploading %s to %s...", filename, remoteDirectory))
ui.Sayf("Uploading %s to %s...", filename, remoteDirectory)

// Check if the remote cache directory exists. If not, create it.
if !ds.DirExists(remotePath) {
ui.Say(fmt.Sprintf("Remote cache directory does not exist; creating %s...", remoteDirectory))
ui.Sayf("Remote cache directory does not exist; creating %s...", remoteDirectory)
if err := ds.MakeDirectory(remoteDirectory); err != nil {
return "", err
}
Expand Down Expand Up @@ -141,17 +141,17 @@ func (s *StepRemoteUpload) Cleanup(state multistep.StateBag) {

ui := state.Get("ui").(packersdk.Ui)
d := state.Get("driver").(*driver.VCenterDriver)
ui.Say(fmt.Sprintf("Removing %s...", UploadedCDPath))
ui.Sayf("Removing %s...", UploadedCDPath)

ds, err := d.FindDatastore(s.Datastore, s.Host)
if err != nil {
ui.Say(fmt.Sprintf("Unable to find the remote cache datastore. Please remove the item manually: %s", err))
ui.Sayf("Unable to find the remote cache datastore. Please remove the item manually: %s", err)
return
}

err = ds.Delete(UploadedCDPath.(string))
if err != nil {
ui.Say(fmt.Sprintf("Unable to remove item from the remote cache. Please remove the item manually: %s", err))
ui.Sayf("Unable to remove item from the remote cache. Please remove the item manually: %s", err)
return
}
}
4 changes: 2 additions & 2 deletions builder/vsphere/common/step_remove_floppy.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (s *StepRemoveFloppy) Run(_ context.Context, state multistep.StateBag) mult
vm := state.Get("vm").(driver.VirtualMachine)
d := state.Get("driver").(driver.Driver)

ui.Say("Deleting Floppy drives...")
ui.Say("Deleting floppy drives...")
floppies, err := vm.FloppyDevices()
if err != nil {
state.Put("error", err)
Expand All @@ -33,7 +33,7 @@ func (s *StepRemoveFloppy) Run(_ context.Context, state multistep.StateBag) mult
}

if UploadedFloppyPath, ok := state.GetOk("uploaded_floppy_path"); ok {
ui.Say("Deleting Floppy image...")
ui.Say("Deleting floppy image...")
ds, err := d.FindDatastore(s.Datastore, s.Host)
if err != nil {
state.Put("error", err)
Expand Down
2 changes: 1 addition & 1 deletion builder/vsphere/common/step_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (s *StepRun) Cleanup(state multistep.StateBag) {
vm := state.Get("vm").(*driver.VirtualMachineDriver)

if s.Config.BootOrder == "" && s.SetOrder {
ui.Say("Clearing the boot order...")
ui.Say("Clearing boot order...")
if err := vm.SetBootOrder([]string{"-"}); err != nil {
state.Put("error", err)
return
Expand Down
6 changes: 3 additions & 3 deletions builder/vsphere/common/step_shutdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multis

if off, _ := vm.IsPoweredOff(); off {
// Probably power off initiated by last provisioner, though disable_shutdown is not set
ui.Say("VM is already powered off")
ui.Say("Virtual machine is already powered off.")
return multistep.ActionContinue
}

Expand All @@ -75,7 +75,7 @@ func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multis
} else if s.Config.Command != "" {
// Communicator is not needed unless shutdown_command is populated

ui.Say("Executing shutdown command...")
ui.Say("Running shutdown command...")
log.Printf("Shutdown command: %s", s.Config.Command)

var stdout, stderr bytes.Buffer
Expand All @@ -90,7 +90,7 @@ func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multis
return multistep.ActionHalt
}
} else {
ui.Say("Shutting down VM...")
ui.Say("Shutting down virtual machine...")

err := vm.StartShutdown()
if err != nil {
Expand Down
14 changes: 5 additions & 9 deletions builder/vsphere/common/step_ssh_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (s *StepSshKeyPair) Run(ctx context.Context, state multistep.StateBag) mult
Type: ssh.Rsa,
})
if err != nil {
state.Put("error", fmt.Errorf("error creating temporary keypair: %s", err))
state.Put("error", fmt.Errorf("error creating temporary key pair: %s", err))
return multistep.ActionHalt
}

Expand All @@ -86,17 +86,14 @@ func (s *StepSshKeyPair) Run(ctx context.Context, state multistep.StateBag) mult
vm := state.Get("vm").(*driver.VirtualMachineDriver)
err = vm.AddPublicKeys(ctx, string(s.Comm.SSHPublicKey))
if err != nil {
state.Put("error", fmt.Errorf("error saving temporary keypair in the vm: %s", err))
state.Put("error", fmt.Errorf("error saving temporary key pair in the vm: %s", err))
return multistep.ActionHalt
}

ui.Say("Created ephemeral SSH key pair for communicator")

// If we're in debug mode, output the private key to the working
// directory.
// If we're in debug mode, output the private key to the working directory.
if s.Debug {
ui.Message(fmt.Sprintf("Saving communicator private key for debug purposes: %s", s.DebugKeyPath))
// Write the key out
// Write the key to the file.
if err := os.WriteFile(s.DebugKeyPath, kp.PrivateKeyPemBlock, 0600); err != nil {
state.Put("error", fmt.Errorf("error saving debug key: %s", err))
return multistep.ActionHalt
Expand All @@ -110,8 +107,7 @@ func (s *StepSshKeyPair) Cleanup(state multistep.StateBag) {
if s.Debug {
if err := os.Remove(s.DebugKeyPath); err != nil {
ui := state.Get("ui").(packersdk.Ui)
ui.Error(fmt.Sprintf(
"Error removing debug key '%s': %s", s.DebugKeyPath, err))
ui.Errorf("Error removing the debug key pair from path '%s': %s", s.DebugKeyPath, err)
}
}
}
2 changes: 1 addition & 1 deletion builder/vsphere/common/step_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (s *StepConvertToTemplate) Run(_ context.Context, state multistep.StateBag)
vm := state.Get("vm").(*driver.VirtualMachineDriver)

if s.ConvertToTemplate {
ui.Say("Convert VM into template...")
ui.Say("Converting virtual machine to template...")
err := vm.ConvertToTemplate()
if err != nil {
state.Put("error", err)
Expand Down
2 changes: 1 addition & 1 deletion builder/vsphere/common/step_wait_for_ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (s *StepWaitForIp) Run(ctx context.Context, state multistep.StateBag) multi
return multistep.ActionHalt
}
state.Put("ip", ip)
ui.Say(fmt.Sprintf("IP address: %v", ip))
ui.Sayf("IP address: %v", ip)
return multistep.ActionContinue
case <-time.After(1 * time.Second):
if _, ok := state.GetOk(multistep.StateCancelled); ok {
Expand Down
8 changes: 4 additions & 4 deletions builder/vsphere/driver/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,21 +168,21 @@ func (d *VCenterDriver) PreCleanVM(ui packersdk.Ui, vmPath string, force bool, v
vm, err := d.FindVM(vmPath)
if err != nil {
if _, ok := err.(*find.NotFoundError); !ok {
return fmt.Errorf("error looking up old vm: %v", err)
return fmt.Errorf("error looking up existing virtual machine: %v", err)
}
}
if force && vm != nil {
ui.Say(fmt.Sprintf("the vm/template %s already exists, but deleting it due to -force flag", vmPath))
ui.Sayf("Removing the existing virtual machine at %s based on use of the '-force' option...", vmPath)

// power off just in case it is still on
_ = vm.PowerOff()

// covert to a vm if it is a template so it can be deleted
isTemplate, err := vm.IsTemplate()
if err != nil {
return fmt.Errorf("error determining if the vm is a template%s: %v", vmPath, err)
return fmt.Errorf("error determining if the virtual machine is a template%s: %v", vmPath, err)
} else if isTemplate {
ui.Say(fmt.Sprintf("%s is a template, attempting to convert it to a vm", vmPath))
ui.Sayf("Attempting to convert the template at %s to a virtual machine...", vmPath)
err := vm.ConvertToVirtualMachine(vsphereCluster, vsphereHost, vsphereResourcePool)
if err != nil {
return fmt.Errorf("error converting template back to virtual machine for cleanup %s: %v", vmPath, err)
Expand Down
2 changes: 1 addition & 1 deletion builder/vsphere/supervisor/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func (pl *PackerLogger) Info(msg string, args ...interface{}) {
}

func (pl *PackerLogger) Error(msg string, args ...interface{}) {
pl.UI.Error(fmt.Sprintf(msg, args...))
pl.UI.Errorf(msg, args...)
}

func CheckRequiredStates(state multistep.StateBag, keys ...string) error {
Expand Down
Loading

0 comments on commit 228ec9e

Please sign in to comment.