packer-cn/builder/googlecompute/step_create_image.go

70 lines
1.9 KiB
Go
Raw Normal View History

package googlecompute
import (
"context"
"errors"
"fmt"
"time"
2020-11-17 19:31:03 -05:00
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
)
2013-12-13 21:26:00 -05:00
// StepCreateImage represents a Packer build step that creates GCE machine
// images.
2013-12-13 21:26:00 -05:00
type StepCreateImage int
// Run executes the Packer build step that creates a GCE machine image.
//
// The image is created from the persistent disk used by the instance. The
// instance must be deleted and the disk retained before doing this step.
func (s *StepCreateImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packersdk.Ui)
2013-12-13 21:26:00 -05:00
if config.SkipCreateImage {
ui.Say("Skipping image creation...")
return multistep.ActionContinue
}
2016-09-23 08:21:43 -04:00
if config.PackerForce && config.imageAlreadyExists {
ui.Say("Deleting previous image...")
errCh := driver.DeleteImage(config.ImageName)
err := <-errCh
if err != nil {
err := fmt.Errorf("Error deleting image: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
2013-12-13 21:26:00 -05:00
ui.Say("Creating image...")
imageCh, errCh := driver.CreateImage(
config.ImageName, config.ImageDescription, config.ImageFamily, config.Zone,
config.DiskName, config.ImageLabels, config.ImageLicenses, config.ImageEncryptionKey.ComputeType(),
config.ImageStorageLocations)
var err error
select {
case err = <-errCh:
case <-time.After(config.StateTimeout):
err = errors.New("time out while waiting for image to register")
2013-12-13 21:26:00 -05:00
}
if err != nil {
err := fmt.Errorf("Error waiting for image: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
2013-12-13 21:26:00 -05:00
state.Put("image", <-imageCh)
return multistep.ActionContinue
}
// Cleanup.
2013-12-13 21:26:00 -05:00
func (s *StepCreateImage) Cleanup(state multistep.StateBag) {}