github.phpd.cn/hashicorp/packer@v1.3.2/builder/hcloud/step_create_snapshot.go (about)

     1  package hcloud
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/packer/helper/multistep"
     8  	"github.com/hashicorp/packer/packer"
     9  	"github.com/hetznercloud/hcloud-go/hcloud"
    10  )
    11  
    12  type stepCreateSnapshot struct{}
    13  
    14  func (s *stepCreateSnapshot) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    15  	client := state.Get("hcloudClient").(*hcloud.Client)
    16  	ui := state.Get("ui").(packer.Ui)
    17  	c := state.Get("config").(*Config)
    18  	serverID := state.Get("server_id").(int)
    19  
    20  	ui.Say("Creating snapshot ...")
    21  	ui.Say("This can take some time")
    22  	result, _, err := client.Server.CreateImage(context.TODO(), &hcloud.Server{ID: serverID}, &hcloud.ServerCreateImageOpts{
    23  		Type:        hcloud.ImageTypeSnapshot,
    24  		Description: hcloud.String(c.SnapshotName),
    25  	})
    26  	if err != nil {
    27  		err := fmt.Errorf("Error creating snapshot: %s", err)
    28  		state.Put("error", err)
    29  		ui.Error(err.Error())
    30  		return multistep.ActionHalt
    31  	}
    32  	state.Put("snapshot_id", result.Image.ID)
    33  	state.Put("snapshot_name", c.SnapshotName)
    34  	_, errCh := client.Action.WatchProgress(context.TODO(), result.Action)
    35  	for {
    36  		select {
    37  		case err1 := <-errCh:
    38  			if err1 == nil {
    39  				return multistep.ActionContinue
    40  			} else {
    41  				err := fmt.Errorf("Error creating snapshot: %s", err)
    42  				state.Put("error", err)
    43  				ui.Error(err.Error())
    44  				return multistep.ActionHalt
    45  			}
    46  
    47  		}
    48  	}
    49  }
    50  
    51  func (s *stepCreateSnapshot) Cleanup(state multistep.StateBag) {
    52  	// no cleanup
    53  }