ansible/ansible — pull request #3250 by gildegoma (2013-06-18 18:14:52+00:00)
Title: Enlarge scope of 'ansible_ssh_user' magic variable

In continuation to #3217, I propose to make magical variable `ansible_ssh_user` available in more Ansible YAML scopes. Examples below needs this patch to work:

```
- name: Enjoy more 'ansible_ssh_user' magical variable

hosts: all

# Vars added here for sake of example simplicity,
# but should typically be stored in group/host vars files.
vars:
deploy_user: greatapp
dev_user: vagrant

# By default tasks are not exectued by Ansible SSH remote user, and not by root
sudo: yes
sudo_user: '{{ deploy_user }}'

# Dummy examples (imagine a list of roles instead... ;-)
tasks:

- name: Who am I to deploy that stuff 'alone' ?
command: whoami

- name: Task for the ansible remote user
file: dest=/tmp/test1 state=directory
sudo_user: '{{ ansible_ssh_user }}'

- name: Conditional task, depending on ansible remote user value
file: dest=/tmp/test2 state=directory
when: "ansible_ssh_user != dev_user"
sudo_user: root
```

Without this patch, I have to define a similar `ansible_ssh_user` variable in my different group/host vars file, which is okay, but a bit frustrating since the information is dynamically available.

Now a few comments about this single-line patch:
* If the patch idea is accepted, it would be worth verify if `_executor_internal_inner` method should be adapted (and even more things, since I don't exactly know what I'm doing...). To make it clear: I haven't tested this patch with *delegated hosts*, since I never used this feature so far)
* If there is any problem to enlarge `ansible_ssh_user` scope, I'd propose to at least consider making it available for `sudo_user`, with a patch looking like:

```
# late processing of parameterized sudo_user
if self.sudo_user is not None:
+ inject_copy = inject.copy()
+ inject_copy.setdefault('ansible_ssh_user', self.remote_user)
self.sudo_user = template.template(self.basedir, self.sudo_user, inject_copy)
```

So much to dig and learn...