Files

92 lines
2.4 KiB
Go
Raw Permalink Normal View History

2018-10-17 12:15:47 +02:00
package hcloud
import (
"context"
2018-10-17 12:15:47 +02:00
"fmt"
2019-12-17 11:25:56 +01:00
"github.com/hashicorp/hcl/v2/hcldec"
2020-12-17 13:29:25 -08:00
"github.com/hashicorp/packer-plugin-sdk/communicator"
"github.com/hashicorp/packer-plugin-sdk/multistep"
"github.com/hashicorp/packer-plugin-sdk/multistep/commonsteps"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
2018-10-17 12:15:47 +02:00
"github.com/hetznercloud/hcloud-go/hcloud"
)
// The unique id for the builder
const BuilderId = "hcloud.builder"
type Builder struct {
config Config
runner multistep.Runner
hcloudClient *hcloud.Client
}
var pluginVersion = "1.0.0"
2019-12-17 11:25:56 +01:00
func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() }
func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) {
2019-12-17 11:25:56 +01:00
warnings, errs := b.config.Prepare(raws...)
2018-10-17 12:15:47 +02:00
if errs != nil {
return nil, warnings, errs
2018-10-17 12:15:47 +02:00
}
return nil, nil, nil
2018-10-17 12:15:47 +02:00
}
func (b *Builder) Run(ctx context.Context, ui packersdk.Ui, hook packersdk.Hook) (packersdk.Artifact, error) {
2018-10-17 12:15:47 +02:00
opts := []hcloud.ClientOption{
hcloud.WithToken(b.config.HCloudToken),
hcloud.WithEndpoint(b.config.Endpoint),
hcloud.WithPollInterval(b.config.PollInterval),
hcloud.WithApplication("hcloud-packer", pluginVersion),
}
b.hcloudClient = hcloud.NewClient(opts...)
// Set up the state
state := new(multistep.BasicStateBag)
state.Put("config", &b.config)
state.Put("hcloudClient", b.hcloudClient)
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps
steps := []multistep.Step{
&stepCreateSSHKey{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("ssh_key_%s.pem", b.config.PackerBuildName),
},
2018-10-18 08:03:04 +02:00
&stepCreateServer{},
2018-10-17 12:15:47 +02:00
&communicator.StepConnect{
Config: &b.config.Comm,
Host: getServerIP,
SSHConfig: b.config.Comm.SSHConfigFunc(),
},
&commonsteps.StepProvision{},
&commonsteps.StepCleanupTempKeys{
2018-10-17 12:15:47 +02:00
Comm: &b.config.Comm,
},
2018-10-18 08:03:04 +02:00
&stepShutdownServer{},
&stepCreateSnapshot{},
2018-10-17 12:15:47 +02:00
}
// Run the steps
b.runner = commonsteps.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
2018-10-17 12:15:47 +02:00
// If there was an error, return that
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
if _, ok := state.GetOk("snapshot_name"); !ok {
return nil, nil
}
artifact := &Artifact{
snapshotName: state.Get("snapshot_name").(string),
snapshotId: state.Get("snapshot_id").(int),
hcloudClient: b.hcloudClient,
StateData: map[string]interface{}{"generated_data": state.Get("generated_data")},
2018-10-17 12:15:47 +02:00
}
return artifact, nil
}