packer-cn/provisioner/chef-solo/provisioner.go

612 lines
18 KiB
Go
Raw Normal View History

//go:generate mapstructure-to-hcl2 -type Config
// This package implements a provisioner for Packer that uses
// Chef to provision the remote machine, specifically with chef-solo (that is,
// without a Chef server).
package chefsolo
2013-07-05 00:26:48 -04:00
import (
"bytes"
"context"
"encoding/json"
2013-07-05 00:26:48 -04:00
"fmt"
"io/ioutil"
2013-07-05 00:26:48 -04:00
"os"
"path/filepath"
2013-07-05 00:26:48 -04:00
"strings"
2015-05-27 17:50:20 -04:00
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"
2020-12-17 16:29:25 -05:00
"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"
2013-07-05 00:26:48 -04:00
)
type guestOSTypeConfig struct {
executeCommand string
installCommand string
stagingDir string
}
var guestOSTypeConfigs = map[string]guestOSTypeConfig{
guestexec.UnixOSType: {
executeCommand: "{{if .Sudo}}sudo {{end}}chef-solo --no-color -c {{.ConfigPath}} -j {{.JsonPath}}",
installCommand: "curl -L https://omnitruck.chef.io/install.sh | {{if .Sudo}}sudo {{end}}bash -s --{{if .Version}} -v {{.Version}}{{end}}",
stagingDir: "/tmp/packer-chef-solo",
},
guestexec.WindowsOSType: {
executeCommand: "c:/opscode/chef/bin/chef-solo.bat --no-color -c {{.ConfigPath}} -j {{.JsonPath}}",
installCommand: "powershell.exe -Command \". { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; Install-Project{{if .Version}} -version {{.Version}}{{end}}\"",
stagingDir: "C:/Windows/Temp/packer-chef-solo",
},
}
type Config struct {
common.PackerConfig `mapstructure:",squash"`
ChefEnvironment string `mapstructure:"chef_environment"`
ChefLicense string `mapstructure:"chef_license"`
ConfigTemplate string `mapstructure:"config_template"`
CookbookPaths []string `mapstructure:"cookbook_paths"`
RolesPath string `mapstructure:"roles_path"`
DataBagsPath string `mapstructure:"data_bags_path"`
EncryptedDataBagSecretPath string `mapstructure:"encrypted_data_bag_secret_path"`
EnvironmentsPath string `mapstructure:"environments_path"`
ExecuteCommand string `mapstructure:"execute_command"`
InstallCommand string `mapstructure:"install_command"`
RemoteCookbookPaths []string `mapstructure:"remote_cookbook_paths"`
// HCL cannot be decoded into an interface so for HCL templates you must use the JsonString option,
// To be used with https://www.packer.io/docs/templates/hcl_templates/functions/encoding/jsonencode
// ref: https://github.com/hashicorp/hcl/issues/291#issuecomment-496347585
JsonString string `mapstructure:"json_string"`
// For JSON templates we keep the map[string]interface{}
Json map[string]interface{} `mapstructure:"json" mapstructure-to-hcl2:",skip"`
PreventSudo bool `mapstructure:"prevent_sudo"`
RunList []string `mapstructure:"run_list"`
SkipInstall bool `mapstructure:"skip_install"`
StagingDir string `mapstructure:"staging_directory"`
GuestOSType string `mapstructure:"guest_os_type"`
Version string `mapstructure:"version"`
2015-05-27 17:50:20 -04:00
ctx interpolate.Context
2013-07-05 00:26:48 -04:00
}
type Provisioner struct {
config Config
guestOSTypeConfig guestOSTypeConfig
guestCommands *guestexec.GuestCommands
2013-07-05 00:26:48 -04:00
}
type ConfigTemplate struct {
CookbookPaths string
DataBagsPath string
EncryptedDataBagSecretPath string
RolesPath string
EnvironmentsPath string
ChefEnvironment string
ChefLicense string
// Templates don't support boolean statements until Go 1.2. In the
// mean time, we do this.
// TODO(mitchellh): Remove when Go 1.2 is released
HasDataBagsPath bool
HasEncryptedDataBagSecretPath bool
HasRolesPath bool
HasEnvironmentsPath bool
}
type ExecuteTemplate struct {
ConfigPath string
JsonPath string
Sudo bool
}
type InstallChefTemplate struct {
Sudo bool
Version string
2013-07-05 00:26:48 -04:00
}
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 *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
2013-07-05 00:26:48 -04:00
func (p *Provisioner) Prepare(raws ...interface{}) error {
2015-05-27 17:50:20 -04:00
err := config.Decode(&p.config, &config.DecodeOpts{
PluginType: "chef-solo",
Interpolate: true,
InterpolateContext: &p.config.ctx,
2015-05-27 17:50:20 -04:00
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"execute_command",
"install_command",
},
},
}, raws...)
if err != nil {
return err
}
if p.config.JsonString != "" {
if err := json.Unmarshal([]byte(p.config.JsonString), &p.config.Json); err != nil {
return fmt.Errorf("Failed to unmarshal 'json_string': %s", err.Error())
}
}
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
2013-07-05 00:26:48 -04:00
}
if p.config.InstallCommand == "" {
p.config.InstallCommand = p.guestOSTypeConfig.installCommand
}
if p.config.RunList == nil {
p.config.RunList = make([]string, 0)
2013-07-05 00:26:48 -04:00
}
if p.config.StagingDir == "" {
p.config.StagingDir = p.guestOSTypeConfig.stagingDir
2013-07-05 00:26:48 -04:00
}
if p.config.SkipInstall == false && p.config.InstallCommand == p.guestOSTypeConfig.installCommand {
if p.config.ChefLicense == "" {
p.config.ChefLicense = "accept-silent"
}
}
var errs *packersdk.MultiError
if p.config.ConfigTemplate != "" {
fi, err := os.Stat(p.config.ConfigTemplate)
if err != nil {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Bad config template path: %s", err))
} else if fi.IsDir() {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Config template path must be a file: %s", err))
}
}
for _, path := range p.config.CookbookPaths {
2013-07-05 00:26:48 -04:00
pFileInfo, err := os.Stat(path)
2013-07-05 00:26:48 -04:00
if err != nil || !pFileInfo.IsDir() {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Bad cookbook path '%s': %s", path, err))
2013-07-05 00:26:48 -04:00
}
}
2013-09-18 17:14:18 -04:00
if p.config.RolesPath != "" {
pFileInfo, err := os.Stat(p.config.RolesPath)
2013-09-18 17:14:18 -04:00
if err != nil || !pFileInfo.IsDir() {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Bad roles path '%s': %s", p.config.RolesPath, err))
}
}
if p.config.DataBagsPath != "" {
pFileInfo, err := os.Stat(p.config.DataBagsPath)
2013-09-18 17:14:18 -04:00
if err != nil || !pFileInfo.IsDir() {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Bad data bags path '%s': %s", p.config.DataBagsPath, err))
}
}
2013-07-05 00:26:48 -04:00
if p.config.EncryptedDataBagSecretPath != "" {
pFileInfo, err := os.Stat(p.config.EncryptedDataBagSecretPath)
if err != nil || pFileInfo.IsDir() {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Bad encrypted data bag secret '%s': %s", p.config.EncryptedDataBagSecretPath, err))
}
}
if p.config.EnvironmentsPath != "" {
pFileInfo, err := os.Stat(p.config.EnvironmentsPath)
if err != nil || !pFileInfo.IsDir() {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Bad environments path '%s': %s", p.config.EnvironmentsPath, err))
}
}
jsonValid := true
for k, v := range p.config.Json {
p.config.Json[k], err = p.deepJsonFix(k, v)
if err != nil {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Error processing JSON: %s", err))
jsonValid = false
}
}
if jsonValid {
// Process the user variables within the JSON and set the JSON.
// Do this early so that we can validate and show errors.
p.config.Json, err = p.processJsonUserVars()
if err != nil {
errs = packersdk.MultiErrorAppend(
errs, fmt.Errorf("Error processing user variables in JSON: %s", err))
}
}
if errs != nil && len(errs.Errors) > 0 {
return errs
2013-07-05 00:26:48 -04:00
}
return nil
}
func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packersdk.Communicator, _ map[string]interface{}) error {
ui.Say("Provisioning with chef-solo")
if !p.config.SkipInstall {
if err := p.installChef(ui, comm, p.config.Version); err != nil {
return fmt.Errorf("Error installing Chef: %s", err)
}
2013-07-05 00:26:48 -04:00
}
if err := p.createDir(ui, comm, p.config.StagingDir); err != nil {
return fmt.Errorf("Error creating staging directory: %s", err)
2013-07-05 00:26:48 -04:00
}
cookbookPaths := make([]string, 0, len(p.config.CookbookPaths))
for i, path := range p.config.CookbookPaths {
targetPath := fmt.Sprintf("%s/cookbooks-%d", p.config.StagingDir, i)
if err := p.uploadDirectory(ui, comm, targetPath, path); err != nil {
return fmt.Errorf("Error uploading cookbooks: %s", err)
}
cookbookPaths = append(cookbookPaths, targetPath)
}
2013-09-18 17:14:18 -04:00
rolesPath := ""
if p.config.RolesPath != "" {
rolesPath = fmt.Sprintf("%s/roles", p.config.StagingDir)
if err := p.uploadDirectory(ui, comm, rolesPath, p.config.RolesPath); err != nil {
return fmt.Errorf("Error uploading roles: %s", err)
}
}
dataBagsPath := ""
if p.config.DataBagsPath != "" {
dataBagsPath = fmt.Sprintf("%s/data_bags", p.config.StagingDir)
if err := p.uploadDirectory(ui, comm, dataBagsPath, p.config.DataBagsPath); err != nil {
return fmt.Errorf("Error uploading data bags: %s", err)
}
}
encryptedDataBagSecretPath := ""
if p.config.EncryptedDataBagSecretPath != "" {
encryptedDataBagSecretPath = fmt.Sprintf("%s/encrypted_data_bag_secret", p.config.StagingDir)
if err := p.uploadFile(ui, comm, encryptedDataBagSecretPath, p.config.EncryptedDataBagSecretPath); err != nil {
return fmt.Errorf("Error uploading encrypted data bag secret: %s", err)
}
}
environmentsPath := ""
if p.config.EnvironmentsPath != "" {
environmentsPath = fmt.Sprintf("%s/environments", p.config.StagingDir)
if err := p.uploadDirectory(ui, comm, environmentsPath, p.config.EnvironmentsPath); err != nil {
return fmt.Errorf("Error uploading environments: %s", err)
}
}
configPath, err := p.createConfig(ui, comm, cookbookPaths, rolesPath, dataBagsPath, encryptedDataBagSecretPath, environmentsPath, p.config.ChefEnvironment, p.config.ChefLicense)
2013-07-05 00:26:48 -04:00
if err != nil {
return fmt.Errorf("Error creating Chef config file: %s", err)
2013-07-05 00:26:48 -04:00
}
jsonPath, err := p.createJson(ui, comm)
if err != nil {
return fmt.Errorf("Error creating JSON attributes: %s", err)
2013-07-05 00:26:48 -04:00
}
if err := p.executeChef(ui, comm, configPath, jsonPath); err != nil {
return fmt.Errorf("Error executing Chef: %s", err)
2013-07-05 00:26:48 -04:00
}
2013-07-05 00:26:48 -04:00
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) uploadFile(ui packersdk.Ui, comm packersdk.Communicator, dst string, src string) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
return comm.Upload(dst, f, nil)
}
func (p *Provisioner) createConfig(ui packersdk.Ui, comm packersdk.Communicator, localCookbooks []string, rolesPath string, dataBagsPath string, encryptedDataBagSecretPath string, environmentsPath string, chefEnvironment string, chefLicense string) (string, error) {
ui.Message("Creating configuration file 'solo.rb'")
cookbook_paths := make([]string, len(p.config.RemoteCookbookPaths)+len(localCookbooks))
for i, path := range p.config.RemoteCookbookPaths {
cookbook_paths[i] = fmt.Sprintf(`"%s"`, path)
2013-07-05 00:26:48 -04:00
}
for i, path := range localCookbooks {
i = len(p.config.RemoteCookbookPaths) + i
cookbook_paths[i] = fmt.Sprintf(`"%s"`, path)
}
2013-09-18 17:14:18 -04:00
// Read the template
tpl := DefaultConfigTemplate
if p.config.ConfigTemplate != "" {
f, err := os.Open(p.config.ConfigTemplate)
if err != nil {
return "", err
}
defer f.Close()
tplBytes, err := ioutil.ReadAll(f)
if err != nil {
return "", err
}
tpl = string(tplBytes)
}
2015-05-27 17:50:20 -04:00
p.config.ctx.Data = &ConfigTemplate{
CookbookPaths: strings.Join(cookbook_paths, ","),
RolesPath: rolesPath,
DataBagsPath: dataBagsPath,
EncryptedDataBagSecretPath: encryptedDataBagSecretPath,
EnvironmentsPath: environmentsPath,
HasRolesPath: rolesPath != "",
HasDataBagsPath: dataBagsPath != "",
HasEncryptedDataBagSecretPath: encryptedDataBagSecretPath != "",
HasEnvironmentsPath: environmentsPath != "",
ChefEnvironment: chefEnvironment,
ChefLicense: chefLicense,
2015-05-27 17:50:20 -04:00
}
configString, err := interpolate.Render(tpl, &p.config.ctx)
2013-07-05 00:26:48 -04:00
if err != nil {
return "", err
2013-07-05 00:26:48 -04:00
}
remotePath := filepath.ToSlash(filepath.Join(p.config.StagingDir, "solo.rb"))
if err := comm.Upload(remotePath, bytes.NewReader([]byte(configString)), nil); err != nil {
return "", err
2013-07-05 00:26:48 -04:00
}
return remotePath, nil
2013-07-05 00:26:48 -04:00
}
func (p *Provisioner) createJson(ui packersdk.Ui, comm packersdk.Communicator) (string, error) {
ui.Message("Creating JSON attribute file")
jsonData := make(map[string]interface{})
// Copy the configured JSON
for k, v := range p.config.Json {
jsonData[k] = v
}
// Set the run list if it was specified
if len(p.config.RunList) > 0 {
jsonData["run_list"] = p.config.RunList
2013-07-05 00:26:48 -04:00
}
jsonBytes, err := json.MarshalIndent(jsonData, "", " ")
if err != nil {
return "", err
2013-07-05 00:26:48 -04:00
}
// Upload the bytes
remotePath := filepath.ToSlash(filepath.Join(p.config.StagingDir, "node.json"))
if err := comm.Upload(remotePath, bytes.NewReader(jsonBytes), nil); err != nil {
return "", err
2013-07-05 00:26:48 -04:00
}
2013-07-05 00:26:48 -04:00
return remotePath, 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.")
}
2016-02-09 06:03:05 -05:00
// 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 {
2016-02-09 06:03:05 -05:00
return err
}
if cmd.ExitStatus() != 0 {
2016-02-09 06:03:05 -05:00
return fmt.Errorf("Non-zero exit status. See output above for more info.")
}
return nil
}
func (p *Provisioner) executeChef(ui packersdk.Ui, comm packersdk.Communicator, config string, json string) error {
2015-05-27 17:50:20 -04:00
p.config.ctx.Data = &ExecuteTemplate{
ConfigPath: config,
JsonPath: json,
Sudo: !p.config.PreventSudo,
2015-05-27 17:50:20 -04:00
}
command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
if err != nil {
return err
}
2013-07-05 00:26:48 -04:00
ui.Message(fmt.Sprintf("Executing Chef: %s", command))
2013-07-05 00:26:48 -04:00
cmd := &packersdk.RemoteCmd{
Command: command,
2013-07-05 00:26:48 -04:00
}
ctx := context.TODO()
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return err
2013-07-05 00:26:48 -04:00
}
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Non-zero exit status: %d", cmd.ExitStatus())
2013-07-05 00:26:48 -04:00
}
return nil
2013-07-05 00:26:48 -04:00
}
func (p *Provisioner) installChef(ui packersdk.Ui, comm packersdk.Communicator, version string) error {
ui.Message("Installing Chef...")
ctx := context.TODO()
2015-05-27 17:50:20 -04:00
p.config.ctx.Data = &InstallChefTemplate{
Sudo: !p.config.PreventSudo,
Version: version,
2015-05-27 17:50:20 -04:00
}
command, err := interpolate.Render(p.config.InstallCommand, &p.config.ctx)
2013-07-05 00:26:48 -04:00
if err != nil {
return err
}
cmd := &packersdk.RemoteCmd{Command: command}
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return err
}
if cmd.ExitStatus() != 0 {
return fmt.Errorf(
"Install script exited with non-zero exit status %d", cmd.ExitStatus())
2013-07-05 00:26:48 -04:00
}
2013-07-05 00:26:48 -04:00
return nil
}
func (p *Provisioner) deepJsonFix(key string, current interface{}) (interface{}, error) {
if current == nil {
return nil, nil
}
switch c := current.(type) {
case []interface{}:
val := make([]interface{}, len(c))
for i, v := range c {
var err error
val[i], err = p.deepJsonFix(fmt.Sprintf("%s[%d]", key, i), v)
if err != nil {
return nil, err
}
}
return val, nil
case []uint8:
return string(c), nil
case map[interface{}]interface{}:
val := make(map[string]interface{})
for k, v := range c {
ks, ok := k.(string)
if !ok {
return nil, fmt.Errorf("%s: key is not string", key)
}
var err error
val[ks], err = p.deepJsonFix(
fmt.Sprintf("%s.%s", key, ks), v)
if err != nil {
return nil, err
}
}
return val, nil
default:
return current, nil
}
}
2013-08-30 19:35:57 -04:00
func (p *Provisioner) processJsonUserVars() (map[string]interface{}, error) {
jsonBytes, err := json.Marshal(p.config.Json)
if err != nil {
// This really shouldn't happen since we literally just unmarshalled
panic(err)
}
// Copy the user variables so that we can restore them later, and
// make sure we make the quotes JSON-friendly in the user variables.
originalUserVars := make(map[string]string)
2015-05-27 17:50:20 -04:00
for k, v := range p.config.ctx.UserVariables {
2013-08-30 19:35:57 -04:00
originalUserVars[k] = v
}
// Make sure we reset them no matter what
defer func() {
2015-05-27 17:50:20 -04:00
p.config.ctx.UserVariables = originalUserVars
2013-08-30 19:35:57 -04:00
}()
// Make the current user variables JSON string safe.
2015-05-27 17:50:20 -04:00
for k, v := range p.config.ctx.UserVariables {
2013-08-30 19:35:57 -04:00
v = strings.Replace(v, `\`, `\\`, -1)
v = strings.Replace(v, `"`, `\"`, -1)
2015-05-27 17:50:20 -04:00
p.config.ctx.UserVariables[k] = v
2013-08-30 19:35:57 -04:00
}
// Process the bytes with the template processor
2015-05-27 17:50:20 -04:00
p.config.ctx.Data = nil
jsonBytesProcessed, err := interpolate.Render(string(jsonBytes), &p.config.ctx)
2013-08-30 19:35:57 -04:00
if err != nil {
return nil, err
}
var result map[string]interface{}
if err := json.Unmarshal([]byte(jsonBytesProcessed), &result); err != nil {
return nil, err
}
return result, nil
}
var DefaultConfigTemplate = `
chef_license "{{.ChefLicense}}"
cookbook_path [{{.CookbookPaths}}]
{{if .HasRolesPath}}
role_path "{{.RolesPath}}"
{{end}}
{{if .HasDataBagsPath}}
data_bag_path "{{.DataBagsPath}}"
{{end}}
{{if .HasEncryptedDataBagSecretPath}}
encrypted_data_bag_secret "{{.EncryptedDataBagSecretPath}}"
{{end}}
{{if .HasEnvironmentsPath}}
environment_path "{{.EnvironmentsPath}}"
environment "{{.ChefEnvironment}}"
{{end}}
`