packer-cn/builder/ucloud/uhost/builder.go

164 lines
4.6 KiB
Go
Raw Normal View History

//go:generate mapstructure-to-hcl2 -type Config
2019-06-13 03:16:49 -04:00
// The ucloud-uhost contains a packer.Builder implementation that
// builds uhost images for UCloud UHost instance.
package uhost
import (
"context"
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
"github.com/hashicorp/hcl/v2/hcldec"
2019-10-12 04:46:21 -04:00
ucloudcommon "github.com/hashicorp/packer/builder/ucloud/common"
2019-06-13 03:16:49 -04:00
"github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer-plugin-sdk/common"
2020-11-17 19:31:03 -05:00
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
"github.com/hashicorp/packer/packer-plugin-sdk/multistep/commonsteps"
"github.com/hashicorp/packer/packer-plugin-sdk/template/config"
"github.com/hashicorp/packer/packer-plugin-sdk/template/interpolate"
2019-06-13 03:16:49 -04:00
)
// The unique ID for this builder
const BuilderId = "ucloud.uhost"
type Config struct {
2019-10-12 04:46:21 -04:00
common.PackerConfig `mapstructure:",squash"`
ucloudcommon.AccessConfig `mapstructure:",squash"`
ucloudcommon.ImageConfig `mapstructure:",squash"`
ucloudcommon.RunConfig `mapstructure:",squash"`
2019-06-13 03:16:49 -04:00
ctx interpolate.Context
}
type Builder struct {
config Config
runner multistep.Runner
}
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 (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() }
func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) {
2019-06-13 03:16:49 -04:00
err := config.Decode(&b.config, &config.DecodeOpts{
PluginType: BuilderId,
2019-06-13 03:16:49 -04:00
Interpolate: true,
InterpolateContext: &b.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"run_command",
},
},
}, raws...)
b.config.ctx.EnableEnv = true
if err != nil {
return nil, nil, err
2019-06-13 03:16:49 -04:00
}
// Accumulate any errors
var errs *packer.MultiError
errs = packer.MultiErrorAppend(errs, b.config.AccessConfig.Prepare(&b.config.ctx)...)
errs = packer.MultiErrorAppend(errs, b.config.ImageConfig.Prepare(&b.config.ctx)...)
errs = packer.MultiErrorAppend(errs, b.config.RunConfig.Prepare(&b.config.ctx)...)
if errs != nil && len(errs.Errors) > 0 {
return nil, nil, errs
2019-06-13 03:16:49 -04:00
}
packer.LogSecretFilter.Set(b.config.PublicKey, b.config.PrivateKey)
return nil, nil, nil
2019-06-13 03:16:49 -04:00
}
func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
client, err := b.config.Client()
if err != nil {
return nil, err
}
// Setup the state bag and initial state for the steps
state := new(multistep.BasicStateBag)
state.Put("config", &b.config)
state.Put("client", client)
state.Put("hook", hook)
state.Put("ui", ui)
var steps []multistep.Step
// Build the steps
steps = []multistep.Step{
&stepPreValidate{
2019-06-14 02:50:46 -04:00
ProjectId: b.config.ProjectId,
2019-06-13 03:16:49 -04:00
Region: b.config.Region,
Zone: b.config.Zone,
ImageDestinations: b.config.ImageDestinations,
},
&stepCheckSourceImageId{
SourceUHostImageId: b.config.SourceImageId,
},
&stepConfigVPC{
VPCId: b.config.VPCId,
},
&stepConfigSubnet{
SubnetId: b.config.SubnetId,
},
&stepConfigSecurityGroup{
SecurityGroupId: b.config.SecurityGroupId,
},
&stepCreateInstance{
InstanceType: b.config.InstanceType,
Region: b.config.Region,
Zone: b.config.Zone,
SourceImageId: b.config.SourceImageId,
InstanceName: b.config.InstanceName,
BootDiskType: b.config.BootDiskType,
UsePrivateIp: b.config.UseSSHPrivateIp,
EipBandwidth: b.config.EipBandwidth,
EipChargeMode: b.config.EipChargeMode,
UserData: b.config.UserData,
UserDataFile: b.config.UserDataFile,
MinCpuPlatform: b.config.MinCpuPlatform,
2019-06-13 03:16:49 -04:00
},
&communicator.StepConnect{
Config: &b.config.RunConfig.Comm,
2019-10-12 04:46:21 -04:00
Host: ucloudcommon.SSHHost(
2019-06-13 03:16:49 -04:00
b.config.UseSSHPrivateIp),
SSHConfig: b.config.RunConfig.Comm.SSHConfigFunc(),
},
&commonsteps.StepProvision{},
2019-06-13 03:16:49 -04:00
&stepStopInstance{},
&stepCreateImage{},
&stepCopyUCloudImage{
2019-10-18 02:52:20 -04:00
ImageDestinations: b.config.ImageDestinations,
RegionId: b.config.Region,
ProjectId: b.config.ProjectId,
WaitImageReadyTimeout: b.config.WaitImageReadyTimeout,
2019-06-13 03:16:49 -04:00
},
}
// Run!
b.runner = commonsteps.NewRunner(steps, b.config.PackerConfig, ui)
2019-06-13 03:16:49 -04:00
b.runner.Run(ctx, state)
// If there was an error, return that
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
// If there are no ucloud images, then just return
if _, ok := state.GetOk("ucloud_images"); !ok {
return nil, nil
}
// Build the artifact and return it
2019-10-12 04:46:21 -04:00
artifact := &ucloudcommon.Artifact{
UCloudImages: state.Get("ucloud_images").(*ucloudcommon.ImageInfoSet),
2019-06-13 03:16:49 -04:00
BuilderIdValue: BuilderId,
Client: client,
StateData: map[string]interface{}{"generated_data": state.Get("generated_data")},
2019-06-13 03:16:49 -04:00
}
return artifact, nil
}