github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/oneandone/builder.go (about)

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