diff --git a/command/vendored_plugins.go b/command/vendored_plugins.go index 7d8d42901..4201a1319 100644 --- a/command/vendored_plugins.go +++ b/command/vendored_plugins.go @@ -39,6 +39,8 @@ import ( parallelspvmbuilder "github.com/hashicorp/packer-plugin-parallels/builder/parallels/pvm" proxmoxclone "github.com/hashicorp/packer-plugin-proxmox/builder/proxmox/clone" proxmoxiso "github.com/hashicorp/packer-plugin-proxmox/builder/proxmox/iso" + puppetmasterlessprovisioner "github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless" + puppetserverprovisioner "github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server" qemubuilder "github.com/hashicorp/packer-plugin-qemu/builder/qemu" scalewaybuilder "github.com/hashicorp/packer-plugin-scaleway/builder/scaleway" virtualboxisobuilder "github.com/hashicorp/packer-plugin-virtualbox/builder/virtualbox/iso" @@ -95,10 +97,12 @@ var VendoredBuilders = map[string]packersdk.Builder{ // VendoredProvisioners are provisioner components that were once bundled with the // Packer core, but are now being imported from their counterpart plugin repos var VendoredProvisioners = map[string]packersdk.Provisioner{ - "ansible": new(ansibleprovisioner.Provisioner), - "ansible-local": new(ansiblelocalprovisioner.Provisioner), - "chef-client": new(chefclientprovisioner.Provisioner), - "chef-solo": new(chefsoloprovisioner.Provisioner), + "ansible": new(ansibleprovisioner.Provisioner), + "ansible-local": new(ansiblelocalprovisioner.Provisioner), + "chef-client": new(chefclientprovisioner.Provisioner), + "chef-solo": new(chefsoloprovisioner.Provisioner), + "puppet-masterless": new(puppetmasterlessprovisioner.Provisioner), + "puppet-server": new(puppetserverprovisioner.Provisioner), } // VendoredPostProcessors are post-processor components that were once bundled with the diff --git a/go.mod b/go.mod index 0a17ded97..b5059cd3c 100644 --- a/go.mod +++ b/go.mod @@ -48,6 +48,7 @@ require ( github.com/hashicorp/packer-plugin-outscale v0.0.1 github.com/hashicorp/packer-plugin-parallels v0.0.1 github.com/hashicorp/packer-plugin-proxmox v0.0.2 + github.com/hashicorp/packer-plugin-puppet v0.0.1 github.com/hashicorp/packer-plugin-qemu v0.0.1 github.com/hashicorp/packer-plugin-scaleway v0.0.1 github.com/hashicorp/packer-plugin-sdk v0.2.0 diff --git a/go.sum b/go.sum index 5c320b4d6..eca69cfb7 100644 --- a/go.sum +++ b/go.sum @@ -484,6 +484,8 @@ github.com/hashicorp/packer-plugin-parallels v0.0.1 h1:fcaaiGWdU1+X4IGadXdUhJ2si github.com/hashicorp/packer-plugin-parallels v0.0.1/go.mod h1:FGNtZ7XFBr3IYuj7uvJtSaNnyhAwe457zP464m06+20= github.com/hashicorp/packer-plugin-proxmox v0.0.2 h1:x6QW7PeKh+IJymPEt3QdpBhSRi5vqXb8qTWv7rMLuns= github.com/hashicorp/packer-plugin-proxmox v0.0.2/go.mod h1:3URutEWX1yy10qcHNJncS4OMpZknA1FyvlrfL+5usYk= +github.com/hashicorp/packer-plugin-puppet v0.0.1 h1:avOlJB2suArgqo3gn/JipLtHY0TVuTcweYA3GxVceyY= +github.com/hashicorp/packer-plugin-puppet v0.0.1/go.mod h1:HgRpw6hXYykjyceBRbrRvBT7vSU7Ofo5HIfFRMCehQc= github.com/hashicorp/packer-plugin-qemu v0.0.1 h1:yGnmWf4Z+ZmOJXJF6w23V2KChtTCiPHsFnfg7+LRu74= github.com/hashicorp/packer-plugin-qemu v0.0.1/go.mod h1:8Q/LCjO7oplLcLe1KLdEt7rq94h42Di6Lab2DTLNwVg= github.com/hashicorp/packer-plugin-scaleway v0.0.1 h1:FSq76WuMJNKwCvF77v06EpuLe/AJP3sG5/YrfL41kcw= diff --git a/vendor/github.com/hashicorp/packer-plugin-puppet/LICENSE b/vendor/github.com/hashicorp/packer-plugin-puppet/LICENSE new file mode 100644 index 000000000..a612ad981 --- /dev/null +++ b/vendor/github.com/hashicorp/packer-plugin-puppet/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless/provisioner.go b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless/provisioner.go new file mode 100644 index 000000000..6ec699e4a --- /dev/null +++ b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless/provisioner.go @@ -0,0 +1,501 @@ +//go:generate packer-sdc mapstructure-to-hcl2 -type Config + +// Package puppetmasterless implements a provisioner for Packer that executes +// Puppet on the remote machine, configured to apply a local manifest +// versus connecting to a Puppet master. +package puppetmasterless + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/hashicorp/packer-plugin-sdk/common" + "github.com/hashicorp/packer-plugin-sdk/guestexec" + packersdk "github.com/hashicorp/packer-plugin-sdk/packer" + "github.com/hashicorp/packer-plugin-sdk/template/config" + "github.com/hashicorp/packer-plugin-sdk/template/interpolate" +) + +type Config struct { + common.PackerConfig `mapstructure:",squash"` + ctx interpolate.Context + + // If true, staging directory is removed after executing puppet. + CleanStagingDir bool `mapstructure:"clean_staging_directory"` + + // The Guest OS Type (unix or windows) + GuestOSType string `mapstructure:"guest_os_type"` + + // The command used to execute Puppet. + ExecuteCommand string `mapstructure:"execute_command"` + + // Additional arguments to pass when executing Puppet + ExtraArguments []string `mapstructure:"extra_arguments"` + + // Additional facts to set when executing Puppet + Facter map[string]string + + // Path to a hiera configuration file to upload and use. + HieraConfigPath string `mapstructure:"hiera_config_path"` + + // If true, packer will ignore all exit-codes from a puppet run + IgnoreExitCodes bool `mapstructure:"ignore_exit_codes"` + + // An array of local paths of modules to upload. + ModulePaths []string `mapstructure:"module_paths"` + + // The main manifest file to apply to kick off the entire thing. + ManifestFile string `mapstructure:"manifest_file"` + + // A directory of manifest files that will be uploaded to the remote + // machine. + ManifestDir string `mapstructure:"manifest_dir"` + + // If true, `sudo` will NOT be used to execute Puppet. + PreventSudo bool `mapstructure:"prevent_sudo"` + + // The directory that contains the puppet binary. + // E.g. if it can't be found on the standard path. + PuppetBinDir string `mapstructure:"puppet_bin_dir"` + + // The directory where files will be uploaded. Packer requires write + // permissions in this directory. + StagingDir string `mapstructure:"staging_directory"` + + // The directory from which the command will be executed. + // Packer requires the directory to exist when running puppet. + WorkingDir string `mapstructure:"working_directory"` + + // Instructs the communicator to run the remote script as a Windows + // scheduled task, effectively elevating the remote user by impersonating + // a logged-in user + ElevatedUser string `mapstructure:"elevated_user"` + ElevatedPassword string `mapstructure:"elevated_password"` +} + +type guestOSTypeConfig struct { + executeCommand string + facterVarsFmt string + facterVarsJoiner string + modulePathJoiner string + stagingDir string + tempDir string +} + +// FIXME assumes both Packer host and target are same OS +var guestOSTypeConfigs = map[string]guestOSTypeConfig{ + guestexec.UnixOSType: { + tempDir: "/tmp", + stagingDir: "/tmp/packer-puppet-masterless", + executeCommand: "cd {{.WorkingDir}} && " + + `{{if ne .FacterVars ""}}{{.FacterVars}} {{end}}` + + "{{if .Sudo}}sudo -E {{end}}" + + `{{if ne .PuppetBinDir ""}}{{.PuppetBinDir}}/{{end}}` + + "puppet apply --detailed-exitcodes " + + "{{if .Debug}}--debug {{end}}" + + `{{if ne .ModulePath ""}}--modulepath='{{.ModulePath}}' {{end}}` + + `{{if ne .HieraConfigPath ""}}--hiera_config='{{.HieraConfigPath}}' {{end}}` + + `{{if ne .ManifestDir ""}}--manifestdir='{{.ManifestDir}}' {{end}}` + + `{{if ne .ExtraArguments ""}}{{.ExtraArguments}} {{end}}` + + "{{.ManifestFile}}", + facterVarsFmt: "FACTER_%s='%s'", + facterVarsJoiner: " ", + modulePathJoiner: ":", + }, + guestexec.WindowsOSType: { + tempDir: filepath.ToSlash(os.Getenv("TEMP")), + stagingDir: filepath.ToSlash(os.Getenv("SYSTEMROOT")) + "/Temp/packer-puppet-masterless", + executeCommand: "cd {{.WorkingDir}} && " + + `{{if ne .FacterVars ""}}{{.FacterVars}} && {{end}}` + + `{{if ne .PuppetBinDir ""}}{{.PuppetBinDir}}/{{end}}` + + "puppet apply --detailed-exitcodes " + + "{{if .Debug}}--debug {{end}}" + + `{{if ne .ModulePath ""}}--modulepath='{{.ModulePath}}' {{end}}` + + `{{if ne .HieraConfigPath ""}}--hiera_config='{{.HieraConfigPath}}' {{end}}` + + `{{if ne .ManifestDir ""}}--manifestdir='{{.ManifestDir}}' {{end}}` + + `{{if ne .ExtraArguments ""}}{{.ExtraArguments}} {{end}}` + + "{{.ManifestFile}}", + facterVarsFmt: `SET "FACTER_%s=%s"`, + facterVarsJoiner: " & ", + modulePathJoiner: ";", + }, +} + +type Provisioner struct { + config Config + communicator packersdk.Communicator + guestOSTypeConfig guestOSTypeConfig + guestCommands *guestexec.GuestCommands + generatedData map[string]interface{} +} + +type ExecuteTemplate struct { + Debug bool + ExtraArguments string + FacterVars string + HieraConfigPath string + ModulePath string + ModulePathJoiner string + ManifestFile string + ManifestDir string + PuppetBinDir string + Sudo bool + WorkingDir string +} + +type EnvVarsTemplate struct { + WinRMPassword string +} + +func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() } + +func (p *Provisioner) Prepare(raws ...interface{}) error { + err := config.Decode(&p.config, &config.DecodeOpts{ + PluginType: "puppet-masterless", + Interpolate: true, + InterpolateContext: &p.config.ctx, + InterpolateFilter: &interpolate.RenderFilter{ + Exclude: []string{ + "execute_command", + "extra_arguments", + }, + }, + }, raws...) + if err != nil { + return err + } + + // Set some defaults + if p.config.GuestOSType == "" { + p.config.GuestOSType = guestexec.DefaultOSType + } + p.config.GuestOSType = strings.ToLower(p.config.GuestOSType) + + var ok bool + p.guestOSTypeConfig, ok = guestOSTypeConfigs[p.config.GuestOSType] + if !ok { + return fmt.Errorf("Invalid guest_os_type: \"%s\"", p.config.GuestOSType) + } + + p.guestCommands, err = guestexec.NewGuestCommands(p.config.GuestOSType, !p.config.PreventSudo) + if err != nil { + return fmt.Errorf("Invalid guest_os_type: \"%s\"", p.config.GuestOSType) + } + + if p.config.ExecuteCommand == "" { + p.config.ExecuteCommand = p.guestOSTypeConfig.executeCommand + } + + if p.config.StagingDir == "" { + p.config.StagingDir = p.guestOSTypeConfig.stagingDir + } + + if p.config.WorkingDir == "" { + p.config.WorkingDir = p.config.StagingDir + } + + if p.config.Facter == nil { + p.config.Facter = make(map[string]string) + } + p.config.Facter["packer_build_name"] = p.config.PackerBuildName + p.config.Facter["packer_builder_type"] = p.config.PackerBuilderType + + // Validation + var errs *packersdk.MultiError + if p.config.HieraConfigPath != "" { + info, err := os.Stat(p.config.HieraConfigPath) + if err != nil { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("hiera_config_path is invalid: %s", err)) + } else if info.IsDir() { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("hiera_config_path must point to a file")) + } + } + + if p.config.ManifestDir != "" { + info, err := os.Stat(p.config.ManifestDir) + if err != nil { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("manifest_dir is invalid: %s", err)) + } else if !info.IsDir() { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("manifest_dir must point to a directory")) + } + } + + if p.config.ManifestFile == "" { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("A manifest_file must be specified.")) + } else { + _, err := os.Stat(p.config.ManifestFile) + if err != nil { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("manifest_file is invalid: %s", err)) + } + } + + for i, path := range p.config.ModulePaths { + info, err := os.Stat(path) + if err != nil { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("module_path[%d] is invalid: %s", i, err)) + } else if !info.IsDir() { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("module_path[%d] must point to a directory", i)) + } + } + + if errs != nil && len(errs.Errors) > 0 { + return errs + } + + return nil +} + +func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packersdk.Communicator, generatedData map[string]interface{}) error { + ui.Say("Provisioning with Puppet...") + p.communicator = comm + p.generatedData = generatedData + ui.Message("Creating Puppet staging directory...") + if err := p.createDir(ui, comm, p.config.StagingDir); err != nil { + return fmt.Errorf("Error creating staging directory: %s", err) + } + + // Upload hiera config if set + remoteHieraConfigPath := "" + if p.config.HieraConfigPath != "" { + var err error + remoteHieraConfigPath, err = p.uploadHieraConfig(ui, comm) + if err != nil { + return fmt.Errorf("Error uploading hiera config: %s", err) + } + } + + // Upload manifest dir if set + remoteManifestDir := "" + if p.config.ManifestDir != "" { + ui.Message(fmt.Sprintf( + "Uploading manifest directory from: %s", p.config.ManifestDir)) + remoteManifestDir = fmt.Sprintf("%s/manifests", p.config.StagingDir) + err := p.uploadDirectory(ui, comm, remoteManifestDir, p.config.ManifestDir) + if err != nil { + return fmt.Errorf("Error uploading manifest dir: %s", err) + } + } + + // Upload all modules + modulePaths := make([]string, 0, len(p.config.ModulePaths)) + for i, path := range p.config.ModulePaths { + ui.Message(fmt.Sprintf("Uploading local modules from: %s", path)) + targetPath := fmt.Sprintf("%s/module-%d", p.config.StagingDir, i) + if err := p.uploadDirectory(ui, comm, targetPath, path); err != nil { + return fmt.Errorf("Error uploading modules: %s", err) + } + + modulePaths = append(modulePaths, targetPath) + } + + // Upload manifests + remoteManifestFile, err := p.uploadManifests(ui, comm) + if err != nil { + return fmt.Errorf("Error uploading manifests: %s", err) + } + + // Compile the facter variables + facterVars := make([]string, 0, len(p.config.Facter)) + for k, v := range p.config.Facter { + facterVars = append(facterVars, fmt.Sprintf(p.guestOSTypeConfig.facterVarsFmt, k, v)) + } + + data := ExecuteTemplate{ + ExtraArguments: "", + FacterVars: strings.Join(facterVars, p.guestOSTypeConfig.facterVarsJoiner), + HieraConfigPath: remoteHieraConfigPath, + ManifestDir: remoteManifestDir, + ManifestFile: remoteManifestFile, + ModulePath: strings.Join(modulePaths, p.guestOSTypeConfig.modulePathJoiner), + ModulePathJoiner: p.guestOSTypeConfig.modulePathJoiner, + PuppetBinDir: p.config.PuppetBinDir, + Sudo: !p.config.PreventSudo, + WorkingDir: p.config.WorkingDir, + } + + p.config.ctx.Data = &data + _ExtraArguments, err := interpolate.Render(strings.Join(p.config.ExtraArguments, " "), &p.config.ctx) + if err != nil { + return err + } + data.ExtraArguments = _ExtraArguments + + command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx) + if err != nil { + return err + } + + if p.config.ElevatedUser != "" { + command, err = guestexec.GenerateElevatedRunner(command, p) + if err != nil { + return err + } + } + + cmd := &packersdk.RemoteCmd{ + Command: command, + } + + ui.Message(fmt.Sprintf("Running Puppet: %s", command)) + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return fmt.Errorf("Got an error starting command: %s", err) + } + + if cmd.ExitStatus() != 0 && cmd.ExitStatus() != 2 && !p.config.IgnoreExitCodes { + return fmt.Errorf("Puppet exited with a non-zero exit status: %d", cmd.ExitStatus()) + } + + if p.config.CleanStagingDir { + if err := p.removeDir(ui, comm, p.config.StagingDir); err != nil { + return fmt.Errorf("Error removing staging directory: %s", err) + } + } + + return nil +} + +func (p *Provisioner) uploadHieraConfig(ui packersdk.Ui, comm packersdk.Communicator) (string, error) { + ui.Message("Uploading hiera configuration...") + f, err := os.Open(p.config.HieraConfigPath) + if err != nil { + return "", err + } + defer f.Close() + + path := fmt.Sprintf("%s/hiera.yaml", p.config.StagingDir) + if err := comm.Upload(path, f, nil); err != nil { + return "", err + } + + return path, nil +} + +func (p *Provisioner) uploadManifests(ui packersdk.Ui, comm packersdk.Communicator) (string, error) { + // Create the remote manifests directory... + ui.Message("Uploading manifests...") + remoteManifestsPath := fmt.Sprintf("%s/manifests", p.config.StagingDir) + if err := p.createDir(ui, comm, remoteManifestsPath); err != nil { + return "", fmt.Errorf("Error creating manifests directory: %s", err) + } + + // NOTE! manifest_file may either be a directory or a file, as puppet apply + // now accepts either one. + + fi, err := os.Stat(p.config.ManifestFile) + if err != nil { + return "", fmt.Errorf("Error inspecting manifest file: %s", err) + } + + if fi.IsDir() { + // If manifest_file is a directory we'll upload the whole thing + ui.Message(fmt.Sprintf( + "Uploading manifest directory from: %s", p.config.ManifestFile)) + + remoteManifestDir := fmt.Sprintf("%s/manifests", p.config.StagingDir) + err := p.uploadDirectory(ui, comm, remoteManifestDir, p.config.ManifestFile) + if err != nil { + return "", fmt.Errorf("Error uploading manifest dir: %s", err) + } + return remoteManifestDir, nil + } + // Otherwise manifest_file is a file and we'll upload it + ui.Message(fmt.Sprintf( + "Uploading manifest file from: %s", p.config.ManifestFile)) + + f, err := os.Open(p.config.ManifestFile) + if err != nil { + return "", err + } + defer f.Close() + + manifestFilename := filepath.Base(p.config.ManifestFile) + remoteManifestFile := fmt.Sprintf("%s/%s", remoteManifestsPath, manifestFilename) + if err := comm.Upload(remoteManifestFile, f, nil); err != nil { + return "", err + } + return remoteManifestFile, nil +} + +func (p *Provisioner) createDir(ui packersdk.Ui, comm packersdk.Communicator, dir string) error { + ui.Message(fmt.Sprintf("Creating directory: %s", dir)) + + cmd := &packersdk.RemoteCmd{Command: p.guestCommands.CreateDir(dir)} + ctx := context.TODO() + + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + + if cmd.ExitStatus() != 0 { + return fmt.Errorf("Non-zero exit status.") + } + + // Chmod the directory to 0777 just so that we can access it as our user + cmd = &packersdk.RemoteCmd{Command: p.guestCommands.Chmod(dir, "0777")} + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + if cmd.ExitStatus() != 0 { + return fmt.Errorf("Non-zero exit status. See output above for more info.") + } + + return nil +} + +func (p *Provisioner) removeDir(ui packersdk.Ui, comm packersdk.Communicator, dir string) error { + ctx := context.TODO() + + cmd := &packersdk.RemoteCmd{Command: p.guestCommands.RemoveDir(dir)} + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + + if cmd.ExitStatus() != 0 { + return fmt.Errorf("Non-zero exit status.") + } + + return nil +} + +func (p *Provisioner) uploadDirectory(ui packersdk.Ui, comm packersdk.Communicator, dst string, src string) error { + if err := p.createDir(ui, comm, dst); err != nil { + return err + } + + // Make sure there is a trailing "/" so that the directory isn't + // created on the other side. + if src[len(src)-1] != '/' { + src = src + "/" + } + + return comm.UploadDir(dst, src, nil) +} + +func (p *Provisioner) Communicator() packersdk.Communicator { + return p.communicator +} + +func (p *Provisioner) ElevatedUser() string { + return p.config.ElevatedUser +} + +func (p *Provisioner) ElevatedPassword() string { + // Replace ElevatedPassword for winrm users who used this feature + p.config.ctx.Data = p.generatedData + + elevatedPassword, _ := interpolate.Render(p.config.ElevatedPassword, &p.config.ctx) + + return elevatedPassword +} diff --git a/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless/provisioner.hcl2spec.go b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless/provisioner.hcl2spec.go new file mode 100644 index 000000000..c17611081 --- /dev/null +++ b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless/provisioner.hcl2spec.go @@ -0,0 +1,77 @@ +// Code generated by "packer-sdc mapstructure-to-hcl2"; DO NOT EDIT. + +package puppetmasterless + +import ( + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/zclconf/go-cty/cty" +) + +// FlatConfig is an auto-generated flat version of Config. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatConfig struct { + PackerBuildName *string `mapstructure:"packer_build_name" cty:"packer_build_name" hcl:"packer_build_name"` + PackerBuilderType *string `mapstructure:"packer_builder_type" cty:"packer_builder_type" hcl:"packer_builder_type"` + PackerCoreVersion *string `mapstructure:"packer_core_version" cty:"packer_core_version" hcl:"packer_core_version"` + PackerDebug *bool `mapstructure:"packer_debug" cty:"packer_debug" hcl:"packer_debug"` + PackerForce *bool `mapstructure:"packer_force" cty:"packer_force" hcl:"packer_force"` + PackerOnError *string `mapstructure:"packer_on_error" cty:"packer_on_error" hcl:"packer_on_error"` + PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` + PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` + CleanStagingDir *bool `mapstructure:"clean_staging_directory" cty:"clean_staging_directory" hcl:"clean_staging_directory"` + GuestOSType *string `mapstructure:"guest_os_type" cty:"guest_os_type" hcl:"guest_os_type"` + ExecuteCommand *string `mapstructure:"execute_command" cty:"execute_command" hcl:"execute_command"` + ExtraArguments []string `mapstructure:"extra_arguments" cty:"extra_arguments" hcl:"extra_arguments"` + Facter map[string]string `cty:"facter" hcl:"facter"` + HieraConfigPath *string `mapstructure:"hiera_config_path" cty:"hiera_config_path" hcl:"hiera_config_path"` + IgnoreExitCodes *bool `mapstructure:"ignore_exit_codes" cty:"ignore_exit_codes" hcl:"ignore_exit_codes"` + ModulePaths []string `mapstructure:"module_paths" cty:"module_paths" hcl:"module_paths"` + ManifestFile *string `mapstructure:"manifest_file" cty:"manifest_file" hcl:"manifest_file"` + ManifestDir *string `mapstructure:"manifest_dir" cty:"manifest_dir" hcl:"manifest_dir"` + PreventSudo *bool `mapstructure:"prevent_sudo" cty:"prevent_sudo" hcl:"prevent_sudo"` + PuppetBinDir *string `mapstructure:"puppet_bin_dir" cty:"puppet_bin_dir" hcl:"puppet_bin_dir"` + StagingDir *string `mapstructure:"staging_directory" cty:"staging_directory" hcl:"staging_directory"` + WorkingDir *string `mapstructure:"working_directory" cty:"working_directory" hcl:"working_directory"` + ElevatedUser *string `mapstructure:"elevated_user" cty:"elevated_user" hcl:"elevated_user"` + ElevatedPassword *string `mapstructure:"elevated_password" cty:"elevated_password" hcl:"elevated_password"` +} + +// FlatMapstructure returns a new FlatConfig. +// FlatConfig is an auto-generated flat version of Config. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*Config) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatConfig) +} + +// HCL2Spec returns the hcl spec of a Config. +// This spec is used by HCL to read the fields of Config. +// The decoded values from this spec will then be applied to a FlatConfig. +func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "packer_build_name": &hcldec.AttrSpec{Name: "packer_build_name", Type: cty.String, Required: false}, + "packer_builder_type": &hcldec.AttrSpec{Name: "packer_builder_type", Type: cty.String, Required: false}, + "packer_core_version": &hcldec.AttrSpec{Name: "packer_core_version", Type: cty.String, Required: false}, + "packer_debug": &hcldec.AttrSpec{Name: "packer_debug", Type: cty.Bool, Required: false}, + "packer_force": &hcldec.AttrSpec{Name: "packer_force", Type: cty.Bool, Required: false}, + "packer_on_error": &hcldec.AttrSpec{Name: "packer_on_error", Type: cty.String, Required: false}, + "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, + "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, + "clean_staging_directory": &hcldec.AttrSpec{Name: "clean_staging_directory", Type: cty.Bool, Required: false}, + "guest_os_type": &hcldec.AttrSpec{Name: "guest_os_type", Type: cty.String, Required: false}, + "execute_command": &hcldec.AttrSpec{Name: "execute_command", Type: cty.String, Required: false}, + "extra_arguments": &hcldec.AttrSpec{Name: "extra_arguments", Type: cty.List(cty.String), Required: false}, + "facter": &hcldec.AttrSpec{Name: "facter", Type: cty.Map(cty.String), Required: false}, + "hiera_config_path": &hcldec.AttrSpec{Name: "hiera_config_path", Type: cty.String, Required: false}, + "ignore_exit_codes": &hcldec.AttrSpec{Name: "ignore_exit_codes", Type: cty.Bool, Required: false}, + "module_paths": &hcldec.AttrSpec{Name: "module_paths", Type: cty.List(cty.String), Required: false}, + "manifest_file": &hcldec.AttrSpec{Name: "manifest_file", Type: cty.String, Required: false}, + "manifest_dir": &hcldec.AttrSpec{Name: "manifest_dir", Type: cty.String, Required: false}, + "prevent_sudo": &hcldec.AttrSpec{Name: "prevent_sudo", Type: cty.Bool, Required: false}, + "puppet_bin_dir": &hcldec.AttrSpec{Name: "puppet_bin_dir", Type: cty.String, Required: false}, + "staging_directory": &hcldec.AttrSpec{Name: "staging_directory", Type: cty.String, Required: false}, + "working_directory": &hcldec.AttrSpec{Name: "working_directory", Type: cty.String, Required: false}, + "elevated_user": &hcldec.AttrSpec{Name: "elevated_user", Type: cty.String, Required: false}, + "elevated_password": &hcldec.AttrSpec{Name: "elevated_password", Type: cty.String, Required: false}, + } + return s +} diff --git a/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server/provisioner.go b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server/provisioner.go new file mode 100644 index 000000000..47c5066f4 --- /dev/null +++ b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server/provisioner.go @@ -0,0 +1,390 @@ +//go:generate packer-sdc mapstructure-to-hcl2 -type Config + +// Package puppetserver implements a provisioner for Packer that executes +// Puppet on the remote machine connecting to a Puppet master. +package puppetserver + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/hashicorp/packer-plugin-sdk/common" + "github.com/hashicorp/packer-plugin-sdk/guestexec" + packersdk "github.com/hashicorp/packer-plugin-sdk/packer" + "github.com/hashicorp/packer-plugin-sdk/template/config" + "github.com/hashicorp/packer-plugin-sdk/template/interpolate" +) + +type Config struct { + common.PackerConfig `mapstructure:",squash"` + ctx interpolate.Context + + // If true, staging directory is removed after executing puppet. + CleanStagingDir bool `mapstructure:"clean_staging_directory"` + + // A path to the client certificate + ClientCertPath string `mapstructure:"client_cert_path"` + + // A path to a directory containing the client private keys + ClientPrivateKeyPath string `mapstructure:"client_private_key_path"` + + // The command used to execute Puppet. + ExecuteCommand string `mapstructure:"execute_command"` + + // Additional argument to pass when executing Puppet. + ExtraArguments []string `mapstructure:"extra_arguments"` + + // Additional facts to set when executing Puppet + Facter map[string]string + + // The Guest OS Type (unix or windows) + GuestOSType string `mapstructure:"guest_os_type"` + + // If true, packer will ignore all exit-codes from a puppet run + IgnoreExitCodes bool `mapstructure:"ignore_exit_codes"` + + // If true, `sudo` will NOT be used to execute Puppet. + PreventSudo bool `mapstructure:"prevent_sudo"` + + // The directory that contains the puppet binary. + // E.g. if it can't be found on the standard path. + PuppetBinDir string `mapstructure:"puppet_bin_dir"` + + // The hostname of the Puppet node. + PuppetNode string `mapstructure:"puppet_node"` + + // The hostname of the Puppet server. + PuppetServer string `mapstructure:"puppet_server"` + + // The directory where files will be uploaded. Packer requires write + // permissions in this directory. + StagingDir string `mapstructure:"staging_dir"` + + // The directory from which the command will be executed. + // Packer requires the directory to exist when running puppet. + WorkingDir string `mapstructure:"working_directory"` + + // Instructs the communicator to run the remote script as a Windows + // scheduled task, effectively elevating the remote user by impersonating + // a logged-in user + ElevatedUser string `mapstructure:"elevated_user"` + ElevatedPassword string `mapstructure:"elevated_password"` +} + +type guestOSTypeConfig struct { + executeCommand string + facterVarsFmt string + facterVarsJoiner string + stagingDir string + tempDir string +} + +// FIXME assumes both Packer host and target are same OS +var guestOSTypeConfigs = map[string]guestOSTypeConfig{ + guestexec.UnixOSType: { + tempDir: "/tmp", + stagingDir: "/tmp/packer-puppet-server", + executeCommand: "cd {{.WorkingDir}} && " + + `{{if ne .FacterVars ""}}{{.FacterVars}} {{end}}` + + "{{if .Sudo}}sudo -E {{end}}" + + `{{if ne .PuppetBinDir ""}}{{.PuppetBinDir}}/{{end}}` + + "puppet agent --onetime --no-daemonize --detailed-exitcodes " + + "{{if .Debug}}--debug {{end}}" + + `{{if ne .PuppetServer ""}}--server='{{.PuppetServer}}' {{end}}` + + `{{if ne .PuppetNode ""}}--certname='{{.PuppetNode}}' {{end}}` + + `{{if ne .ClientCertPath ""}}--certdir='{{.ClientCertPath}}' {{end}}` + + `{{if ne .ClientPrivateKeyPath ""}}--privatekeydir='{{.ClientPrivateKeyPath}}' {{end}}` + + `{{if ne .ExtraArguments ""}}{{.ExtraArguments}} {{end}}`, + facterVarsFmt: "FACTER_%s='%s'", + facterVarsJoiner: " ", + }, + guestexec.WindowsOSType: { + tempDir: filepath.ToSlash(os.Getenv("TEMP")), + stagingDir: filepath.ToSlash(os.Getenv("SYSTEMROOT")) + "/Temp/packer-puppet-server", + executeCommand: "cd {{.WorkingDir}} && " + + `{{if ne .FacterVars ""}}{{.FacterVars}} && {{end}}` + + `{{if ne .PuppetBinDir ""}}{{.PuppetBinDir}}/{{end}}` + + "puppet agent --onetime --no-daemonize --detailed-exitcodes " + + "{{if .Debug}}--debug {{end}}" + + `{{if ne .PuppetServer ""}}--server='{{.PuppetServer}}' {{end}}` + + `{{if ne .PuppetNode ""}}--certname='{{.PuppetNode}}' {{end}}` + + `{{if ne .ClientCertPath ""}}--certdir='{{.ClientCertPath}}' {{end}}` + + `{{if ne .ClientPrivateKeyPath ""}}--privatekeydir='{{.ClientPrivateKeyPath}}' {{end}}` + + `{{if ne .ExtraArguments ""}}{{.ExtraArguments}} {{end}}`, + facterVarsFmt: `SET "FACTER_%s=%s"`, + facterVarsJoiner: " & ", + }, +} + +type Provisioner struct { + config Config + communicator packersdk.Communicator + guestOSTypeConfig guestOSTypeConfig + guestCommands *guestexec.GuestCommands + generatedData map[string]interface{} +} + +type ExecuteTemplate struct { + ClientCertPath string + ClientPrivateKeyPath string + Debug bool + ExtraArguments string + FacterVars string + PuppetNode string + PuppetServer string + PuppetBinDir string + Sudo bool + WorkingDir string +} + +type EnvVarsTemplate struct { + WinRMPassword string +} + +func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() } + +func (p *Provisioner) Prepare(raws ...interface{}) error { + err := config.Decode(&p.config, &config.DecodeOpts{ + PluginType: "puppet-server", + Interpolate: true, + InterpolateContext: &p.config.ctx, + InterpolateFilter: &interpolate.RenderFilter{ + Exclude: []string{ + "execute_command", + "extra_arguments", + }, + }, + }, raws...) + if err != nil { + return err + } + + if p.config.GuestOSType == "" { + p.config.GuestOSType = guestexec.DefaultOSType + } + p.config.GuestOSType = strings.ToLower(p.config.GuestOSType) + + var ok bool + p.guestOSTypeConfig, ok = guestOSTypeConfigs[p.config.GuestOSType] + if !ok { + return fmt.Errorf("Invalid guest_os_type: \"%s\"", p.config.GuestOSType) + } + + p.guestCommands, err = guestexec.NewGuestCommands(p.config.GuestOSType, !p.config.PreventSudo) + if err != nil { + return fmt.Errorf("Invalid guest_os_type: \"%s\"", p.config.GuestOSType) + } + + if p.config.ExecuteCommand == "" { + p.config.ExecuteCommand = p.guestOSTypeConfig.executeCommand + } + + if p.config.StagingDir == "" { + p.config.StagingDir = p.guestOSTypeConfig.stagingDir + } + + if p.config.WorkingDir == "" { + p.config.WorkingDir = p.config.StagingDir + } + + if p.config.Facter == nil { + p.config.Facter = make(map[string]string) + } + p.config.Facter["packer_build_name"] = p.config.PackerBuildName + p.config.Facter["packer_builder_type"] = p.config.PackerBuilderType + + var errs *packersdk.MultiError + if p.config.ClientCertPath != "" { + info, err := os.Stat(p.config.ClientCertPath) + if err != nil { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("client_cert_dir is invalid: %s", err)) + } else if !info.IsDir() { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("client_cert_dir must point to a directory")) + } + } + + if p.config.ClientPrivateKeyPath != "" { + info, err := os.Stat(p.config.ClientPrivateKeyPath) + if err != nil { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("client_private_key_dir is invalid: %s", err)) + } else if !info.IsDir() { + errs = packersdk.MultiErrorAppend(errs, + fmt.Errorf("client_private_key_dir must point to a directory")) + } + } + + if errs != nil && len(errs.Errors) > 0 { + return errs + } + + return nil +} + +func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packersdk.Communicator, generatedData map[string]interface{}) error { + ui.Say("Provisioning with Puppet...") + p.communicator = comm + p.generatedData = generatedData + ui.Message("Creating Puppet staging directory...") + if err := p.createDir(ui, comm, p.config.StagingDir); err != nil { + return fmt.Errorf("Error creating staging directory: %s", err) + } + + // Upload client cert dir if set + remoteClientCertPath := "" + if p.config.ClientCertPath != "" { + ui.Message(fmt.Sprintf( + "Uploading client cert from: %s", p.config.ClientCertPath)) + remoteClientCertPath = fmt.Sprintf("%s/certs", p.config.StagingDir) + err := p.uploadDirectory(ui, comm, remoteClientCertPath, p.config.ClientCertPath) + if err != nil { + return fmt.Errorf("Error uploading client cert: %s", err) + } + } + + // Upload client cert dir if set + remoteClientPrivateKeyPath := "" + if p.config.ClientPrivateKeyPath != "" { + ui.Message(fmt.Sprintf( + "Uploading client private keys from: %s", p.config.ClientPrivateKeyPath)) + remoteClientPrivateKeyPath = fmt.Sprintf("%s/private_keys", p.config.StagingDir) + err := p.uploadDirectory(ui, comm, remoteClientPrivateKeyPath, p.config.ClientPrivateKeyPath) + if err != nil { + return fmt.Errorf("Error uploading client private keys: %s", err) + } + } + + // Compile the facter variables + facterVars := make([]string, 0, len(p.config.Facter)) + for k, v := range p.config.Facter { + facterVars = append(facterVars, fmt.Sprintf(p.guestOSTypeConfig.facterVarsFmt, k, v)) + } + + data := ExecuteTemplate{ + ClientCertPath: remoteClientCertPath, + ClientPrivateKeyPath: remoteClientPrivateKeyPath, + ExtraArguments: "", + FacterVars: strings.Join(facterVars, p.guestOSTypeConfig.facterVarsJoiner), + PuppetNode: p.config.PuppetNode, + PuppetServer: p.config.PuppetServer, + PuppetBinDir: p.config.PuppetBinDir, + Sudo: !p.config.PreventSudo, + WorkingDir: p.config.WorkingDir, + } + + p.config.ctx.Data = &data + _ExtraArguments, err := interpolate.Render(strings.Join(p.config.ExtraArguments, " "), &p.config.ctx) + if err != nil { + return err + } + data.ExtraArguments = _ExtraArguments + + command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx) + if err != nil { + return err + } + + if p.config.ElevatedUser != "" { + command, err = guestexec.GenerateElevatedRunner(command, p) + if err != nil { + return err + } + } + + cmd := &packersdk.RemoteCmd{ + Command: command, + } + + ui.Message(fmt.Sprintf("Running Puppet: %s", command)) + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + + if cmd.ExitStatus() != 0 && cmd.ExitStatus() != 2 && !p.config.IgnoreExitCodes { + return fmt.Errorf("Puppet exited with a non-zero exit status: %d", cmd.ExitStatus()) + } + + if p.config.CleanStagingDir { + if err := p.removeDir(ui, comm, p.config.StagingDir); err != nil { + return fmt.Errorf("Error removing staging directory: %s", err) + } + } + + return nil +} + +func (p *Provisioner) createDir(ui packersdk.Ui, comm packersdk.Communicator, dir string) error { + ui.Message(fmt.Sprintf("Creating directory: %s", dir)) + ctx := context.TODO() + + cmd := &packersdk.RemoteCmd{Command: p.guestCommands.CreateDir(dir)} + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + if cmd.ExitStatus() != 0 { + return fmt.Errorf("Non-zero exit status. See output above for more info.") + } + + // Chmod the directory to 0777 just so that we can access it as our user + cmd = &packersdk.RemoteCmd{Command: p.guestCommands.Chmod(dir, "0777")} + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + if cmd.ExitStatus() != 0 { + return fmt.Errorf("Non-zero exit status. See output above for more info.") + } + + return nil +} + +func (p *Provisioner) removeDir(ui packersdk.Ui, comm packersdk.Communicator, dir string) error { + ctx := context.TODO() + + cmd := &packersdk.RemoteCmd{Command: p.guestCommands.RemoveDir(dir)} + if err := cmd.RunWithUi(ctx, comm, ui); err != nil { + return err + } + + if cmd.ExitStatus() != 0 { + return fmt.Errorf("Non-zero exit status.") + } + + return nil +} + +func (p *Provisioner) uploadDirectory(ui packersdk.Ui, comm packersdk.Communicator, dst string, src string) error { + if err := p.createDir(ui, comm, dst); err != nil { + return err + } + + // Make sure there is a trailing "/" so that the directory isn't + // created on the other side. + if src[len(src)-1] != '/' { + src = src + "/" + } + + return comm.UploadDir(dst, src, nil) +} + +func (p *Provisioner) Communicator() packersdk.Communicator { + return p.communicator +} + +func (p *Provisioner) ElevatedUser() string { + return p.config.ElevatedUser +} + +func (p *Provisioner) ElevatedPassword() string { + // Replace ElevatedPassword for winrm users who used this feature + p.config.ctx.Data = p.generatedData + + elevatedPassword, _ := interpolate.Render(p.config.ElevatedPassword, &p.config.ctx) + + return elevatedPassword +} diff --git a/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server/provisioner.hcl2spec.go b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server/provisioner.hcl2spec.go new file mode 100644 index 000000000..26efe907c --- /dev/null +++ b/vendor/github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server/provisioner.hcl2spec.go @@ -0,0 +1,77 @@ +// Code generated by "packer-sdc mapstructure-to-hcl2"; DO NOT EDIT. + +package puppetserver + +import ( + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/zclconf/go-cty/cty" +) + +// FlatConfig is an auto-generated flat version of Config. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatConfig struct { + PackerBuildName *string `mapstructure:"packer_build_name" cty:"packer_build_name" hcl:"packer_build_name"` + PackerBuilderType *string `mapstructure:"packer_builder_type" cty:"packer_builder_type" hcl:"packer_builder_type"` + PackerCoreVersion *string `mapstructure:"packer_core_version" cty:"packer_core_version" hcl:"packer_core_version"` + PackerDebug *bool `mapstructure:"packer_debug" cty:"packer_debug" hcl:"packer_debug"` + PackerForce *bool `mapstructure:"packer_force" cty:"packer_force" hcl:"packer_force"` + PackerOnError *string `mapstructure:"packer_on_error" cty:"packer_on_error" hcl:"packer_on_error"` + PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` + PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` + CleanStagingDir *bool `mapstructure:"clean_staging_directory" cty:"clean_staging_directory" hcl:"clean_staging_directory"` + ClientCertPath *string `mapstructure:"client_cert_path" cty:"client_cert_path" hcl:"client_cert_path"` + ClientPrivateKeyPath *string `mapstructure:"client_private_key_path" cty:"client_private_key_path" hcl:"client_private_key_path"` + ExecuteCommand *string `mapstructure:"execute_command" cty:"execute_command" hcl:"execute_command"` + ExtraArguments []string `mapstructure:"extra_arguments" cty:"extra_arguments" hcl:"extra_arguments"` + Facter map[string]string `cty:"facter" hcl:"facter"` + GuestOSType *string `mapstructure:"guest_os_type" cty:"guest_os_type" hcl:"guest_os_type"` + IgnoreExitCodes *bool `mapstructure:"ignore_exit_codes" cty:"ignore_exit_codes" hcl:"ignore_exit_codes"` + PreventSudo *bool `mapstructure:"prevent_sudo" cty:"prevent_sudo" hcl:"prevent_sudo"` + PuppetBinDir *string `mapstructure:"puppet_bin_dir" cty:"puppet_bin_dir" hcl:"puppet_bin_dir"` + PuppetNode *string `mapstructure:"puppet_node" cty:"puppet_node" hcl:"puppet_node"` + PuppetServer *string `mapstructure:"puppet_server" cty:"puppet_server" hcl:"puppet_server"` + StagingDir *string `mapstructure:"staging_dir" cty:"staging_dir" hcl:"staging_dir"` + WorkingDir *string `mapstructure:"working_directory" cty:"working_directory" hcl:"working_directory"` + ElevatedUser *string `mapstructure:"elevated_user" cty:"elevated_user" hcl:"elevated_user"` + ElevatedPassword *string `mapstructure:"elevated_password" cty:"elevated_password" hcl:"elevated_password"` +} + +// FlatMapstructure returns a new FlatConfig. +// FlatConfig is an auto-generated flat version of Config. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*Config) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatConfig) +} + +// HCL2Spec returns the hcl spec of a Config. +// This spec is used by HCL to read the fields of Config. +// The decoded values from this spec will then be applied to a FlatConfig. +func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "packer_build_name": &hcldec.AttrSpec{Name: "packer_build_name", Type: cty.String, Required: false}, + "packer_builder_type": &hcldec.AttrSpec{Name: "packer_builder_type", Type: cty.String, Required: false}, + "packer_core_version": &hcldec.AttrSpec{Name: "packer_core_version", Type: cty.String, Required: false}, + "packer_debug": &hcldec.AttrSpec{Name: "packer_debug", Type: cty.Bool, Required: false}, + "packer_force": &hcldec.AttrSpec{Name: "packer_force", Type: cty.Bool, Required: false}, + "packer_on_error": &hcldec.AttrSpec{Name: "packer_on_error", Type: cty.String, Required: false}, + "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, + "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, + "clean_staging_directory": &hcldec.AttrSpec{Name: "clean_staging_directory", Type: cty.Bool, Required: false}, + "client_cert_path": &hcldec.AttrSpec{Name: "client_cert_path", Type: cty.String, Required: false}, + "client_private_key_path": &hcldec.AttrSpec{Name: "client_private_key_path", Type: cty.String, Required: false}, + "execute_command": &hcldec.AttrSpec{Name: "execute_command", Type: cty.String, Required: false}, + "extra_arguments": &hcldec.AttrSpec{Name: "extra_arguments", Type: cty.List(cty.String), Required: false}, + "facter": &hcldec.AttrSpec{Name: "facter", Type: cty.Map(cty.String), Required: false}, + "guest_os_type": &hcldec.AttrSpec{Name: "guest_os_type", Type: cty.String, Required: false}, + "ignore_exit_codes": &hcldec.AttrSpec{Name: "ignore_exit_codes", Type: cty.Bool, Required: false}, + "prevent_sudo": &hcldec.AttrSpec{Name: "prevent_sudo", Type: cty.Bool, Required: false}, + "puppet_bin_dir": &hcldec.AttrSpec{Name: "puppet_bin_dir", Type: cty.String, Required: false}, + "puppet_node": &hcldec.AttrSpec{Name: "puppet_node", Type: cty.String, Required: false}, + "puppet_server": &hcldec.AttrSpec{Name: "puppet_server", Type: cty.String, Required: false}, + "staging_dir": &hcldec.AttrSpec{Name: "staging_dir", Type: cty.String, Required: false}, + "working_directory": &hcldec.AttrSpec{Name: "working_directory", Type: cty.String, Required: false}, + "elevated_user": &hcldec.AttrSpec{Name: "elevated_user", Type: cty.String, Required: false}, + "elevated_password": &hcldec.AttrSpec{Name: "elevated_password", Type: cty.String, Required: false}, + } + return s +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 1827fb962..109f3e21f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -548,6 +548,10 @@ github.com/hashicorp/packer-plugin-parallels/builder/parallels/pvm github.com/hashicorp/packer-plugin-proxmox/builder/proxmox/clone github.com/hashicorp/packer-plugin-proxmox/builder/proxmox/common github.com/hashicorp/packer-plugin-proxmox/builder/proxmox/iso +# github.com/hashicorp/packer-plugin-puppet v0.0.1 +## explicit +github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-masterless +github.com/hashicorp/packer-plugin-puppet/provisioner/puppet-server # github.com/hashicorp/packer-plugin-qemu v0.0.1 ## explicit github.com/hashicorp/packer-plugin-qemu/builder/qemu diff --git a/website/data/docs-remote-plugins.json b/website/data/docs-remote-plugins.json index e6c63184d..cae3a723b 100644 --- a/website/data/docs-remote-plugins.json +++ b/website/data/docs-remote-plugins.json @@ -115,13 +115,6 @@ "repo": "hashicorp/packer-plugin-parallels", "version": "latest" }, - { - "title": "Chef", - "path": "chef", - "repo": "hashicorp/packer-plugin-chef", - "version": "latest", - "pluginTier": "community" - }, { "title": "Puppet", "path": "puppet",