packer-cn/clone/step_clone.go

84 lines
1.8 KiB
Go
Raw Normal View History

package clone
import (
2018-04-25 07:22:38 -04:00
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"fmt"
"github.com/jetbrains-infra/packer-builder-vsphere/driver"
2018-03-15 17:53:25 -04:00
"github.com/jetbrains-infra/packer-builder-vsphere/common"
2018-04-25 07:22:38 -04:00
"context"
)
type CloneConfig struct {
Template string `mapstructure:"template"`
2018-03-15 17:53:25 -04:00
common.VMConfig `mapstructure:",squash"`
LinkedClone bool `mapstructure:"linked_clone"`
}
func (c *CloneConfig) Prepare() []error {
2018-03-15 17:53:25 -04:00
errs := c.VMConfig.Prepare()
if c.Template == "" {
errs = append(errs, fmt.Errorf("Template name is required"))
}
return errs
}
2017-06-27 23:04:25 -04:00
type StepCloneVM struct {
2017-07-01 23:46:38 -04:00
config *CloneConfig
}
2018-04-25 07:22:38 -04:00
func (s *StepCloneVM) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
d := state.Get("driver").(*driver.Driver)
2017-07-01 23:46:38 -04:00
ui.Say("Cloning VM...")
2017-08-23 20:06:50 -04:00
template, err := d.FindVM(s.config.Template)
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
vm, err := template.Clone(&driver.CloneConfig{
Name: s.config.VMName,
Folder: s.config.Folder,
2018-03-15 17:53:25 -04:00
Cluster: s.config.Cluster,
Host: s.config.Host,
ResourcePool: s.config.ResourcePool,
Datastore: s.config.Datastore,
LinkedClone: s.config.LinkedClone,
})
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
state.Put("vm", vm)
return multistep.ActionContinue
}
func (s *StepCloneVM) Cleanup(state multistep.StateBag) {
_, cancelled := state.GetOk(multistep.StateCancelled)
_, halted := state.GetOk(multistep.StateHalted)
if !cancelled && !halted {
return
}
2017-08-23 20:06:50 -04:00
ui := state.Get("ui").(packer.Ui)
st := state.Get("vm")
if st == nil {
return
}
vm := st.(*driver.VirtualMachine)
2017-08-23 20:06:50 -04:00
ui.Say("Destroying VM...")
2017-08-23 20:06:50 -04:00
err := vm.Destroy()
if err != nil {
ui.Error(err.Error())
}
}