2019-10-14 10:43:59 -04:00
|
|
|
//go:generate mapstructure-to-hcl2 -type Config
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// This package implements a provisioner for Packer that executes powershell
|
|
|
|
// scripts within the remote machine.
|
2015-06-14 14:01:28 -04:00
|
|
|
package powershell
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2019-03-19 13:11:19 -04:00
|
|
|
"context"
|
2015-06-14 14:01:28 -04:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
2019-05-30 16:34:18 -04:00
|
|
|
"path/filepath"
|
2015-06-14 14:01:28 -04:00
|
|
|
"sort"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2019-12-17 05:25:56 -05:00
|
|
|
"github.com/hashicorp/hcl/v2/hcldec"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/common"
|
2019-04-08 11:57:27 -04:00
|
|
|
"github.com/hashicorp/packer/common/retry"
|
2019-03-14 06:57:54 -04:00
|
|
|
"github.com/hashicorp/packer/common/shell"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/common/uuid"
|
|
|
|
"github.com/hashicorp/packer/helper/config"
|
|
|
|
"github.com/hashicorp/packer/packer"
|
2018-12-12 09:45:00 -05:00
|
|
|
"github.com/hashicorp/packer/packer/tmp"
|
2018-12-07 10:30:50 -05:00
|
|
|
"github.com/hashicorp/packer/provisioner"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/template/interpolate"
|
2015-06-14 14:01:28 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
var retryableSleep = 2 * time.Second
|
|
|
|
|
2017-10-15 08:28:59 -04:00
|
|
|
var psEscape = strings.NewReplacer(
|
|
|
|
"$", "`$",
|
|
|
|
"\"", "`\"",
|
|
|
|
"`", "``",
|
|
|
|
"'", "`'",
|
|
|
|
)
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
type Config struct {
|
2019-03-14 06:57:54 -04:00
|
|
|
shell.Provisioner `mapstructure:",squash"`
|
2015-06-14 14:01:28 -04:00
|
|
|
|
2019-11-21 19:43:13 -05:00
|
|
|
shell.ProvisionerRemoteSpecific `mapstructure:",squash"`
|
|
|
|
|
2018-03-23 07:46:55 -04:00
|
|
|
// The remote path where the file containing the environment variables
|
2018-06-14 19:49:15 -04:00
|
|
|
// will be uploaded to. This should be set to a writable file that is in a
|
|
|
|
// pre-existing directory.
|
2018-03-23 07:46:55 -04:00
|
|
|
RemoteEnvVarPath string `mapstructure:"remote_env_var_path"`
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// The command used to execute the elevated script. The '{{ .Path }}'
|
|
|
|
// variable should be used to specify where the script goes, {{ .Vars }}
|
2015-06-14 14:01:28 -04:00
|
|
|
// can be used to inject the environment_vars into the environment.
|
|
|
|
ElevatedExecuteCommand string `mapstructure:"elevated_execute_command"`
|
|
|
|
|
2020-03-18 18:05:36 -04:00
|
|
|
// Whether to clean scripts up after executing the provisioner.
|
2020-04-08 00:44:00 -04:00
|
|
|
// Defaults to false. When true any script created by a non-elevated Powershell
|
|
|
|
// provisioner will be removed from the remote machine. Elevated scripts,
|
|
|
|
// along with the scheduled tasks, will always be removed regardless of the
|
|
|
|
// value set for `skip_clean`.
|
2020-03-18 18:05:36 -04:00
|
|
|
SkipClean bool `mapstructure:"skip_clean"`
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// The timeout for retrying to start the process. Until this timeout is
|
|
|
|
// reached, if the provisioner can't start a process, it retries. This
|
|
|
|
// can be set high to allow for reboots.
|
2015-06-14 14:01:28 -04:00
|
|
|
StartRetryTimeout time.Duration `mapstructure:"start_retry_timeout"`
|
|
|
|
|
|
|
|
// This is used in the template generation to format environment variables
|
|
|
|
// inside the `ElevatedExecuteCommand` template.
|
|
|
|
ElevatedEnvVarFormat string `mapstructure:"elevated_env_var_format"`
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// Instructs the communicator to run the remote script as a Windows
|
|
|
|
// scheduled task, effectively elevating the remote user by impersonating
|
|
|
|
// a logged-in user
|
2015-06-14 14:01:28 -04:00
|
|
|
ElevatedUser string `mapstructure:"elevated_user"`
|
|
|
|
ElevatedPassword string `mapstructure:"elevated_password"`
|
|
|
|
|
2019-05-23 08:10:41 -04:00
|
|
|
ExecutionPolicy ExecutionPolicy `mapstructure:"execution_policy"`
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
remoteCleanUpScriptPath string
|
|
|
|
|
2020-04-17 05:39:39 -04:00
|
|
|
// If set, sets PowerShell's [PSDebug mode](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-psdebug?view=powershell-7)
|
|
|
|
// in order to make script debugging easier. For instance, setting the
|
|
|
|
// value to 1 results in adding this to the execute command:
|
|
|
|
//
|
|
|
|
// ``` powershell
|
|
|
|
// Set-PSDebug -Trace 1
|
|
|
|
// ```
|
|
|
|
DebugMode int `mapstructure:"debug_mode"`
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
ctx interpolate.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
type Provisioner struct {
|
2019-07-11 12:37:59 -04:00
|
|
|
config Config
|
|
|
|
communicator packer.Communicator
|
2019-10-04 14:36:57 -04:00
|
|
|
generatedData map[string]interface{}
|
2018-03-14 20:19:17 -04:00
|
|
|
}
|
|
|
|
|
2019-05-23 08:10:41 -04:00
|
|
|
func (p *Provisioner) defaultExecuteCommand() string {
|
2019-05-23 10:42:44 -04:00
|
|
|
baseCmd := `& { if (Test-Path variable:global:ProgressPreference)` +
|
2020-06-09 11:41:07 -04:00
|
|
|
`{set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'};`
|
2020-04-17 05:39:39 -04:00
|
|
|
|
|
|
|
if p.config.DebugMode != 0 {
|
2020-05-20 15:25:19 -04:00
|
|
|
baseCmd += fmt.Sprintf(`Set-PsDebug -Trace %d;`, p.config.DebugMode)
|
2020-04-17 05:39:39 -04:00
|
|
|
}
|
2020-06-09 11:41:07 -04:00
|
|
|
|
|
|
|
baseCmd += `. {{.Vars}}; &'{{.Path}}'; exit $LastExitCode }`
|
2020-03-18 18:05:36 -04:00
|
|
|
|
2019-05-23 11:05:37 -04:00
|
|
|
if p.config.ExecutionPolicy == ExecutionPolicyNone {
|
2019-05-23 10:42:44 -04:00
|
|
|
return baseCmd
|
|
|
|
}
|
2020-03-18 18:05:36 -04:00
|
|
|
|
|
|
|
return fmt.Sprintf(`powershell -executionpolicy %s "%s"`, p.config.ExecutionPolicy, baseCmd)
|
2019-05-23 08:10:41 -04:00
|
|
|
}
|
2020-03-18 18:05:36 -04:00
|
|
|
|
2019-12-17 05:25:56 -05:00
|
|
|
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
|
2019-05-23 08:10:41 -04:00
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
func (p *Provisioner) Prepare(raws ...interface{}) error {
|
|
|
|
err := config.Decode(&p.config, &config.DecodeOpts{
|
2015-06-22 15:26:54 -04:00
|
|
|
Interpolate: true,
|
|
|
|
InterpolateContext: &p.config.ctx,
|
2015-06-14 14:01:28 -04:00
|
|
|
InterpolateFilter: &interpolate.RenderFilter{
|
|
|
|
Exclude: []string{
|
|
|
|
"execute_command",
|
2017-09-14 13:46:40 -04:00
|
|
|
"elevated_execute_command",
|
2015-06-14 14:01:28 -04:00
|
|
|
},
|
|
|
|
},
|
2019-05-23 08:10:41 -04:00
|
|
|
DecodeHooks: append(config.DefaultDecodeHookFuncs, StringToExecutionPolicyHook),
|
2015-06-14 14:01:28 -04:00
|
|
|
}, raws...)
|
2018-03-14 20:19:17 -04:00
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
if err != nil {
|
2018-09-10 19:48:42 -04:00
|
|
|
return err
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.EnvVarFormat == "" {
|
2017-10-25 08:50:58 -04:00
|
|
|
p.config.EnvVarFormat = `$env:%s="%s"; `
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.ElevatedEnvVarFormat == "" {
|
2016-07-04 18:44:33 -04:00
|
|
|
p.config.ElevatedEnvVarFormat = `$env:%s="%s"; `
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.ExecuteCommand == "" {
|
2019-05-23 08:10:41 -04:00
|
|
|
p.config.ExecuteCommand = p.defaultExecuteCommand()
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.ElevatedExecuteCommand == "" {
|
2019-05-23 08:10:41 -04:00
|
|
|
p.config.ElevatedExecuteCommand = p.defaultExecuteCommand()
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.Inline != nil && len(p.config.Inline) == 0 {
|
|
|
|
p.config.Inline = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.StartRetryTimeout == 0 {
|
|
|
|
p.config.StartRetryTimeout = 5 * time.Minute
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.RemotePath == "" {
|
2017-08-22 17:03:28 -04:00
|
|
|
uuid := uuid.TimeOrderedUUID()
|
|
|
|
p.config.RemotePath = fmt.Sprintf(`c:/Windows/Temp/script-%s.ps1`, uuid)
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
2018-03-23 07:46:55 -04:00
|
|
|
if p.config.RemoteEnvVarPath == "" {
|
|
|
|
uuid := uuid.TimeOrderedUUID()
|
|
|
|
p.config.RemoteEnvVarPath = fmt.Sprintf(`c:/Windows/Temp/packer-ps-env-vars-%s.ps1`, uuid)
|
|
|
|
}
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
if p.config.Scripts == nil {
|
|
|
|
p.config.Scripts = make([]string, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.Vars == nil {
|
|
|
|
p.config.Vars = make([]string, 0)
|
|
|
|
}
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
p.config.remoteCleanUpScriptPath = fmt.Sprintf(`c:/Windows/Temp/packer-cleanup-%s.ps1`, uuid.TimeOrderedUUID())
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
var errs error
|
|
|
|
if p.config.Script != "" && len(p.config.Scripts) > 0 {
|
|
|
|
errs = packer.MultiErrorAppend(errs,
|
|
|
|
errors.New("Only one of script or scripts can be specified."))
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.ElevatedUser == "" && p.config.ElevatedPassword != "" {
|
|
|
|
errs = packer.MultiErrorAppend(errs,
|
|
|
|
errors.New("Must supply an 'elevated_user' if 'elevated_password' provided"))
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.config.Script != "" {
|
|
|
|
p.config.Scripts = []string{p.config.Script}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(p.config.Scripts) == 0 && p.config.Inline == nil {
|
|
|
|
errs = packer.MultiErrorAppend(errs,
|
|
|
|
errors.New("Either a script file or inline script must be specified."))
|
|
|
|
} else if len(p.config.Scripts) > 0 && p.config.Inline != nil {
|
|
|
|
errs = packer.MultiErrorAppend(errs,
|
|
|
|
errors.New("Only a script file or an inline script can be specified, not both."))
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, path := range p.config.Scripts {
|
|
|
|
if _, err := os.Stat(path); err != nil {
|
|
|
|
errs = packer.MultiErrorAppend(errs,
|
|
|
|
fmt.Errorf("Bad script '%s': %s", path, err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do a check for bad environment variables, such as '=foo', 'foobar'
|
|
|
|
for _, kv := range p.config.Vars {
|
|
|
|
vs := strings.SplitN(kv, "=", 2)
|
|
|
|
if len(vs) != 2 || vs[0] == "" {
|
|
|
|
errs = packer.MultiErrorAppend(errs,
|
|
|
|
fmt.Errorf("Environment variable not in format 'key=value': %s", kv))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-07 04:32:58 -04:00
|
|
|
if p.config.ExecutionPolicy > 7 {
|
|
|
|
errs = packer.MultiErrorAppend(errs, fmt.Errorf(`Invalid execution `+
|
|
|
|
`policy provided. Please supply one of: "bypass", "allsigned",`+
|
|
|
|
` "default", "remotesigned", "restricted", "undefined", `+
|
|
|
|
`"unrestricted", "none".`))
|
|
|
|
}
|
|
|
|
|
2020-04-17 05:39:39 -04:00
|
|
|
if !(p.config.DebugMode >= 0 && p.config.DebugMode <= 2) {
|
|
|
|
errs = packer.MultiErrorAppend(errs, fmt.Errorf("%d is an invalid Trace level for `debug_mode`; valid values are 0, 1, and 2", p.config.DebugMode))
|
|
|
|
}
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
if errs != nil {
|
|
|
|
return errs
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// Takes the inline scripts, concatenates them into a temporary file and
|
|
|
|
// returns a string containing the location of said file.
|
2015-06-14 14:01:28 -04:00
|
|
|
func extractScript(p *Provisioner) (string, error) {
|
2018-12-12 09:45:00 -05:00
|
|
|
temp, err := tmp.File("powershell-provisioner")
|
2015-06-14 14:01:28 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer temp.Close()
|
|
|
|
writer := bufio.NewWriter(temp)
|
|
|
|
for _, command := range p.config.Inline {
|
|
|
|
log.Printf("Found command: %s", command)
|
|
|
|
if _, err := writer.WriteString(command + "\n"); err != nil {
|
2017-09-06 14:59:25 -04:00
|
|
|
return "", fmt.Errorf("Error preparing powershell script: %s", err)
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := writer.Flush(); err != nil {
|
2017-09-06 14:59:25 -04:00
|
|
|
return "", fmt.Errorf("Error preparing powershell script: %s", err)
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return temp.Name(), nil
|
|
|
|
}
|
|
|
|
|
2019-12-12 13:59:44 -05:00
|
|
|
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, generatedData map[string]interface{}) error {
|
2015-06-14 14:01:28 -04:00
|
|
|
ui.Say(fmt.Sprintf("Provisioning with Powershell..."))
|
|
|
|
p.communicator = comm
|
2019-12-12 19:42:53 -05:00
|
|
|
p.generatedData = generatedData
|
2019-07-11 12:37:59 -04:00
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
scripts := make([]string, len(p.config.Scripts))
|
|
|
|
copy(scripts, p.config.Scripts)
|
|
|
|
|
|
|
|
if p.config.Inline != nil {
|
|
|
|
temp, err := extractScript(p)
|
|
|
|
if err != nil {
|
|
|
|
ui.Error(fmt.Sprintf("Unable to extract inline scripts into a file: %s", err))
|
|
|
|
}
|
|
|
|
scripts = append(scripts, temp)
|
2018-04-25 19:17:13 -04:00
|
|
|
// Remove temp script containing the inline commands when done
|
|
|
|
defer os.Remove(temp)
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
// every provisioner run will only have one env var script file so lets add it first
|
|
|
|
uploadedScripts := []string{p.config.RemoteEnvVarPath}
|
2015-06-14 14:01:28 -04:00
|
|
|
for _, path := range scripts {
|
2017-09-06 14:59:25 -04:00
|
|
|
ui.Say(fmt.Sprintf("Provisioning with powershell script: %s", path))
|
2015-06-14 14:01:28 -04:00
|
|
|
|
|
|
|
log.Printf("Opening %s for reading", path)
|
2019-05-30 16:34:18 -04:00
|
|
|
fi, err := os.Stat(path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error stating powershell script: %s", err)
|
|
|
|
}
|
|
|
|
if strings.HasSuffix(p.config.RemotePath, `\`) {
|
|
|
|
// path is a directory
|
|
|
|
p.config.RemotePath += filepath.Base((fi).Name())
|
|
|
|
}
|
2015-06-14 14:01:28 -04:00
|
|
|
f, err := os.Open(path)
|
|
|
|
if err != nil {
|
2017-09-06 14:59:25 -04:00
|
|
|
return fmt.Errorf("Error opening powershell script: %s", err)
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
command, err := p.createCommandText()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error processing command: %s", err)
|
|
|
|
}
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// Upload the file and run the command. Do this in the context of a
|
|
|
|
// single retryable function so that we don't end up with the case
|
|
|
|
// that the upload succeeded, a restart is initiated, and then the
|
|
|
|
// command is executed but the file doesn't exist any longer.
|
2015-06-14 14:01:28 -04:00
|
|
|
var cmd *packer.RemoteCmd
|
2019-05-17 18:28:34 -04:00
|
|
|
err = retry.Config{StartTimeout: p.config.StartRetryTimeout}.Run(ctx, func(ctx context.Context) error {
|
2015-06-14 14:01:28 -04:00
|
|
|
if _, err := f.Seek(0, 0); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-05-30 16:34:18 -04:00
|
|
|
if err := comm.Upload(p.config.RemotePath, f, &fi); err != nil {
|
2015-06-14 14:01:28 -04:00
|
|
|
return fmt.Errorf("Error uploading script: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd = &packer.RemoteCmd{Command: command}
|
2019-04-03 11:14:55 -04:00
|
|
|
return cmd.RunWithUi(ctx, comm, ui)
|
2015-06-14 14:01:28 -04:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close the original file since we copied it
|
|
|
|
f.Close()
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
// Record every other uploaded script file so we can clean it up later
|
|
|
|
uploadedScripts = append(uploadedScripts, p.config.RemotePath)
|
2019-05-23 08:10:41 -04:00
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
log.Printf("%s returned with exit code %d", p.config.RemotePath, cmd.ExitStatus())
|
2019-04-03 11:14:55 -04:00
|
|
|
if err := p.config.ValidExitCode(cmd.ExitStatus()); err != nil {
|
2019-03-14 07:47:22 -04:00
|
|
|
return err
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
2020-03-19 19:50:58 -04:00
|
|
|
}
|
2020-03-18 18:05:36 -04:00
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
if p.config.SkipClean {
|
|
|
|
return nil
|
|
|
|
}
|
2020-03-18 18:05:36 -04:00
|
|
|
|
2020-05-14 10:14:01 -04:00
|
|
|
err := retry.Config{StartTimeout: time.Minute, RetryDelay: func() time.Duration { return 10 * time.Second }}.Run(ctx, func(ctx context.Context) error {
|
2020-03-19 19:50:58 -04:00
|
|
|
command, err := p.createRemoteCleanUpCommand(uploadedScripts)
|
|
|
|
if err != nil {
|
2020-05-14 10:14:01 -04:00
|
|
|
log.Printf("failed to upload the remote cleanup script: %q", err)
|
2020-03-19 19:50:58 -04:00
|
|
|
return err
|
2020-03-18 18:05:36 -04:00
|
|
|
}
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
cmd := &packer.RemoteCmd{Command: command}
|
|
|
|
return cmd.RunWithUi(ctx, comm, ui)
|
|
|
|
})
|
|
|
|
if err != nil {
|
2020-05-14 10:14:01 -04:00
|
|
|
log.Printf("remote cleanup script failed to upload; skipping the removal of temporary files: %s; ", strings.Join(uploadedScripts, ","))
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
// createRemoteCleanUpCommand will generated a powershell script that will remove remote files;
|
|
|
|
// returning a command that can be executed remotely to do the cleanup.
|
|
|
|
func (p *Provisioner) createRemoteCleanUpCommand(remoteFiles []string) (string, error) {
|
|
|
|
if len(remoteFiles) == 0 {
|
|
|
|
return "", fmt.Errorf("no remoteFiles provided for cleanup")
|
2020-03-18 18:05:36 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
var b strings.Builder
|
|
|
|
// This script should self destruct.
|
2020-03-19 19:50:58 -04:00
|
|
|
remotePath := p.config.remoteCleanUpScriptPath
|
|
|
|
remoteFiles = append(remoteFiles, remotePath)
|
|
|
|
for _, filename := range remoteFiles {
|
2020-05-14 10:14:01 -04:00
|
|
|
fmt.Fprintf(&b, "if (Test-Path %[1]s) {Remove-Item %[1]s}\n", filename)
|
2020-03-18 18:05:36 -04:00
|
|
|
}
|
|
|
|
|
2020-03-19 19:50:58 -04:00
|
|
|
if err := p.communicator.Upload(remotePath, strings.NewReader(b.String()), nil); err != nil {
|
|
|
|
return "", fmt.Errorf("clean up script %q failed to upload: %s", remotePath, err)
|
2020-03-18 18:05:36 -04:00
|
|
|
}
|
|
|
|
|
2020-05-25 05:54:27 -04:00
|
|
|
data := p.generatedData
|
|
|
|
data["Path"] = remotePath
|
|
|
|
data["Vars"] = p.config.RemoteEnvVarPath
|
|
|
|
p.config.ctx.Data = data
|
|
|
|
|
2020-03-18 18:05:36 -04:00
|
|
|
p.config.ctx.Data = data
|
|
|
|
return interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
|
|
|
|
}
|
|
|
|
|
2018-06-14 19:49:15 -04:00
|
|
|
// Environment variables required within the remote environment are uploaded
|
|
|
|
// within a PS script and then enabled by 'dot sourcing' the script
|
|
|
|
// immediately prior to execution of the main command
|
2018-03-23 07:46:55 -04:00
|
|
|
func (p *Provisioner) prepareEnvVars(elevated bool) (err error) {
|
2018-06-14 19:49:15 -04:00
|
|
|
// Collate all required env vars into a plain string with required
|
|
|
|
// formatting applied
|
2017-10-25 08:50:58 -04:00
|
|
|
flattenedEnvVars := p.createFlattenedEnvVars(elevated)
|
2018-06-14 19:49:15 -04:00
|
|
|
// Create a powershell script on the target build fs containing the
|
|
|
|
// flattened env vars
|
2018-03-23 07:46:55 -04:00
|
|
|
err = p.uploadEnvVars(flattenedEnvVars)
|
2017-10-25 08:50:58 -04:00
|
|
|
if err != nil {
|
2018-03-23 07:46:55 -04:00
|
|
|
return err
|
2017-10-25 08:50:58 -04:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-01-23 05:50:53 -05:00
|
|
|
func (p *Provisioner) createFlattenedEnvVars(elevated bool) (flattened string) {
|
2015-06-14 14:01:28 -04:00
|
|
|
flattened = ""
|
|
|
|
envVars := make(map[string]string)
|
|
|
|
|
|
|
|
// Always available Packer provided env vars
|
|
|
|
envVars["PACKER_BUILD_NAME"] = p.config.PackerBuildName
|
|
|
|
envVars["PACKER_BUILDER_TYPE"] = p.config.PackerBuilderType
|
2018-03-08 18:14:57 -05:00
|
|
|
|
2018-12-05 19:39:46 -05:00
|
|
|
// expose ip address variables
|
2020-05-19 05:49:48 -04:00
|
|
|
httpAddr := p.generatedData["PackerHTTPAddr"]
|
|
|
|
if httpAddr != nil && httpAddr != common.HttpAddrNotImplemented {
|
|
|
|
envVars["PACKER_HTTP_ADDR"] = httpAddr.(string)
|
2017-01-17 20:17:36 -05:00
|
|
|
}
|
2020-05-19 05:49:48 -04:00
|
|
|
httpIP := p.generatedData["PackerHTTPIP"]
|
|
|
|
if httpIP != nil && httpIP != common.HttpIPNotImplemented {
|
|
|
|
envVars["PACKER_HTTP_IP"] = httpIP.(string)
|
2018-12-05 19:39:46 -05:00
|
|
|
}
|
2020-05-19 05:49:48 -04:00
|
|
|
httpPort := p.generatedData["PackerHTTPPort"]
|
|
|
|
if httpPort != nil && httpPort != common.HttpPortNotImplemented {
|
|
|
|
envVars["PACKER_HTTP_PORT"] = httpPort.(string)
|
2018-12-05 19:39:46 -05:00
|
|
|
}
|
2018-03-08 18:14:57 -05:00
|
|
|
|
2018-03-14 20:19:17 -04:00
|
|
|
// interpolate environment variables
|
2019-07-11 12:37:59 -04:00
|
|
|
p.config.ctx.Data = p.generatedData
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
// Split vars into key/value components
|
|
|
|
for _, envVar := range p.config.Vars {
|
2018-03-15 12:44:22 -04:00
|
|
|
envVar, err := interpolate.Render(envVar, &p.config.ctx)
|
2018-03-14 20:19:17 -04:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2016-12-27 19:33:16 -05:00
|
|
|
keyValue := strings.SplitN(envVar, "=", 2)
|
2017-10-15 08:28:59 -04:00
|
|
|
// Escape chars special to PS in each env var value
|
|
|
|
escapedEnvVarValue := psEscape.Replace(keyValue[1])
|
|
|
|
if escapedEnvVarValue != keyValue[1] {
|
|
|
|
log.Printf("Env var %s converted to %s after escaping chars special to PS", keyValue[1],
|
|
|
|
escapedEnvVarValue)
|
|
|
|
}
|
|
|
|
envVars[keyValue[0]] = escapedEnvVarValue
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create a list of env var keys in sorted order
|
|
|
|
var keys []string
|
|
|
|
for k := range envVars {
|
|
|
|
keys = append(keys, k)
|
|
|
|
}
|
|
|
|
sort.Strings(keys)
|
|
|
|
format := p.config.EnvVarFormat
|
|
|
|
if elevated {
|
|
|
|
format = p.config.ElevatedEnvVarFormat
|
|
|
|
}
|
|
|
|
|
|
|
|
// Re-assemble vars using OS specific format pattern and flatten
|
|
|
|
for _, key := range keys {
|
|
|
|
flattened += fmt.Sprintf(format, key, envVars[key])
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-03-23 07:46:55 -04:00
|
|
|
func (p *Provisioner) uploadEnvVars(flattenedEnvVars string) (err error) {
|
2019-04-08 11:57:27 -04:00
|
|
|
ctx := context.TODO()
|
2018-06-14 19:09:50 -04:00
|
|
|
// Upload all env vars to a powershell script on the target build file
|
2018-06-14 19:49:15 -04:00
|
|
|
// system. Do this in the context of a single retryable function so that
|
|
|
|
// we gracefully handle any errors created by transient conditions such as
|
|
|
|
// a system restart
|
2017-10-25 08:50:58 -04:00
|
|
|
envVarReader := strings.NewReader(flattenedEnvVars)
|
2018-03-23 07:46:55 -04:00
|
|
|
log.Printf("Uploading env vars to %s", p.config.RemoteEnvVarPath)
|
2019-04-08 11:57:27 -04:00
|
|
|
err = retry.Config{StartTimeout: p.config.StartRetryTimeout}.Run(ctx, func(context.Context) error {
|
2018-06-14 19:09:50 -04:00
|
|
|
if err := p.communicator.Upload(p.config.RemoteEnvVarPath, envVarReader, nil); err != nil {
|
|
|
|
return fmt.Errorf("Error uploading ps script containing env vars: %s", err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
})
|
2017-10-25 08:50:58 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
func (p *Provisioner) createCommandText() (command string, err error) {
|
2016-07-04 18:44:33 -04:00
|
|
|
// Return the interpolated command
|
|
|
|
if p.config.ElevatedUser == "" {
|
|
|
|
return p.createCommandTextNonPrivileged()
|
|
|
|
} else {
|
|
|
|
return p.createCommandTextPrivileged()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) createCommandTextNonPrivileged() (command string, err error) {
|
2018-06-14 19:49:15 -04:00
|
|
|
// Prepare everything needed to enable the required env vars within the
|
|
|
|
// remote environment
|
2018-03-23 07:46:55 -04:00
|
|
|
err = p.prepareEnvVars(false)
|
2017-10-25 08:50:58 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2017-01-23 05:50:53 -05:00
|
|
|
|
2019-10-04 14:36:57 -04:00
|
|
|
ctxData := p.generatedData
|
|
|
|
ctxData["Path"] = p.config.RemotePath
|
|
|
|
ctxData["Vars"] = p.config.RemoteEnvVarPath
|
|
|
|
p.config.ctx.Data = ctxData
|
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
command, err = interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
|
2016-07-04 18:44:33 -04:00
|
|
|
|
2015-06-14 14:01:28 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("Error processing command: %s", err)
|
|
|
|
}
|
|
|
|
|
2017-01-26 20:32:33 -05:00
|
|
|
// Return the interpolated command
|
|
|
|
return command, nil
|
2016-07-04 18:44:33 -04:00
|
|
|
}
|
2015-06-14 14:01:28 -04:00
|
|
|
|
2016-07-04 18:44:33 -04:00
|
|
|
func (p *Provisioner) createCommandTextPrivileged() (command string, err error) {
|
2018-06-14 19:49:15 -04:00
|
|
|
// Prepare everything needed to enable the required env vars within the
|
|
|
|
// remote environment
|
2018-03-23 07:46:55 -04:00
|
|
|
err = p.prepareEnvVars(true)
|
2017-09-14 19:39:35 -04:00
|
|
|
if err != nil {
|
2017-10-25 08:50:58 -04:00
|
|
|
return "", err
|
2017-09-14 19:39:35 -04:00
|
|
|
}
|
2019-10-04 14:36:57 -04:00
|
|
|
ctxData := p.generatedData
|
|
|
|
ctxData["Path"] = p.config.RemotePath
|
|
|
|
ctxData["Vars"] = p.config.RemoteEnvVarPath
|
|
|
|
p.config.ctx.Data = ctxData
|
|
|
|
|
2015-07-26 20:43:05 -04:00
|
|
|
command, err = interpolate.Render(p.config.ElevatedExecuteCommand, &p.config.ctx)
|
2015-06-14 14:01:28 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("Error processing command: %s", err)
|
|
|
|
}
|
|
|
|
|
2018-12-07 10:30:50 -05:00
|
|
|
command, err = provisioner.GenerateElevatedRunner(command, p)
|
2016-07-12 19:28:14 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("Error generating elevated runner: %s", err)
|
|
|
|
}
|
2015-06-14 14:01:28 -04:00
|
|
|
|
2016-07-04 18:44:33 -04:00
|
|
|
return command, err
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
2018-12-07 10:30:50 -05:00
|
|
|
func (p *Provisioner) Communicator() packer.Communicator {
|
|
|
|
return p.communicator
|
|
|
|
}
|
2017-10-15 08:28:59 -04:00
|
|
|
|
2018-12-07 10:30:50 -05:00
|
|
|
func (p *Provisioner) ElevatedUser() string {
|
|
|
|
return p.config.ElevatedUser
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Provisioner) ElevatedPassword() string {
|
2018-03-08 18:14:57 -05:00
|
|
|
// Replace ElevatedPassword for winrm users who used this feature
|
2019-07-11 12:37:59 -04:00
|
|
|
p.config.ctx.Data = p.generatedData
|
2018-12-07 10:30:50 -05:00
|
|
|
elevatedPassword, _ := interpolate.Render(p.config.ElevatedPassword, &p.config.ctx)
|
2015-06-14 14:01:28 -04:00
|
|
|
|
2018-12-07 10:30:50 -05:00
|
|
|
return elevatedPassword
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|