diff --git a/builder/hyperv/common/step_compact_disk.go b/builder/hyperv/common/step_compact_disk.go new file mode 100644 index 000000000..628703c7a --- /dev/null +++ b/builder/hyperv/common/step_compact_disk.go @@ -0,0 +1,50 @@ +package common + +import ( + "context" + "fmt" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepCompactDisk struct { + SkipCompaction bool +} + +// Run runs a compaction/optimisation process on attached VHD/VHDX disks +func (s *StepCompactDisk) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { + driver := state.Get("driver").(Driver) + ui := state.Get("ui").(packer.Ui) + + if s.SkipCompaction { + ui.Say("Skipping disk compaction...") + return multistep.ActionContinue + } + + // Get the tmp dir used to store the VMs files during the build process + var tmpPath string + if v, ok := state.GetOk("packerTempDir"); ok { + tmpPath = v.(string) + } + + ui.Say("Compacting disks...") + // CompactDisks searches for all VHD/VHDX files under the supplied + // path and runs the compacting process on each of them. If no disks + // are found under the supplied path this is treated as a 'soft' error + // and a warning message is printed. All other errors halt the build. + result, err := driver.CompactDisks(tmpPath) + if err != nil { + err := fmt.Errorf("Error compacting disks: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + // Report disk compaction results/warn if no disks were found + ui.Message(result) + + return multistep.ActionContinue +} + +// Cleanup does nothing +func (s *StepCompactDisk) Cleanup(state multistep.StateBag) {} diff --git a/builder/hyperv/iso/builder.go b/builder/hyperv/iso/builder.go index d01dd27d6..154161a83 100644 --- a/builder/hyperv/iso/builder.go +++ b/builder/hyperv/iso/builder.go @@ -466,6 +466,9 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe &hypervcommon.StepUnmountFloppyDrive{ Generation: b.config.Generation, }, + &hypervcommon.StepCompactDisk{ + SkipCompaction: b.config.SkipCompaction, + }, &hypervcommon.StepExportVm{ OutputDir: b.config.OutputDir, SkipExport: b.config.SkipExport, diff --git a/builder/hyperv/vmcx/builder.go b/builder/hyperv/vmcx/builder.go index 7e7bc748a..4a95a80dc 100644 --- a/builder/hyperv/vmcx/builder.go +++ b/builder/hyperv/vmcx/builder.go @@ -475,6 +475,9 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe &hypervcommon.StepUnmountFloppyDrive{ Generation: b.config.Generation, }, + &hypervcommon.StepCompactDisk{ + SkipCompaction: b.config.SkipCompaction, + }, &hypervcommon.StepExportVm{ OutputDir: b.config.OutputDir, SkipExport: b.config.SkipExport,