packer-cn/provisioner/puppet-masterless/provisioner.go

311 lines
8.6 KiB
Go
Raw Normal View History

2013-08-01 20:05:23 -04:00
// This package 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
2013-08-01 20:05:23 -04:00
import (
"fmt"
"os"
"path/filepath"
"strings"
2015-05-27 17:50:20 -04:00
"github.com/mitchellh/packer/common"
"github.com/mitchellh/packer/helper/config"
"github.com/mitchellh/packer/packer"
"github.com/mitchellh/packer/template/interpolate"
2013-08-01 20:05:23 -04:00
)
type Config struct {
common.PackerConfig `mapstructure:",squash"`
2015-05-27 17:50:20 -04:00
ctx interpolate.Context
2013-08-01 20:05:23 -04:00
// The command used to execute Puppet.
ExecuteCommand string `mapstructure:"execute_command"`
2013-08-01 20:05:23 -04:00
// 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"`
2013-08-01 20:05:23 -04:00
// An array of local paths of modules to upload.
ModulePaths []string `mapstructure:"module_paths"`
2013-08-01 20:05:23 -04:00
// The main manifest file to apply to kick off the entire thing.
2013-08-01 20:05:23 -04:00
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.
2013-08-01 20:05:23 -04:00
PreventSudo bool `mapstructure:"prevent_sudo"`
// 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"`
2013-08-01 20:05:23 -04:00
}
type Provisioner struct {
config Config
2013-08-01 20:05:23 -04:00
}
type ExecuteTemplate struct {
WorkingDir string
2013-12-11 16:43:59 -05:00
FacterVars string
HieraConfigPath string
ModulePath string
ManifestFile string
ManifestDir string
Sudo bool
2013-08-01 20:05:23 -04:00
}
func (p *Provisioner) Prepare(raws ...interface{}) error {
2015-05-27 17:50:20 -04:00
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"execute_command",
},
},
}, raws...)
if err != nil {
return err
}
// Set some defaults
if p.config.ExecuteCommand == "" {
p.config.ExecuteCommand = "cd {{.WorkingDir}} && " +
"{{.FacterVars}} {{if .Sudo}} sudo -E {{end}}" +
"puppet apply --verbose --modulepath='{{.ModulePath}}' " +
"{{if ne .HieraConfigPath \"\"}}--hiera_config='{{.HieraConfigPath}}' {{end}}" +
"{{if ne .ManifestDir \"\"}}--manifestdir='{{.ManifestDir}}' {{end}}" +
"--detailed-exitcodes " +
"{{.ManifestFile}}"
2013-08-01 20:05:23 -04:00
}
if p.config.StagingDir == "" {
p.config.StagingDir = "/tmp/packer-puppet-masterless"
2013-08-01 20:05:23 -04:00
}
if p.config.WorkingDir == "" {
2015-01-10 18:29:01 -05:00
p.config.WorkingDir = p.config.StagingDir
}
// Validation
2015-05-27 17:50:20 -04:00
var errs *packer.MultiError
if p.config.HieraConfigPath != "" {
info, err := os.Stat(p.config.HieraConfigPath)
if err != nil {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("hiera_config_path is invalid: %s", err))
} else if info.IsDir() {
errs = packer.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 = packer.MultiErrorAppend(errs,
fmt.Errorf("manifest_dir is invalid: %s", err))
} else if !info.IsDir() {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("manifest_dir must point to a directory"))
}
}
if p.config.ManifestFile == "" {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("A manifest_file must be specified."))
} else {
2014-12-16 09:49:57 -05:00
_, err := os.Stat(p.config.ManifestFile)
if err != nil {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("manifest_file is invalid: %s", err))
2013-08-01 20:05:23 -04:00
}
}
for i, path := range p.config.ModulePaths {
info, err := os.Stat(path)
if err != nil {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("module_path[%d] is invalid: %s", i, err))
} else if !info.IsDir() {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("module_path[%d] must point to a directory", i))
}
}
if errs != nil && len(errs.Errors) > 0 {
return errs
2013-08-01 20:05:23 -04:00
}
return nil
}
func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
ui.Say("Provisioning with Puppet...")
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)
2013-08-01 20:05:23 -04:00
}
// 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)
}
}
2013-08-01 20:05:23 -04:00
// 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)
2013-08-01 20:05:23 -04:00
}
// Upload manifests
remoteManifestFile, err := p.uploadManifests(ui, comm)
2013-08-01 20:05:23 -04:00
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("FACTER_%s='%s'", k, v))
}
2013-08-01 20:05:23 -04:00
// Execute Puppet
2015-05-27 17:50:20 -04:00
p.config.ctx.Data = &ExecuteTemplate{
2013-12-11 16:43:59 -05:00
FacterVars: strings.Join(facterVars, " "),
HieraConfigPath: remoteHieraConfigPath,
ManifestDir: remoteManifestDir,
ManifestFile: remoteManifestFile,
ModulePath: strings.Join(modulePaths, ":"),
Sudo: !p.config.PreventSudo,
WorkingDir: p.config.WorkingDir,
2015-05-27 17:50:20 -04:00
}
command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
if err != nil {
return err
}
2013-08-01 20:05:23 -04:00
cmd := &packer.RemoteCmd{
Command: command,
}
2013-08-01 20:05:23 -04:00
ui.Message(fmt.Sprintf("Running Puppet: %s", command))
if err := cmd.StartWithUi(comm, ui); err != nil {
return err
}
if cmd.ExitStatus != 0 && cmd.ExitStatus != 2 {
return fmt.Errorf("Puppet exited with a non-zero exit status: %d", cmd.ExitStatus)
2013-08-01 20:05:23 -04:00
}
return nil
}
func (p *Provisioner) Cancel() {
// Just hard quit. It isn't a big deal if what we're doing keeps
// running on the other side.
os.Exit(0)
}
func (p *Provisioner) uploadHieraConfig(ui packer.Ui, comm packer.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 packer.Ui, comm packer.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)
2013-08-01 20:05:23 -04:00
}
// Upload the main manifest
f, err := os.Open(p.config.ManifestFile)
2013-08-01 20:05:23 -04:00
if err != nil {
return "", err
2013-08-01 20:05:23 -04:00
}
defer f.Close()
2013-08-01 20:05:23 -04:00
manifestFilename := filepath.Base(p.config.ManifestFile)
remoteManifestFile := fmt.Sprintf("%s/%s", remoteManifestsPath, manifestFilename)
if err := comm.Upload(remoteManifestFile, f, nil); err != nil {
return "", err
2013-08-01 20:05:23 -04:00
}
return remoteManifestFile, nil
2013-08-01 20:05:23 -04:00
}
func (p *Provisioner) createDir(ui packer.Ui, comm packer.Communicator, dir string) error {
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("mkdir -p '%s'", dir),
2013-08-01 20:05:23 -04:00
}
if err := cmd.StartWithUi(comm, ui); err != nil {
return err
}
2013-08-01 20:05:23 -04:00
if cmd.ExitStatus != 0 {
return fmt.Errorf("Non-zero exit status.")
2013-08-01 20:05:23 -04:00
}
return nil
}
func (p *Provisioner) uploadDirectory(ui packer.Ui, comm packer.Communicator, dst string, src string) error {
if err := p.createDir(ui, comm, dst); err != nil {
return err
2013-08-01 20:05:23 -04:00
}
// Make sure there is a trailing "/" so that the directory isn't
// created on the other side.
if src[len(src)-1] != '/' {
src = src + "/"
2013-08-01 20:05:23 -04:00
}
return comm.UploadDir(dst, src, nil)
2013-08-01 20:05:23 -04:00
}