github.com/sneal/packer@v0.5.2/builder/googlecompute/step_create_image.go (about)

     1  package googlecompute
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  
     7  	"github.com/mitchellh/multistep"
     8  	"github.com/mitchellh/packer/packer"
     9  )
    10  
    11  // StepCreateImage represents a Packer build step that creates GCE machine
    12  // images.
    13  type StepCreateImage int
    14  
    15  // Run executes the Packer build step that creates a GCE machine image.
    16  //
    17  // Currently the only way to create a GCE image is to run the gcimagebundle
    18  // command on the running GCE instance.
    19  func (s *StepCreateImage) Run(state multistep.StateBag) multistep.StepAction {
    20  	config := state.Get("config").(*Config)
    21  	comm := state.Get("communicator").(packer.Communicator)
    22  	ui := state.Get("ui").(packer.Ui)
    23  
    24  	sudoPrefix := ""
    25  	if config.SSHUsername != "root" {
    26  		sudoPrefix = "sudo "
    27  	}
    28  
    29  	imageFilename := fmt.Sprintf("%s.tar.gz", config.ImageName)
    30  	imageBundleCmd := "/usr/bin/gcimagebundle -d /dev/sda -o /tmp/"
    31  
    32  	ui.Say("Creating image...")
    33  	cmd := new(packer.RemoteCmd)
    34  	cmd.Command = fmt.Sprintf("%s%s --output_file_name %s",
    35  		sudoPrefix, imageBundleCmd, imageFilename)
    36  	err := cmd.StartWithUi(comm, ui)
    37  	if err == nil && cmd.ExitStatus != 0 {
    38  		err = fmt.Errorf(
    39  			"gcimagebundle exited with non-zero exit status: %d", cmd.ExitStatus)
    40  	}
    41  	if err != nil {
    42  		err := fmt.Errorf("Error creating image: %s", err)
    43  		state.Put("error", err)
    44  		ui.Error(err.Error())
    45  		return multistep.ActionHalt
    46  	}
    47  
    48  	state.Put("image_file_name", filepath.Join("/tmp", imageFilename))
    49  	return multistep.ActionContinue
    50  }
    51  
    52  func (s *StepCreateImage) Cleanup(state multistep.StateBag) {}