Ansible: Run 1 task on 1 host under several users

ansible

I have 1 VM, there are several applications on it. Each app is working under it's own user.

host:
– host1
users:
– app1
– app2

They have similar configuration files, the difference is in names and some sensitive data. So, is there any way to run 1 task for several users on 1 host with ansible in parallel.

smth like this.

inventory:

[webservers:children]
app1
app2

[app1]
127.0.0.1
[app2]
127.0.0.1

group_vars/app1/vars.yml:

---
app_user: app1
var2: value

group_vars/app2/vars.yml:

---
app_user: app2
var2: value

tasks/test.yml:

---
- hosts: webservers
  tasks:
  - name: Copy config
    become: true
    become_user: {{ app_user }}
    template: ....

So invoking task in this way, works only with first app. I understand that I can make a playbook for every app_user or write one playbook with sequence of tasks for each app_user, but is there a way how to do what I want?

Best Answer

That won't work, because:

Within any section, redefining a var will overwrite the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a play’s vars: section, the 2nd one wins.

Ansible doc: playbooks_variables

In my understanding of the documentation app_user under group_vars/app2/vars.yml should overwrite app_user under group_vars/app1/vars.yml.

What should work would be to call each hostgroup in a separate play:

---
- hosts: app1
  tasks:
  - name: Copy config
    become: true
    become_user: {{ app_user }}
    template: ....

- hosts: app2
  tasks:
  - name: Copy config
    become: true
    become_user: {{ app_user }}
    template: ....

Also:

It is not necessary or a good practise to use becom_user for a template task. Use the template module like this:

---
- hosts: app1
  tasks:
  - name: Copy config
    template:
      src: template.j2
      dest: /some/remote/path
      owner: "{{ app_user }}"
      group: "{{ app_user }}"
      mode: 0755