Skip to content

Commit

Permalink
Cleanup VM in case of a failure (#120)
Browse files Browse the repository at this point in the history
* Cleanup VM in case of a failure

* Extracted cleanup in a separate step

* Improved message
  • Loading branch information
fkorotkov authored Mar 6, 2024
1 parent fb05173 commit 95c1764
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
4 changes: 3 additions & 1 deletion builder/tart/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ func (b *Builder) Prepare(raws ...interface{}) (generatedVars []string, warnings
}

func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
steps := []multistep.Step{}
steps := []multistep.Step{
new(stepCleanVM), // cleanup the VM if the build is cancelled or halted
}

if b.config.HTTPDir != "" || len(b.config.HTTPContent) != 0 {
if errs := b.config.HTTPConfig.Prepare(interpolate.NewContext()); len(errs) != 0 {
Expand Down
26 changes: 26 additions & 0 deletions builder/tart/step_cleanup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package tart

import (
"context"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
)

type stepCleanVM struct{}

func (s *stepCleanVM) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
return multistep.ActionContinue
}

func (s *stepCleanVM) Cleanup(state multistep.StateBag) {
config := state.Get("config").(*Config)
ui := state.Get("ui").(packersdk.Ui)

_, cancelled := state.GetOk(multistep.StateCancelled)
_, halted := state.GetOk(multistep.StateHalted)
if cancelled || halted {
ui.Say("Cleaning up virtual machine...")
cmdArgs := []string{"delete", config.VMName}
_, _ = TartExec(context.Background(), cmdArgs...)
}
}

0 comments on commit 95c1764

Please sign in to comment.