Skip to content

Commit 89be76c

Browse files
authored
backport 1.13.1 changes to release/1.13.x (#13405)
* Merge pull request #13404 from hashicorp/karthik/prepare_version_1.13.1 prepare version 1.13.1 * Merge pull request #13396 from hashicorp/karthik/powershell_fix Powershell Script Config Environment Variables Fix
1 parent b9fbe81 commit 89be76c

File tree

5 files changed

+89
-15
lines changed

5 files changed

+89
-15
lines changed

provisioner/powershell/provisioner.go

Lines changed: 59 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"context"
1212
"errors"
1313
"fmt"
14+
"io"
1415
"log"
1516
"os"
1617
"path/filepath"
@@ -265,9 +266,43 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
265266
return nil
266267
}
267268

269+
// extractScript prepares a temporary PowerShell script by prepending environment setup and debug config.
270+
// It copies the contents of the provided script file into the temp script and returns its path.
271+
func extractScript(p *Provisioner, script string) (string, error) {
272+
temp, err := tmp.File("powershell-provisioner-script")
273+
if err != nil {
274+
return "", err
275+
}
276+
277+
defer temp.Close()
278+
279+
baseString := `if (Test-Path variable:global:ProgressPreference)` +
280+
`{set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'};`
281+
282+
if p.config.DebugMode != 0 {
283+
baseString += fmt.Sprintf(`Set-PsDebug -Trace %d;`, p.config.DebugMode)
284+
}
285+
baseString += p.createFlattenedEnvVars(p.config.ElevatedUser != "")
286+
if _, err := temp.WriteString(baseString); err != nil {
287+
return "", fmt.Errorf("Error writing PowerShell script: %w", err)
288+
}
289+
290+
f, err := os.Open(script)
291+
if err != nil {
292+
return "", fmt.Errorf("Error opening powershell script: %s", err)
293+
}
294+
defer f.Close()
295+
if _, err := io.Copy(temp, f); err != nil {
296+
return "", fmt.Errorf("Error copying script contents: %w", err)
297+
}
298+
299+
return temp.Name(), nil
300+
301+
}
302+
268303
// Takes the inline scripts, adds a wrapper around the inline scripts, concatenates them into a temporary file and
269304
// returns a string containing the location of said file.
270-
func extractScript(p *Provisioner) (string, error) {
305+
func extractInlineScript(p *Provisioner) (string, error) {
271306
temp, err := tmp.File("powershell-provisioner")
272307
if err != nil {
273308
return "", err
@@ -280,7 +315,7 @@ func extractScript(p *Provisioner) (string, error) {
280315
// we concatenate all the inline commands
281316
for _, command := range p.config.Inline {
282317
log.Printf("Found command: %s", command)
283-
if _, err := commandBuilder.WriteString(command); err != nil {
318+
if _, err := commandBuilder.WriteString(command + "\n\t"); err != nil {
284319
return "", fmt.Errorf("failed to wrap script contents: %w", err)
285320
}
286321
}
@@ -310,11 +345,12 @@ func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packe
310345
p.communicator = comm
311346
p.generatedData = generatedData
312347

313-
scripts := make([]string, len(p.config.Scripts))
314-
copy(scripts, p.config.Scripts)
315-
348+
var scripts []string
349+
// maps temp script paths to original script paths
350+
tempToOriginalScriptMap := make(map[string]string)
316351
if p.config.Inline != nil {
317-
temp, err := extractScript(p)
352+
temp, err := extractInlineScript(p)
353+
tempToOriginalScriptMap[temp] = temp
318354
if err != nil {
319355
ui.Error(fmt.Sprintf("Unable to extract inline scripts into a file: %s", err))
320356
}
@@ -323,12 +359,27 @@ func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packe
323359
defer os.Remove(temp)
324360
}
325361

362+
if len(p.config.Scripts) > 0 {
363+
364+
for _, script := range p.config.Scripts {
365+
temp, err := extractScript(p, script)
366+
tempToOriginalScriptMap[temp] = script
367+
if err != nil {
368+
ui.Error(fmt.Sprintf("Unable to extract script into a file: %s", err))
369+
}
370+
scripts = append(scripts, temp)
371+
// Defer removal until the function exits
372+
defer os.Remove(temp)
373+
374+
}
375+
}
376+
326377
// every provisioner run will only have one env var script file so lets add it first
327378
uploadedScripts := []string{p.config.RemoteEnvVarPath}
328379
for _, path := range scripts {
329-
ui.Say(fmt.Sprintf("Provisioning with powershell script: %s", path))
380+
ui.Say(fmt.Sprintf("Provisioning with powershell script: %s", tempToOriginalScriptMap[path]))
330381

331-
log.Printf("Opening %s for reading", path)
382+
log.Printf("Opening %s for reading", tempToOriginalScriptMap[path])
332383
fi, err := os.Stat(path)
333384
if err != nil {
334385
return fmt.Errorf("Error stating powershell script: %s", err)

provisioner/powershell/provisioner_acc_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"os"
1010
"os/exec"
1111
"path/filepath"
12+
"regexp"
1213
"runtime"
1314
"testing"
1415

@@ -82,6 +83,16 @@ func TestAccPowershellProvisioner_Inline(t *testing.T) {
8283
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
8384
}
8485
}
86+
out, err := os.ReadFile(logfile)
87+
if err != nil {
88+
return err
89+
}
90+
output := string(out)
91+
regexMatchString := "test_env_var: TestValue"
92+
if !regexp.MustCompile(regexp.QuoteMeta(regexMatchString)).MatchString(output) {
93+
t.Errorf("expected env string %q in logs:\n%s", regexMatchString, output)
94+
}
95+
8596
return nil
8697
},
8798
}
@@ -105,6 +116,16 @@ func TestAccPowershellProvisioner_Script(t *testing.T) {
105116
return fmt.Errorf("Bad exit code. Logfile: %s", logfile)
106117
}
107118
}
119+
120+
out, err := os.ReadFile(logfile)
121+
if err != nil {
122+
return err
123+
}
124+
output := string(out)
125+
regexMatchString := "likewise, var2 is A`Backtick"
126+
if !regexp.MustCompile(regexp.QuoteMeta(regexMatchString)).MatchString(output) {
127+
t.Errorf("expected env string %q in logs:\n%s", regexMatchString, output)
128+
}
108129
return nil
109130
},
110131
}

provisioner/powershell/provisioner_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func TestProvisionerPrepare_extractScript(t *testing.T) {
2424
p := new(Provisioner)
2525
_ = p.Prepare(config)
2626
p.generatedData = generatedData()
27-
file, err := extractScript(p)
27+
file, err := extractInlineScript(p)
2828
defer os.Remove(file)
2929
if err != nil {
3030
t.Fatalf("Should not be error: %s", err)
@@ -36,7 +36,7 @@ func TestProvisionerPrepare_extractScript(t *testing.T) {
3636

3737
// File contents should contain 2 lines concatenated by newlines: foo\nbar
3838
readFile, err := os.ReadFile(file)
39-
expectedContents := "if (Test-Path variable:global:ProgressPreference) {\n set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'\n }\n \n $exitCode = 0\n try {\n $env:PACKER_BUILDER_TYPE=\"\"; $env:PACKER_BUILD_NAME=\"\"; \n foobar\n $exitCode = 0\n } catch {\n Write-Error \"An error occurred: $_\"\n $exitCode = 1\n }\n \n if ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) {\n $exitCode = $LASTEXITCODE\n }\n \n Write-Host $result\n exit $exitCode"
39+
expectedContents := " \n\tif (Test-Path variable:global:ProgressPreference) {\n\t set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'\n\t}\n\t\n\t$exitCode = 0\n\ttry {\n\t$env:PACKER_BUILDER_TYPE=\"\"; $env:PACKER_BUILD_NAME=\"\"; \n\tfoo\n\tbar\n\t\n\t$exitCode = 0\n\t} catch {\n\tWrite-Error \"An error occurred: $_\"\n\t$exitCode = 1\n\t}\n\t\n\tif ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) {\n\t\t$exitCode = $LASTEXITCODE\n\t}\n\t\n\tWrite-Host $result\n\texit $exitCode\n\n"
4040
normalizedExpectedContent := normalizeWhiteSpace(expectedContents)
4141
if err != nil {
4242
t.Fatalf("Should not be error: %s", err)
Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
{
22
"type": "powershell",
3-
"environment_vars": "PackerRunUUID={{build `PackerRunUUID`}},ID={{build `ID`}}",
3+
"environment_vars": "PackerRunUUID={{build `PackerRunUUID`}},ID={{build `ID`}},TEST_ENV_VAR=TestValue",
44
"inline": [
5-
"Write-Host \"$env:ID for provisioner.$env:PackerRunUUID\""
5+
"Write-Host \"$env:ID for provisioner.$env:PackerRunUUID build_name: $env:packer_build_name, test_env_var: $env:test_env_var\"",
6+
"setx BUILD_AMI_VERSION \"1.0.0\"",
7+
"setx BUILD_AMI_NAME custom_ami_name",
8+
"setx BUILD_AMI_DESCRIPTION \"This is a custom AMI created for testing purposes\""
69
]
7-
}
8-
10+
}

version/VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.13.0
1+
1.13.1

0 commit comments

Comments
 (0)