Set remote_user for a set of tasks in Ansible playbook without repeating it to the task

I create a playbook that first creates a new username. Then I want to run "moretasks.yml" as the new user I just created. I am currently setting remote_user for each task. Is there a way that I can set for the whole set of tasks once? It seems that I could not find examples of this, and made no attempt to move remote_user around the help.

Below main.yml:

--- - 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:

 --- - name: Task1 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}" - name: Task2 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}" 
+6
source share
2 answers

First of all, you really want to use sudo_user (the remote user is the one who logs in, sudo_user is the one who performs the task).

In your case, you want to complete the task as another user (previously created):

 - include: moretasks.yml sudo: yes sudo_user: "{{ newuser }}" 

and these tasks will be executed as {{newuser}} (do not forget the quotation marks)

Note. In most cases, you should consider remote_user as a host parameter. The user can log on to the machine and has sufficient rights to perform actions. To work, you must use sudo / sudo_user

+7
source

Could you divide this into separate plays? (players may contain several pieces)

 --- - name: PLAY 1 hosts: all remote_user: root gather_facts: true tasks: - include: createuser.yml new_user=username - include: roottasks.yml #some tasks unrelated to username. - name: PLAY 2 hosts: all remote_user: username gather_facts: false tasks: - include: moretasks.yml new_user=username 

There is a game that uses separate plays: you cannot use the variables set with register: or set_fact: in the first game to do something in the second play (this statement is not completely true, variables are available in hostvars , but I recommend not to use variables between roles). Certain variables, such as in group_vars and host_vars, work fine.

Another tip I would like to give is to study the roles http://docs.ansible.com/playbooks_roles.html . Although this may seem more complicated at first, it is much easier to reuse them (as you seem to be doing with "createuser.yml"). Looking at the type of things you are trying to achieve, the โ€œturn on all thingsโ€ path will not last longer.

+7
source

Source: https://habr.com/ru/post/979148/


All Articles