2018-10-17 06:15:47 -04:00
|
|
|
package hcloud
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
2020-11-17 19:31:03 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
|
2020-11-19 14:54:31 -05:00
|
|
|
packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
|
2018-10-17 06:15:47 -04:00
|
|
|
"github.com/hetznercloud/hcloud-go/hcloud"
|
|
|
|
)
|
|
|
|
|
|
|
|
type stepCreateSnapshot struct{}
|
|
|
|
|
2019-03-07 05:41:39 -05:00
|
|
|
func (s *stepCreateSnapshot) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
|
2018-10-17 06:15:47 -04:00
|
|
|
client := state.Get("hcloudClient").(*hcloud.Client)
|
2020-11-19 14:54:31 -05:00
|
|
|
ui := state.Get("ui").(packersdk.Ui)
|
2018-10-17 06:15:47 -04:00
|
|
|
c := state.Get("config").(*Config)
|
|
|
|
serverID := state.Get("server_id").(int)
|
|
|
|
|
|
|
|
ui.Say("Creating snapshot ...")
|
|
|
|
ui.Say("This can take some time")
|
2019-03-07 05:41:39 -05:00
|
|
|
result, _, err := client.Server.CreateImage(ctx, &hcloud.Server{ID: serverID}, &hcloud.ServerCreateImageOpts{
|
2018-10-17 06:15:47 -04:00
|
|
|
Type: hcloud.ImageTypeSnapshot,
|
2018-11-27 14:41:32 -05:00
|
|
|
Labels: c.SnapshotLabels,
|
2018-10-17 06:15:47 -04:00
|
|
|
Description: hcloud.String(c.SnapshotName),
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error creating snapshot: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
state.Put("snapshot_id", result.Image.ID)
|
|
|
|
state.Put("snapshot_name", c.SnapshotName)
|
2019-03-07 05:41:39 -05:00
|
|
|
_, errCh := client.Action.WatchProgress(ctx, result.Action)
|
2018-10-17 06:15:47 -04:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case err1 := <-errCh:
|
|
|
|
if err1 == nil {
|
|
|
|
return multistep.ActionContinue
|
|
|
|
} else {
|
|
|
|
err := fmt.Errorf("Error creating snapshot: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *stepCreateSnapshot) Cleanup(state multistep.StateBag) {
|
|
|
|
// no cleanup
|
|
|
|
}
|