0

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?

0

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
  • hmm, i didn't think in that way))) thank you! I can put all configs under root and then change owner to app_user. Good idea. – igkuz Oct 25 '16 at 9:46
0

I would try to create a role and call it multiple times giving there different variables (users).

---

- hosts: webservers
  roles:
    - common
    - { role: foo_app_instance, dir: '/opt/a',  app_port: 5000 }
    - { role: foo_app_instance, dir: '/opt/b',  app_port: 5001 }

Taken from here. In this way you will reuse your code (if tasks are really similar).

  • yes, that's also a good idea. But it will not run roles in parallel. I think will use the solution in next comment. Put configs under root account, then change permissions for each user and then run restart commands separately. – igkuz Oct 25 '16 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.