packer-cn/builder/oracle/classic/step_upload_image.go

96 lines
2.5 KiB
Go
Raw Normal View History

2018-10-20 17:11:11 -04:00
package classic
import (
"context"
"fmt"
"log"
2018-10-20 17:11:11 -04:00
"strings"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer-plugin-sdk/template/interpolate"
2018-10-20 17:11:11 -04:00
)
type stepUploadImage struct {
UploadImageCommand string
segmentPath string
2018-10-20 17:11:11 -04:00
}
type uploadCmdData struct {
Username string
Password string
AccountID string
ImageFile string
SegmentPath string
}
func (s *stepUploadImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
2018-10-20 17:11:11 -04:00
ui := state.Get("ui").(packer.Ui)
comm := state.Get("communicator").(packer.Communicator)
config := state.Get("config").(*Config)
runID := state.Get("run_id").(string)
imageFile := fmt.Sprintf("%s.tar.gz", config.ImageName)
state.Put("image_file", imageFile)
s.segmentPath = fmt.Sprintf("compute_images_segments/%s/_segment_/%s", imageFile, runID)
2018-10-20 17:11:11 -04:00
config.ctx.Data = uploadCmdData{
Username: config.Username,
Password: config.Password,
AccountID: config.IdentityDomain,
ImageFile: imageFile,
SegmentPath: s.segmentPath,
2018-10-20 17:11:11 -04:00
}
uploadImageCmd, err := interpolate.Render(s.UploadImageCommand, &config.ctx)
2018-10-20 17:11:11 -04:00
if err != nil {
err := fmt.Errorf("Error processing image upload command: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
command := fmt.Sprintf(`#!/bin/sh
set -e
mkdir /builder
mkfs -t ext3 /dev/xvdb
mount /dev/xvdb /builder
chown opc:opc /builder
cd /builder
dd if=/dev/xvdc bs=8M status=progress | cp --sparse=always /dev/stdin diskimage.raw
tar czSf ./diskimage.tar.gz ./diskimage.raw
rm diskimage.raw
%s`, uploadImageCmd)
dest := "/tmp/create-packer-diskimage.sh"
comm.Upload(dest, strings.NewReader(command), nil)
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("sudo /bin/sh %s", dest),
}
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
2018-10-20 17:11:11 -04:00
err = fmt.Errorf("Problem creating image`: %s", err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
if cmd.ExitStatus() != 0 {
err = fmt.Errorf("Create Disk Image command failed with exit code %d", cmd.ExitStatus())
2018-10-20 17:11:11 -04:00
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
2018-10-26 19:44:19 -04:00
ui.Say("Uploaded image to object storage.")
2018-10-20 17:11:11 -04:00
return multistep.ActionContinue
}
func (s *stepUploadImage) Cleanup(state multistep.StateBag) {
_, cancelled := state.GetOk(multistep.StateCancelled)
_, halted := state.GetOk(multistep.StateHalted)
if !cancelled && !halted {
return
}
log.Printf("Some segments may need to be manually cleaned at '%s'", s.segmentPath)
}