Ansible/Yaml -- conditionally become another user

ansible, yaml

Solution

I am posting my own solution for anyone else who may encounter the same situation.

Basically, here is the syntax in the playbook to conditionally become another user.

become: "{{ 'no' if user == ansible_user else 'yes' }}"
become_user: "{{ edge_user }}"

The condition can be whatever you want. Hope this helps!

Problem

I have the following use case. A user runs an ansible play book and provides a user (with -e user=). In the playbook, as expected, I do become and become_user. However, I want to do this only when the username provided differs from his own username (which is statically known). I tried to conditionally include a file, where I will do the become, but this didn't seem to work so far. Here is some of my code: First/playbook file: ``` --- - name: example hosts: examplehost tasks: - include: "usersetup.yml" when: "{{ user }} != {{ user_id }}" ``` Second file (usersetup.yml) I am unclear about the format of this file, since I am relatively new to the process, but I currently have: ``` - become: yes - become_user: "{{ user }}" ``` This doesn't work of course, so any ideas/suggestions welcome. I would be more than happy to provide more clarifications if required. Thanks.

Original source