ansible_user undefined when used in become_user:

Hello,

I thought that when ansible-playbook was used with the “-u” option, then ansible_user was always defined as the “-u” user.

when running the following playbook,

  • hosts: mybox
    gather_facts: no
    tasks:
  • name: Echo ansible_user
    debug:
    msg: “hello {{ ansible_user }}”
    become: yes
    become_user: “{{ansible_user}}”

I get the following error :

The field ‘become_user’ has an invalid value, which includes an undefined variable. The error was: ‘ansible_user’ is undefined\nexception type: <class ‘ansible.errors.AnsibleUndefinedVariable’>\nexception: ‘ansible_user’ is undefined

Why isn’t ansible_user available when the become_user template is rendered ?
Is this a bug ?

Thank you for your help

Let me add that I encounter the “ansible_user” is undefined issue with both stable-2.3 and stable-2.4 branches of the code.

After a bit of research, I ended up understanding that the problem comes from the sequence that creates the context.

during task execution, “ansible_user” is considered a magic variable, that is created out of “remote_user”.
but it is added to the task variables context only after the connection info is built, templated and checked for undefined values.

I suspect this is a bug in the context creation ordering (because this was working with ansible 1.8 with sudo_user: {{ansible_ssh_user}} )

I pushed a PR fixing this bug - https://github.com/ansible/ansible/pull/31179 , simply moving the “template” check for undefined values after magic variables were added. This makes them available during template rendering.

I would appreciate if someone in the ansible team has time to review it and tell me if this has any chance of being merged.

Thanks,
Jérôme

Just to note, that if it 'worked', become_user: "{{ansible_user}}"
would be a noop as the become system would ignore this by default as
you are already THAT user.

Also, debug does not get many of these things set as it has no
connection, it always executes 'locally' and ignores connection
settings.