Question:
I am creating a playbook which first creates a new username. I then want to run “moretasks.yml” as that new user that I just created. Currently, I’m setting remote_user for every task. Is there a way I can set it for the entire set of tasks once? I couldn’t seem to find examples of this, nor did any of my attempts to move remote_user around help.
Below is main.yml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
--- - name: Configure Instance(s) hosts: all remote_user: root gather_facts: true tags: - config - configure tasks: - include: createuser.yml new_user=username - include: moretasks.yml new_user=username - include: roottasks.yml #some tasks unrelated to username. |
moretasks.yml:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
--- - name: Task1 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}" - name: Task2 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}" |
Answer:
First of all you surely want to use sudo_user
(remote user is the one that logs in, sudo_user
is the one who executes the task).
In your case you want to execute the task as another user (the one previously created) just set:
1 2 3 4 |
- include: moretasks.yml sudo: yes sudo_user: "{{ newuser }}" |
and those tasks will be executed as {{ newuser }} (Don’t forget the quotes)
Remark: In most cases you should consider remote_user
as a host parameter. It is the user that is allowed to login on the machine and that has sufficient rights to do things. For operational stuff you should use sudo
/ sudo_user