github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/post-processor/shell-local/post-processor.go (about)

     1  package shell_local
     2  
     3  import (
     4  	"bufio"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"strings"
    10  
    11  	"github.com/mitchellh/packer/common"
    12  	"github.com/mitchellh/packer/helper/config"
    13  	"github.com/mitchellh/packer/packer"
    14  	"github.com/mitchellh/packer/template/interpolate"
    15  )
    16  
    17  type Config struct {
    18  	common.PackerConfig `mapstructure:",squash"`
    19  
    20  	// An inline script to execute. Multiple strings are all executed
    21  	// in the context of a single shell.
    22  	Inline []string
    23  
    24  	// The shebang value used when running inline scripts.
    25  	InlineShebang string `mapstructure:"inline_shebang"`
    26  
    27  	// The local path of the shell script to upload and execute.
    28  	Script string
    29  
    30  	// An array of multiple scripts to run.
    31  	Scripts []string
    32  
    33  	// An array of environment variables that will be injected before
    34  	// your command(s) are executed.
    35  	Vars []string `mapstructure:"environment_vars"`
    36  
    37  	// The command used to execute the script. The '{{ .Path }}' variable
    38  	// should be used to specify where the script goes, {{ .Vars }}
    39  	// can be used to inject the environment_vars into the environment.
    40  	ExecuteCommand string `mapstructure:"execute_command"`
    41  
    42  	ctx interpolate.Context
    43  }
    44  
    45  type PostProcessor struct {
    46  	config Config
    47  }
    48  
    49  type ExecuteCommandTemplate struct {
    50  	Vars   string
    51  	Script string
    52  }
    53  
    54  func (p *PostProcessor) Configure(raws ...interface{}) error {
    55  	err := config.Decode(&p.config, &config.DecodeOpts{
    56  		Interpolate:        true,
    57  		InterpolateContext: &p.config.ctx,
    58  		InterpolateFilter: &interpolate.RenderFilter{
    59  			Exclude: []string{
    60  				"execute_command",
    61  			},
    62  		},
    63  	}, raws...)
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	if p.config.ExecuteCommand == "" {
    69  		p.config.ExecuteCommand = `chmod +x "{{.Script}}"; {{.Vars}} "{{.Script}}"`
    70  	}
    71  
    72  	if p.config.Inline != nil && len(p.config.Inline) == 0 {
    73  		p.config.Inline = nil
    74  	}
    75  
    76  	if p.config.InlineShebang == "" {
    77  		p.config.InlineShebang = "/bin/sh -e"
    78  	}
    79  
    80  	if p.config.Scripts == nil {
    81  		p.config.Scripts = make([]string, 0)
    82  	}
    83  
    84  	if p.config.Vars == nil {
    85  		p.config.Vars = make([]string, 0)
    86  	}
    87  
    88  	var errs *packer.MultiError
    89  	if p.config.Script != "" && len(p.config.Scripts) > 0 {
    90  		errs = packer.MultiErrorAppend(errs,
    91  			errors.New("Only one of script or scripts can be specified."))
    92  	}
    93  
    94  	if p.config.Script != "" {
    95  		p.config.Scripts = []string{p.config.Script}
    96  	}
    97  
    98  	if len(p.config.Scripts) == 0 && p.config.Inline == nil {
    99  		errs = packer.MultiErrorAppend(errs,
   100  			errors.New("Either a script file or inline script must be specified."))
   101  	} else if len(p.config.Scripts) > 0 && p.config.Inline != nil {
   102  		errs = packer.MultiErrorAppend(errs,
   103  			errors.New("Only a script file or an inline script can be specified, not both."))
   104  	}
   105  
   106  	for _, path := range p.config.Scripts {
   107  		if _, err := os.Stat(path); err != nil {
   108  			errs = packer.MultiErrorAppend(errs,
   109  				fmt.Errorf("Bad script '%s': %s", path, err))
   110  		}
   111  	}
   112  
   113  	// Do a check for bad environment variables, such as '=foo', 'foobar'
   114  	for idx, kv := range p.config.Vars {
   115  		vs := strings.SplitN(kv, "=", 2)
   116  		if len(vs) != 2 || vs[0] == "" {
   117  			errs = packer.MultiErrorAppend(errs,
   118  				fmt.Errorf("Environment variable not in format 'key=value': %s", kv))
   119  		} else {
   120  			// Replace single quotes so they parse
   121  			vs[1] = strings.Replace(vs[1], "'", `'"'"'`, -1)
   122  
   123  			// Single quote env var values
   124  			p.config.Vars[idx] = fmt.Sprintf("%s='%s'", vs[0], vs[1])
   125  		}
   126  	}
   127  
   128  	if errs != nil && len(errs.Errors) > 0 {
   129  		return errs
   130  	}
   131  
   132  	return nil
   133  }
   134  
   135  func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, error) {
   136  
   137  	scripts := make([]string, len(p.config.Scripts))
   138  	copy(scripts, p.config.Scripts)
   139  
   140  	// If we have an inline script, then turn that into a temporary
   141  	// shell script and use that.
   142  	if p.config.Inline != nil {
   143  		tf, err := ioutil.TempFile("", "packer-shell")
   144  		if err != nil {
   145  			return nil, false, fmt.Errorf("Error preparing shell script: %s", err)
   146  		}
   147  		defer os.Remove(tf.Name())
   148  
   149  		// Set the path to the temporary file
   150  		scripts = append(scripts, tf.Name())
   151  
   152  		// Write our contents to it
   153  		writer := bufio.NewWriter(tf)
   154  		writer.WriteString(fmt.Sprintf("#!%s\n", p.config.InlineShebang))
   155  		for _, command := range p.config.Inline {
   156  			if _, err := writer.WriteString(command + "\n"); err != nil {
   157  				return nil, false, fmt.Errorf("Error preparing shell script: %s", err)
   158  			}
   159  		}
   160  
   161  		if err := writer.Flush(); err != nil {
   162  			return nil, false, fmt.Errorf("Error preparing shell script: %s", err)
   163  		}
   164  
   165  		tf.Close()
   166  	}
   167  
   168  	// Build our variables up by adding in the build name and builder type
   169  	envVars := make([]string, len(p.config.Vars)+2)
   170  	envVars[0] = fmt.Sprintf("PACKER_BUILD_NAME='%s'", p.config.PackerBuildName)
   171  	envVars[1] = fmt.Sprintf("PACKER_BUILDER_TYPE='%s'", p.config.PackerBuilderType)
   172  	copy(envVars[2:], p.config.Vars)
   173  
   174  	for _, script := range scripts {
   175  		// Flatten the environment variables
   176  		flattendVars := strings.Join(envVars, " ")
   177  
   178  		p.config.ctx.Data = &ExecuteCommandTemplate{
   179  			Vars:   flattendVars,
   180  			Script: script,
   181  		}
   182  
   183  		command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
   184  		if err != nil {
   185  			return nil, false, fmt.Errorf("Error processing command: %s", err)
   186  		}
   187  
   188  		ui.Say(fmt.Sprintf("Post processing with local shell script: %s", command))
   189  
   190  		comm := &Communicator{}
   191  
   192  		cmd := &packer.RemoteCmd{Command: command}
   193  
   194  		ui.Say(fmt.Sprintf(
   195  			"Executing local script: %s",
   196  			script))
   197  		if err := cmd.StartWithUi(comm, ui); err != nil {
   198  			return nil, false, fmt.Errorf(
   199  				"Error executing script: %s\n\n"+
   200  					"Please see output above for more information.",
   201  				script)
   202  		}
   203  		if cmd.ExitStatus != 0 {
   204  			return nil, false, fmt.Errorf(
   205  				"Erroneous exit code %d while executing script: %s\n\n"+
   206  					"Please see output above for more information.",
   207  				cmd.ExitStatus,
   208  				script)
   209  		}
   210  	}
   211  
   212  	return artifact, true, nil
   213  }