github.com/rsyabuta/packer@v1.1.4-0.20180119234903-5ef0c2280f0b/provisioner/powershell/provisioner.go (about)

     1  // This package implements a provisioner for Packer that executes
     2  // powershell scripts within the remote machine.
     3  package powershell
     4  
     5  import (
     6  	"bufio"
     7  	"bytes"
     8  	"encoding/xml"
     9  	"errors"
    10  	"fmt"
    11  	"io/ioutil"
    12  	"log"
    13  	"os"
    14  	"sort"
    15  	"strings"
    16  	"time"
    17  
    18  	"github.com/hashicorp/packer/common"
    19  	"github.com/hashicorp/packer/common/uuid"
    20  	"github.com/hashicorp/packer/helper/config"
    21  	"github.com/hashicorp/packer/packer"
    22  	"github.com/hashicorp/packer/template/interpolate"
    23  )
    24  
    25  var retryableSleep = 2 * time.Second
    26  
    27  type Config struct {
    28  	common.PackerConfig `mapstructure:",squash"`
    29  
    30  	// If true, the script contains binary and line endings will not be
    31  	// converted from Windows to Unix-style.
    32  	Binary bool
    33  
    34  	// An inline script to execute. Multiple strings are all executed
    35  	// in the context of a single shell.
    36  	Inline []string
    37  
    38  	// The local path of the powershell script to upload and execute.
    39  	Script string
    40  
    41  	// An array of multiple scripts to run.
    42  	Scripts []string
    43  
    44  	// An array of environment variables that will be injected before
    45  	// your command(s) are executed.
    46  	Vars []string `mapstructure:"environment_vars"`
    47  
    48  	// The remote path where the local powershell script will be uploaded to.
    49  	// This should be set to a writable file that is in a pre-existing directory.
    50  	RemotePath string `mapstructure:"remote_path"`
    51  
    52  	// The command used to execute the script. The '{{ .Path }}' variable
    53  	// should be used to specify where the script goes, {{ .Vars }}
    54  	// can be used to inject the environment_vars into the environment.
    55  	ExecuteCommand string `mapstructure:"execute_command"`
    56  
    57  	// The command used to execute the elevated script. The '{{ .Path }}' variable
    58  	// should be used to specify where the script goes, {{ .Vars }}
    59  	// can be used to inject the environment_vars into the environment.
    60  	ElevatedExecuteCommand string `mapstructure:"elevated_execute_command"`
    61  
    62  	// The timeout for retrying to start the process. Until this timeout
    63  	// is reached, if the provisioner can't start a process, it retries.
    64  	// This can be set high to allow for reboots.
    65  	StartRetryTimeout time.Duration `mapstructure:"start_retry_timeout"`
    66  
    67  	// This is used in the template generation to format environment variables
    68  	// inside the `ExecuteCommand` template.
    69  	EnvVarFormat string
    70  
    71  	// This is used in the template generation to format environment variables
    72  	// inside the `ElevatedExecuteCommand` template.
    73  	ElevatedEnvVarFormat string `mapstructure:"elevated_env_var_format"`
    74  
    75  	// Instructs the communicator to run the remote script as a
    76  	// Windows scheduled task, effectively elevating the remote
    77  	// user by impersonating a logged-in user
    78  	ElevatedUser     string `mapstructure:"elevated_user"`
    79  	ElevatedPassword string `mapstructure:"elevated_password"`
    80  
    81  	// Valid Exit Codes - 0 is not always the only valid error code!
    82  	// See http://www.symantec.com/connect/articles/windows-system-error-codes-exit-codes-description for examples
    83  	// such as 3010 - "The requested operation is successful. Changes will not be effective until the system is rebooted."
    84  	ValidExitCodes []int `mapstructure:"valid_exit_codes"`
    85  
    86  	ctx interpolate.Context
    87  }
    88  
    89  type Provisioner struct {
    90  	config       Config
    91  	communicator packer.Communicator
    92  }
    93  
    94  type ExecuteCommandTemplate struct {
    95  	Vars string
    96  	Path string
    97  }
    98  
    99  func (p *Provisioner) Prepare(raws ...interface{}) error {
   100  	err := config.Decode(&p.config, &config.DecodeOpts{
   101  		Interpolate:        true,
   102  		InterpolateContext: &p.config.ctx,
   103  		InterpolateFilter: &interpolate.RenderFilter{
   104  			Exclude: []string{
   105  				"execute_command",
   106  				"elevated_execute_command",
   107  			},
   108  		},
   109  	}, raws...)
   110  
   111  	if err != nil {
   112  		return err
   113  	}
   114  
   115  	if p.config.EnvVarFormat == "" {
   116  		p.config.EnvVarFormat = `$env:%s=\"%s\"; `
   117  	}
   118  
   119  	if p.config.ElevatedEnvVarFormat == "" {
   120  		p.config.ElevatedEnvVarFormat = `$env:%s="%s"; `
   121  	}
   122  
   123  	if p.config.ExecuteCommand == "" {
   124  		p.config.ExecuteCommand = `powershell -executionpolicy bypass "& { if (Test-Path variable:global:ProgressPreference){$ProgressPreference='SilentlyContinue'};{{.Vars}}&'{{.Path}}';exit $LastExitCode }"`
   125  	}
   126  
   127  	if p.config.ElevatedExecuteCommand == "" {
   128  		p.config.ElevatedExecuteCommand = `powershell -executionpolicy bypass "& { if (Test-Path variable:global:ProgressPreference){$ProgressPreference='SilentlyContinue'};. {{.Vars}}; &'{{.Path}}'; exit $LastExitCode }"`
   129  	}
   130  
   131  	if p.config.Inline != nil && len(p.config.Inline) == 0 {
   132  		p.config.Inline = nil
   133  	}
   134  
   135  	if p.config.StartRetryTimeout == 0 {
   136  		p.config.StartRetryTimeout = 5 * time.Minute
   137  	}
   138  
   139  	if p.config.RemotePath == "" {
   140  		uuid := uuid.TimeOrderedUUID()
   141  		p.config.RemotePath = fmt.Sprintf(`c:/Windows/Temp/script-%s.ps1`, uuid)
   142  	}
   143  
   144  	if p.config.Scripts == nil {
   145  		p.config.Scripts = make([]string, 0)
   146  	}
   147  
   148  	if p.config.Vars == nil {
   149  		p.config.Vars = make([]string, 0)
   150  	}
   151  
   152  	if p.config.ValidExitCodes == nil {
   153  		p.config.ValidExitCodes = []int{0}
   154  	}
   155  
   156  	var errs error
   157  	if p.config.Script != "" && len(p.config.Scripts) > 0 {
   158  		errs = packer.MultiErrorAppend(errs,
   159  			errors.New("Only one of script or scripts can be specified."))
   160  	}
   161  
   162  	if p.config.ElevatedUser != "" && p.config.ElevatedPassword == "" {
   163  		errs = packer.MultiErrorAppend(errs,
   164  			errors.New("Must supply an 'elevated_password' if 'elevated_user' provided"))
   165  	}
   166  
   167  	if p.config.ElevatedUser == "" && p.config.ElevatedPassword != "" {
   168  		errs = packer.MultiErrorAppend(errs,
   169  			errors.New("Must supply an 'elevated_user' if 'elevated_password' provided"))
   170  	}
   171  
   172  	if p.config.Script != "" {
   173  		p.config.Scripts = []string{p.config.Script}
   174  	}
   175  
   176  	if len(p.config.Scripts) == 0 && p.config.Inline == nil {
   177  		errs = packer.MultiErrorAppend(errs,
   178  			errors.New("Either a script file or inline script must be specified."))
   179  	} else if len(p.config.Scripts) > 0 && p.config.Inline != nil {
   180  		errs = packer.MultiErrorAppend(errs,
   181  			errors.New("Only a script file or an inline script can be specified, not both."))
   182  	}
   183  
   184  	for _, path := range p.config.Scripts {
   185  		if _, err := os.Stat(path); err != nil {
   186  			errs = packer.MultiErrorAppend(errs,
   187  				fmt.Errorf("Bad script '%s': %s", path, err))
   188  		}
   189  	}
   190  
   191  	// Do a check for bad environment variables, such as '=foo', 'foobar'
   192  	for _, kv := range p.config.Vars {
   193  		vs := strings.SplitN(kv, "=", 2)
   194  		if len(vs) != 2 || vs[0] == "" {
   195  			errs = packer.MultiErrorAppend(errs,
   196  				fmt.Errorf("Environment variable not in format 'key=value': %s", kv))
   197  		}
   198  	}
   199  
   200  	if errs != nil {
   201  		return errs
   202  	}
   203  
   204  	return nil
   205  }
   206  
   207  // Takes the inline scripts, concatenates them
   208  // into a temporary file and returns a string containing the location
   209  // of said file.
   210  func extractScript(p *Provisioner) (string, error) {
   211  	temp, err := ioutil.TempFile(os.TempDir(), "packer-powershell-provisioner")
   212  	if err != nil {
   213  		return "", err
   214  	}
   215  	defer temp.Close()
   216  	writer := bufio.NewWriter(temp)
   217  	for _, command := range p.config.Inline {
   218  		log.Printf("Found command: %s", command)
   219  		if _, err := writer.WriteString(command + "\n"); err != nil {
   220  			return "", fmt.Errorf("Error preparing powershell script: %s", err)
   221  		}
   222  	}
   223  
   224  	if err := writer.Flush(); err != nil {
   225  		return "", fmt.Errorf("Error preparing powershell script: %s", err)
   226  	}
   227  
   228  	return temp.Name(), nil
   229  }
   230  
   231  func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
   232  	ui.Say(fmt.Sprintf("Provisioning with Powershell..."))
   233  	p.communicator = comm
   234  
   235  	scripts := make([]string, len(p.config.Scripts))
   236  	copy(scripts, p.config.Scripts)
   237  
   238  	if p.config.Inline != nil {
   239  		temp, err := extractScript(p)
   240  		if err != nil {
   241  			ui.Error(fmt.Sprintf("Unable to extract inline scripts into a file: %s", err))
   242  		}
   243  		scripts = append(scripts, temp)
   244  	}
   245  
   246  	for _, path := range scripts {
   247  		ui.Say(fmt.Sprintf("Provisioning with powershell script: %s", path))
   248  
   249  		log.Printf("Opening %s for reading", path)
   250  		f, err := os.Open(path)
   251  		if err != nil {
   252  			return fmt.Errorf("Error opening powershell script: %s", err)
   253  		}
   254  		defer f.Close()
   255  
   256  		command, err := p.createCommandText()
   257  		if err != nil {
   258  			return fmt.Errorf("Error processing command: %s", err)
   259  		}
   260  
   261  		// Upload the file and run the command. Do this in the context of
   262  		// a single retryable function so that we don't end up with
   263  		// the case that the upload succeeded, a restart is initiated,
   264  		// and then the command is executed but the file doesn't exist
   265  		// any longer.
   266  		var cmd *packer.RemoteCmd
   267  		err = p.retryable(func() error {
   268  			if _, err := f.Seek(0, 0); err != nil {
   269  				return err
   270  			}
   271  			if err := comm.Upload(p.config.RemotePath, f, nil); err != nil {
   272  				return fmt.Errorf("Error uploading script: %s", err)
   273  			}
   274  
   275  			cmd = &packer.RemoteCmd{Command: command}
   276  			return cmd.StartWithUi(comm, ui)
   277  		})
   278  		if err != nil {
   279  			return err
   280  		}
   281  
   282  		// Close the original file since we copied it
   283  		f.Close()
   284  
   285  		// Check exit code against allowed codes (likely just 0)
   286  		validExitCode := false
   287  		for _, v := range p.config.ValidExitCodes {
   288  			if cmd.ExitStatus == v {
   289  				validExitCode = true
   290  			}
   291  		}
   292  		if !validExitCode {
   293  			return fmt.Errorf(
   294  				"Script exited with non-zero exit status: %d. Allowed exit codes are: %v",
   295  				cmd.ExitStatus, p.config.ValidExitCodes)
   296  		}
   297  	}
   298  
   299  	return nil
   300  }
   301  
   302  func (p *Provisioner) Cancel() {
   303  	// Just hard quit. It isn't a big deal if what we're doing keeps
   304  	// running on the other side.
   305  	os.Exit(0)
   306  }
   307  
   308  // retryable will retry the given function over and over until a
   309  // non-error is returned.
   310  func (p *Provisioner) retryable(f func() error) error {
   311  	startTimeout := time.After(p.config.StartRetryTimeout)
   312  	for {
   313  		var err error
   314  		if err = f(); err == nil {
   315  			return nil
   316  		}
   317  
   318  		// Create an error and log it
   319  		err = fmt.Errorf("Retryable error: %s", err)
   320  		log.Print(err.Error())
   321  
   322  		// Check if we timed out, otherwise we retry. It is safe to
   323  		// retry since the only error case above is if the command
   324  		// failed to START.
   325  		select {
   326  		case <-startTimeout:
   327  			return err
   328  		default:
   329  			time.Sleep(retryableSleep)
   330  		}
   331  	}
   332  }
   333  
   334  func (p *Provisioner) createFlattenedEnvVars(elevated bool) (flattened string) {
   335  	flattened = ""
   336  	envVars := make(map[string]string)
   337  
   338  	// Always available Packer provided env vars
   339  	envVars["PACKER_BUILD_NAME"] = p.config.PackerBuildName
   340  	envVars["PACKER_BUILDER_TYPE"] = p.config.PackerBuilderType
   341  	httpAddr := common.GetHTTPAddr()
   342  	if httpAddr != "" {
   343  		envVars["PACKER_HTTP_ADDR"] = httpAddr
   344  	}
   345  
   346  	// Split vars into key/value components
   347  	for _, envVar := range p.config.Vars {
   348  		keyValue := strings.SplitN(envVar, "=", 2)
   349  		envVars[keyValue[0]] = keyValue[1]
   350  	}
   351  
   352  	// Create a list of env var keys in sorted order
   353  	var keys []string
   354  	for k := range envVars {
   355  		keys = append(keys, k)
   356  	}
   357  	sort.Strings(keys)
   358  	format := p.config.EnvVarFormat
   359  	if elevated {
   360  		format = p.config.ElevatedEnvVarFormat
   361  	}
   362  
   363  	// Re-assemble vars using OS specific format pattern and flatten
   364  	for _, key := range keys {
   365  		flattened += fmt.Sprintf(format, key, envVars[key])
   366  	}
   367  	return
   368  }
   369  
   370  func (p *Provisioner) createCommandText() (command string, err error) {
   371  	// Return the interpolated command
   372  	if p.config.ElevatedUser == "" {
   373  		return p.createCommandTextNonPrivileged()
   374  	} else {
   375  		return p.createCommandTextPrivileged()
   376  	}
   377  }
   378  
   379  func (p *Provisioner) createCommandTextNonPrivileged() (command string, err error) {
   380  	// Create environment variables to set before executing the command
   381  	flattenedEnvVars := p.createFlattenedEnvVars(false)
   382  
   383  	p.config.ctx.Data = &ExecuteCommandTemplate{
   384  		Vars: flattenedEnvVars,
   385  		Path: p.config.RemotePath,
   386  	}
   387  	command, err = interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
   388  
   389  	if err != nil {
   390  		return "", fmt.Errorf("Error processing command: %s", err)
   391  	}
   392  
   393  	// Return the interpolated command
   394  	return command, nil
   395  }
   396  
   397  func (p *Provisioner) createCommandTextPrivileged() (command string, err error) {
   398  	// Can't double escape the env vars, lets create shiny new ones
   399  	flattenedEnvVars := p.createFlattenedEnvVars(true)
   400  	// Need to create a mini ps1 script containing all of the environment variables we want;
   401  	// we'll be dot-sourcing this later
   402  	envVarReader := strings.NewReader(flattenedEnvVars)
   403  	uuid := uuid.TimeOrderedUUID()
   404  	envVarPath := fmt.Sprintf(`${env:SYSTEMROOT}\Temp\packer-env-vars-%s.ps1`, uuid)
   405  	log.Printf("Uploading env vars to %s", envVarPath)
   406  	err = p.communicator.Upload(envVarPath, envVarReader, nil)
   407  	if err != nil {
   408  		return "", fmt.Errorf("Error preparing elevated powershell script: %s", err)
   409  	}
   410  
   411  	p.config.ctx.Data = &ExecuteCommandTemplate{
   412  		Path: p.config.RemotePath,
   413  		Vars: envVarPath,
   414  	}
   415  	command, err = interpolate.Render(p.config.ElevatedExecuteCommand, &p.config.ctx)
   416  	if err != nil {
   417  		return "", fmt.Errorf("Error processing command: %s", err)
   418  	}
   419  
   420  	// OK so we need an elevated shell runner to wrap our command, this is going to have its own path
   421  	// generate the script and update the command runner in the process
   422  	path, err := p.generateElevatedRunner(command)
   423  	if err != nil {
   424  		return "", fmt.Errorf("Error generating elevated runner: %s", err)
   425  	}
   426  
   427  	// Return the path to the elevated shell wrapper
   428  	command = fmt.Sprintf("powershell -executionpolicy bypass -file \"%s\"", path)
   429  
   430  	return command, err
   431  }
   432  
   433  func (p *Provisioner) generateElevatedRunner(command string) (uploadedPath string, err error) {
   434  	log.Printf("Building elevated command wrapper for: %s", command)
   435  
   436  	var buffer bytes.Buffer
   437  
   438  	// Output from the elevated command cannot be returned directly to
   439  	// the Packer console. In order to be able to view output from elevated
   440  	// commands and scripts an indirect approach is used by which the
   441  	// commands output is first redirected to file. The output file is then
   442  	// 'watched' by Packer while the elevated command is running and any
   443  	// content appearing in the file is written out to the console.
   444  	// Below the portion of command required to redirect output from the
   445  	// command to file is built and appended to the existing command string
   446  	taskName := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())
   447  	// Only use %ENVVAR% format for environment variables when setting
   448  	// the log file path; Do NOT use $env:ENVVAR format as it won't be
   449  	// expanded correctly in the elevatedTemplate
   450  	logFile := `%SYSTEMROOT%\Temp\` + taskName + ".out"
   451  	command += fmt.Sprintf(" > %s 2>&1", logFile)
   452  
   453  	// elevatedTemplate wraps the command in a single quoted XML text
   454  	// string so we need to escape characters considered 'special' in XML.
   455  	err = xml.EscapeText(&buffer, []byte(command))
   456  	if err != nil {
   457  		return "", fmt.Errorf("Error escaping characters special to XML in command %s: %s", command, err)
   458  	}
   459  	escapedCommand := buffer.String()
   460  	log.Printf("Command [%s] converted to [%s] for use in XML string", command, escapedCommand)
   461  
   462  	buffer.Reset()
   463  
   464  	// Generate command
   465  	err = elevatedTemplate.Execute(&buffer, elevatedOptions{
   466  		User:              p.config.ElevatedUser,
   467  		Password:          p.config.ElevatedPassword,
   468  		TaskName:          taskName,
   469  		TaskDescription:   "Packer elevated task",
   470  		LogFile:           logFile,
   471  		XMLEscapedCommand: escapedCommand,
   472  	})
   473  
   474  	if err != nil {
   475  		fmt.Printf("Error creating elevated template: %s", err)
   476  		return "", err
   477  	}
   478  	uuid := uuid.TimeOrderedUUID()
   479  	path := fmt.Sprintf(`${env:TEMP}\packer-elevated-shell-%s.ps1`, uuid)
   480  	log.Printf("Uploading elevated shell wrapper for command [%s] to [%s]", command, path)
   481  	err = p.communicator.Upload(path, &buffer, nil)
   482  	if err != nil {
   483  		return "", fmt.Errorf("Error preparing elevated powershell script: %s", err)
   484  	}
   485  
   486  	// CMD formatted Path required for this op
   487  	path = fmt.Sprintf("%s-%s.ps1", "%TEMP%\\packer-elevated-shell", uuid)
   488  	return path, err
   489  }