packer-cn/post-processor/vsphere-template/post-processor.go

154 lines
4.8 KiB
Go
Raw Normal View History

//go:generate mapstructure-to-hcl2 -type Config
package vsphere_template
2017-07-09 14:12:37 -04:00
import (
"context"
"errors"
2017-07-09 14:12:37 -04:00
"fmt"
"net/url"
2017-07-09 20:33:03 -04:00
"strings"
2017-07-09 22:13:31 -04:00
"time"
2017-07-09 14:12:37 -04:00
"github.com/hashicorp/hcl/v2/hcldec"
vmwcommon "github.com/hashicorp/packer/builder/vmware/common"
vsphere "github.com/hashicorp/packer/builder/vsphere/common"
2017-07-09 14:12:37 -04:00
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/commonsteps"
2017-07-09 14:12:37 -04:00
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/helper/multistep"
2017-07-09 14:12:37 -04:00
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer-plugin-sdk/template/interpolate"
"github.com/hashicorp/packer/post-processor/artifice"
vspherepost "github.com/hashicorp/packer/post-processor/vsphere"
"github.com/vmware/govmomi"
2017-07-09 14:12:37 -04:00
)
2017-07-09 20:33:03 -04:00
var builtins = map[string]string{
vspherepost.BuilderId: "vmware",
vmwcommon.BuilderIdESX: "vmware",
vsphere.BuilderId: "vsphere",
artifice.BuilderId: "artifice",
2017-07-09 20:33:03 -04:00
}
2017-07-09 14:12:37 -04:00
type Config struct {
common.PackerConfig `mapstructure:",squash"`
Host string `mapstructure:"host"`
Insecure bool `mapstructure:"insecure"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
Datacenter string `mapstructure:"datacenter"`
Folder string `mapstructure:"folder"`
SnapshotEnable bool `mapstructure:"snapshot_enable"`
SnapshotName string `mapstructure:"snapshot_name"`
SnapshotDescription string `mapstructure:"snapshot_description"`
ReregisterVM config.Trilean `mapstructure:"reregister_vm"`
2017-07-09 14:12:37 -04:00
ctx interpolate.Context
}
type PostProcessor struct {
config Config
url *url.URL
}
build using HCL2 (#8423) This follows #8232 which added the code to generate the code required to parse HCL files for each packer component. All old config files of packer will keep on working the same. Packer takes one argument. When a directory is passed, all files in the folder with a name ending with “.pkr.hcl” or “.pkr.json” will be parsed using the HCL2 format. When a file ending with “.pkr.hcl” or “.pkr.json” is passed it will be parsed using the HCL2 format. For every other case; the old packer style will be used. ## 1. the hcl2template pkg can create a packer.Build from a set of HCL (v2) files I had to make the packer.coreBuild (which is our one and only packer.Build ) a public struct with public fields ## 2. Components interfaces get a new ConfigSpec Method to read a file from an HCL file. This is a breaking change for packer plugins. a packer component can be a: builder/provisioner/post-processor each component interface now gets a `ConfigSpec() hcldec.ObjectSpec` which allows packer to tell what is the layout of the hcl2 config meant to configure that specific component. This ObjectSpec is sent through the wire (RPC) and a cty.Value is now sent through the already existing configuration entrypoints: Provisioner.Prepare(raws ...interface{}) error Builder.Prepare(raws ...interface{}) ([]string, error) PostProcessor.Configure(raws ...interface{}) error close #1768 Example hcl files: ```hcl // file amazon-ebs-kms-key/run.pkr.hcl build { sources = [ "source.amazon-ebs.first", ] provisioner "shell" { inline = [ "sleep 5" ] } post-processor "shell-local" { inline = [ "sleep 5" ] } } // amazon-ebs-kms-key/source.pkr.hcl source "amazon-ebs" "first" { ami_name = "hcl2-test" region = "us-east-1" instance_type = "t2.micro" kms_key_id = "c729958f-c6ba-44cd-ab39-35ab68ce0a6c" encrypt_boot = true source_ami_filter { filters { virtualization-type = "hvm" name = "amzn-ami-hvm-????.??.?.????????-x86_64-gp2" root-device-type = "ebs" } most_recent = true owners = ["amazon"] } launch_block_device_mappings { device_name = "/dev/xvda" volume_size = 20 volume_type = "gp2" delete_on_termination = "true" } launch_block_device_mappings { device_name = "/dev/xvdf" volume_size = 500 volume_type = "gp2" delete_on_termination = true encrypted = true } ami_regions = ["eu-central-1"] run_tags { Name = "packer-solr-something" stack-name = "DevOps Tools" } communicator = "ssh" ssh_pty = true ssh_username = "ec2-user" associate_public_ip_address = true } ```
2019-12-17 05:25:56 -05:00
func (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
2017-07-09 14:12:37 -04:00
func (p *PostProcessor) Configure(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
PluginType: vsphere.BuilderId,
2017-07-09 14:12:37 -04:00
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
if err != nil {
return err
}
errs := new(packer.MultiError)
vc := map[string]*string{
"host": &p.config.Host,
"username": &p.config.Username,
"password": &p.config.Password,
}
for key, ptr := range vc {
if *ptr == "" {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("%s must be set", key))
}
}
2017-07-18 23:10:05 -04:00
if p.config.Folder != "" && !strings.HasPrefix(p.config.Folder, "/") {
2017-07-09 14:56:39 -04:00
errs = packer.MultiErrorAppend(
2017-07-18 23:10:05 -04:00
errs, fmt.Errorf("Folder must be bound to the root"))
2017-07-09 14:56:39 -04:00
}
2017-07-18 23:10:05 -04:00
sdk, err := url.Parse(fmt.Sprintf("https://%v/sdk", p.config.Host))
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Error invalid vSphere sdk endpoint: %s", err))
return errs
2017-07-18 23:10:05 -04:00
}
sdk.User = url.UserPassword(p.config.Username, p.config.Password)
p.url = sdk
2017-07-09 14:12:37 -04:00
if len(errs.Errors) > 0 {
return errs
}
return nil
}
func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {
2017-07-09 20:33:03 -04:00
if _, ok := builtins[artifact.BuilderId()]; !ok {
2019-04-02 19:51:58 -04:00
return nil, false, false, fmt.Errorf("The Packer vSphere Template post-processor "+
"can only take an artifact from the VMware-iso builder, built on "+
"ESXi (i.e. remote) or an artifact from the vSphere post-processor. "+
"Artifact type %s does not fit this requirement", artifact.BuilderId())
2017-07-09 20:33:03 -04:00
}
2017-07-09 14:56:39 -04:00
f := artifact.State(vmwcommon.ArtifactConfFormat)
k := artifact.State(vmwcommon.ArtifactConfKeepRegistered)
s := artifact.State(vmwcommon.ArtifactConfSkipExport)
if f != "" && k != "true" && s == "false" {
2019-04-02 19:51:58 -04:00
return nil, false, false, errors.New("To use this post-processor with exporting behavior you need set keep_registered as true")
}
// In some occasions the VM state is powered on and if we immediately try to mark as template
// (after the ESXi creates it) it will fail. If vSphere is given a few seconds this behavior doesn't reappear.
2017-08-24 21:46:35 -04:00
ui.Message("Waiting 10s for VMware vSphere to start")
2017-07-09 14:56:39 -04:00
time.Sleep(10 * time.Second)
2017-07-18 23:10:05 -04:00
c, err := govmomi.NewClient(context.Background(), p.url, p.config.Insecure)
if err != nil {
2019-04-02 19:51:58 -04:00
return nil, false, false, fmt.Errorf("Error connecting to vSphere: %s", err)
}
2017-07-31 10:30:13 -04:00
defer c.Logout(context.Background())
state := new(multistep.BasicStateBag)
state.Put("ui", ui)
state.Put("client", c)
2017-07-09 14:56:39 -04:00
steps := []multistep.Step{
2017-07-18 23:10:05 -04:00
&stepChooseDatacenter{
2017-07-09 14:56:39 -04:00
Datacenter: p.config.Datacenter,
},
&stepCreateFolder{
Folder: p.config.Folder,
},
NewStepCreateSnapshot(artifact, p),
NewStepMarkAsTemplate(artifact, p),
2017-07-09 14:56:39 -04:00
}
runner := commonsteps.NewRunnerWithPauseFn(steps, p.config.PackerConfig, ui, state)
2019-03-22 09:56:02 -04:00
runner.Run(ctx, state)
2017-07-09 14:56:39 -04:00
if rawErr, ok := state.GetOk("error"); ok {
2019-04-02 19:51:58 -04:00
return nil, false, false, rawErr.(error)
2017-07-09 14:56:39 -04:00
}
2019-04-02 19:51:58 -04:00
return artifact, true, true, nil
2017-07-09 14:12:37 -04:00
}