github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/builder/oneandone/builder.go (about)

     1  package oneandone
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/hashicorp/packer/common"
     9  	"github.com/hashicorp/packer/helper/communicator"
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	"github.com/hashicorp/packer/packer"
    12  )
    13  
    14  const BuilderId = "packer.oneandone"
    15  
    16  type Builder struct {
    17  	config *Config
    18  	runner multistep.Runner
    19  }
    20  
    21  func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
    22  	c, warnings, errs := NewConfig(raws...)
    23  	if errs != nil {
    24  		return warnings, errs
    25  	}
    26  	b.config = c
    27  
    28  	return warnings, nil
    29  }
    30  
    31  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
    32  
    33  	state := new(multistep.BasicStateBag)
    34  
    35  	state.Put("config", b.config)
    36  	state.Put("hook", hook)
    37  	state.Put("ui", ui)
    38  
    39  	steps := []multistep.Step{
    40  		&StepCreateSSHKey{
    41  			Debug:        b.config.PackerDebug,
    42  			DebugKeyPath: fmt.Sprintf("oneandone_%s", b.config.SnapshotName),
    43  		},
    44  		new(stepCreateServer),
    45  		&communicator.StepConnect{
    46  			Config:    &b.config.Comm,
    47  			Host:      commHost,
    48  			SSHConfig: sshConfig,
    49  		},
    50  		&common.StepProvision{},
    51  		new(stepTakeSnapshot),
    52  	}
    53  
    54  	b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
    55  	b.runner.Run(state)
    56  
    57  	if rawErr, ok := state.GetOk("error"); ok {
    58  		return nil, rawErr.(error)
    59  	}
    60  
    61  	if temp, ok := state.GetOk("snapshot_name"); ok {
    62  		b.config.SnapshotName = temp.(string)
    63  	}
    64  
    65  	artifact := &Artifact{
    66  		snapshotName: b.config.SnapshotName,
    67  	}
    68  
    69  	if id, ok := state.GetOk("snapshot_id"); ok {
    70  		artifact.snapshotId = id.(string)
    71  	} else {
    72  		return nil, errors.New("Image creation has failed.")
    73  	}
    74  
    75  	return artifact, nil
    76  }
    77  
    78  func (b *Builder) Cancel() {
    79  	if b.runner != nil {
    80  		log.Println("Cancelling the step runner...")
    81  		b.runner.Cancel()
    82  	}
    83  }