From 708869edd60abb1493c2cbc3b042b835544c3eb8 Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Fri, 9 Mar 2018 08:02:54 +1000 Subject: [PATCH] win: handle non string as an environment value (#37215) * win: handle non string as an environment value * Changed powershell environment handler to use .net function instead for special chars --- lib/ansible/plugins/shell/powershell.py | 5 +++- .../targets/win_exec_wrapper/tasks/main.yml | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/ansible/plugins/shell/powershell.py b/lib/ansible/plugins/shell/powershell.py index 92a2fa40c35..0708abbe59c 100644 --- a/lib/ansible/plugins/shell/powershell.py +++ b/lib/ansible/plugins/shell/powershell.py @@ -162,7 +162,10 @@ Function Run($payload) { $ps.AddStatement().AddScript("Function Write-Host(`$msg){ Write-Output `$msg }") | Out-Null ForEach ($env_kv in $payload.environment.GetEnumerator()) { - $escaped_env_set = "`$env:{0} = '{1}'" -f $env_kv.Key,$env_kv.Value.Replace("'","''") + # need to escape ' in both the key and value + $env_key = $env_kv.Key.ToString().Replace("'", "''") + $env_value = $env_kv.Value.ToString().Replace("'", "''") + $escaped_env_set = "[System.Environment]::SetEnvironmentVariable('{0}', '{1}')" -f $env_key, $env_value $ps.AddStatement().AddScript($escaped_env_set) | Out-Null } diff --git a/test/integration/targets/win_exec_wrapper/tasks/main.yml b/test/integration/targets/win_exec_wrapper/tasks/main.yml index 16d8c255419..36bc81855be 100644 --- a/test/integration/targets/win_exec_wrapper/tasks/main.yml +++ b/test/integration/targets/win_exec_wrapper/tasks/main.yml @@ -31,6 +31,32 @@ - invalid_ps_version is failed - '"This module cannot run as it requires a minimum PowerShell version of 20.0.0.0, actual was " in invalid_ps_version.msg' +- name: test out environment block for task + win_shell: set | more + args: + executable: cmd.exe + environment: + String: string value + Int: 1234 + Bool: True + double_quote: 'double " quote' + single_quote: "single ' quote" + hyphen-var: abc@123 + '_-(){}[]<>*+-/\?"''!@#$%^&|;:i,.`~0': '_-(){}[]<>*+-/\?"''!@#$%^&|;:i,.`~0' + register: environment_block + +- name: assert environment block for task + assert: + that: + - '"String=string value" in environment_block.stdout_lines' + - '"Int=1234" in environment_block.stdout_lines' + - '"Bool=True" in environment_block.stdout_lines' + - '"double_quote=double \" quote" in environment_block.stdout_lines' + - '"single_quote=single '' quote" in environment_block.stdout_lines' + - '"hyphen-var=abc@123" in environment_block.stdout_lines' + # yaml escaping rules - (\\ == \), (\" == "), ('' == ') + - '"_-(){}[]<>*+-/\\?\"''!@#$%^&|;:i,.`~0=_-(){}[]<>*+-/\\?\"''!@#$%^&|;:i,.`~0" in environment_block.stdout_lines' + - name: test out become requires without become_user set test_all_options: register: become_system