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 ?
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.
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.