diff --git a/changelogs/fragments/58876-do-not-reuse-remote_user-from-prev-loop.yaml b/changelogs/fragments/58876-do-not-reuse-remote_user-from-prev-loop.yaml new file mode 100644 index 0000000000..d345b2254b --- /dev/null +++ b/changelogs/fragments/58876-do-not-reuse-remote_user-from-prev-loop.yaml @@ -0,0 +1,2 @@ +bugfixes: + - Do not re-use remote_user from previous loop iteration (https://github.com/ansible/ansible/issues/58876) diff --git a/lib/ansible/executor/task_executor.py b/lib/ansible/executor/task_executor.py index 74aad5d385..3499dc1a48 100644 --- a/lib/ansible/executor/task_executor.py +++ b/lib/ansible/executor/task_executor.py @@ -410,6 +410,20 @@ class TaskExecutor: results.append(res) del task_vars[loop_var] + # clear 'connection related' plugin variables for next iteration + if self._connection: + clear_plugins = { + 'connection': self._connection._load_name, + 'shell': self._connection._shell._load_name + } + if self._connection.become: + clear_plugins['become'] = self._connection.become._load_name + + for plugin_type, plugin_name in iteritems(clear_plugins): + for var in C.config.get_plugin_vars(plugin_type, plugin_name): + if var in task_vars and var not in self._job_vars: + del task_vars[var] + self._task.no_log = no_log return results diff --git a/test/integration/targets/loops/tasks/main.yml b/test/integration/targets/loops/tasks/main.yml index 0ce32ab589..5dd7d26fe9 100644 --- a/test/integration/targets/loops/tasks/main.yml +++ b/test/integration/targets/loops/tasks/main.yml @@ -344,3 +344,18 @@ loop_var: "{{ loop_var_name }}" vars: loop_var_name: templated_loop_var_name + +# https://github.com/ansible/ansible/issues/59414 +- name: Test preserving original connection related vars + debug: + var: ansible_remote_tmp + vars: + ansible_remote_tmp: /tmp/test1 + with_items: + - 1 + - 2 + register: loop_out + +- assert: + that: + - loop_out['results'][1]['ansible_remote_tmp'] == '/tmp/test1'