Search code examples
sudoansible

How to get ansible 'become' user in included file?


Using ansible 1.9. Inventory:

my.host ansible_ssh_user=FIRSTUSER

Playbook:

- hosts: my.host
  roles:
    - myrole

Role tasks file:

- include: tasks.yml

- include: tasks.yml
  become: true
  become_user: SECONDUSER

In tasks.yml I'm trying to print out the user who is currently running that file. The first time it should print FIRSTUSER and the second time it should print SECONDUSER. But no matter what I try (ansible_ssh_user, ansible_user_id, ansible_env), it always prints FIRSTUSER, even though the second time tasks.yml is run it's run as SECONDUSER.

How do I print the user that is currently running tasks.yml?

If in tasks.yml I include a task file: dest=~/tmp state=directory', using the user-relative path ~/tmp, it correctly puts it at /home/FIRSTUSER/tmp the first time and /home/SECONDUSER/tmp the second time. So it's working correctly, but I can't get the user from a variable within tasks.yml so that I can conditionally execute certain things for example.


Solution

  • Vars like ansible_ssh_user, ansible_user_id, ansible_env etc. are provided by the setup module. The setup module is by default executed as first task of the playbook, which is the GATHERING FACTS task you should see during play. That should explain why these variables do not correlate to what you have specified in your include statements.

    You should be able to fetch these vars again in your included tasks file by running the setup module again. But be aware this would permanently change these values, not only in your included file.

    - setup:
    

    A better solution might be to simply run the shell module and ask for whoami:

    - shell: whoami
      register: whoami
    
    - debug: msg="{{ whoami.stdout }}"