github.com/hashicorp/packer@v1.14.3/fix/fixer_powershell_escapes.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package fix 5 6 import ( 7 "strings" 8 9 "github.com/mitchellh/mapstructure" 10 ) 11 12 // FixerPowerShellEscapes removes the PowerShell escape character from user 13 // environment variables and elevated username and password strings 14 type FixerPowerShellEscapes struct{} 15 16 func (FixerPowerShellEscapes) DeprecatedOptions() map[string][]string { 17 return map[string][]string{} 18 } 19 20 func (FixerPowerShellEscapes) Fix(input map[string]interface{}) (map[string]interface{}, error) { 21 type template struct { 22 Provisioners []interface{} 23 } 24 25 var psUnescape = strings.NewReplacer( 26 "`$", "$", 27 "`\"", "\"", 28 "``", "`", 29 "`'", "'", 30 ) 31 32 // Decode the input into our structure, if we can 33 var tpl template 34 if err := mapstructure.WeakDecode(input, &tpl); err != nil { 35 return nil, err 36 } 37 38 for i, raw := range tpl.Provisioners { 39 var provisioners map[string]interface{} 40 if err := mapstructure.Decode(raw, &provisioners); err != nil { 41 // Ignore errors, could be a non-map 42 continue 43 } 44 45 if ok := provisioners["type"] == "powershell"; !ok { 46 continue 47 } 48 49 if _, ok := provisioners["elevated_user"]; ok { 50 provisioners["elevated_user"] = psUnescape.Replace(provisioners["elevated_user"].(string)) 51 } 52 if _, ok := provisioners["elevated_password"]; ok { 53 provisioners["elevated_password"] = psUnescape.Replace(provisioners["elevated_password"].(string)) 54 } 55 if raw, ok := provisioners["environment_vars"]; ok { 56 var env_vars []string 57 if err := mapstructure.Decode(raw, &env_vars); err != nil { 58 continue 59 } 60 env_vars_unescaped := make([]interface{}, len(env_vars)) 61 for j, env_var := range env_vars { 62 env_vars_unescaped[j] = psUnescape.Replace(env_var) 63 } 64 // Replace with unescaped environment variables 65 provisioners["environment_vars"] = env_vars_unescaped 66 } 67 68 // Write all changes back to template 69 tpl.Provisioners[i] = provisioners 70 } 71 72 if len(tpl.Provisioners) > 0 { 73 input["provisioners"] = tpl.Provisioners 74 } 75 76 return input, nil 77 } 78 79 func (FixerPowerShellEscapes) Synopsis() string { 80 return `Removes PowerShell escapes from user env vars and elevated username and password strings` 81 }