title: Execute different tasks as different users in Ansible
body: <p>I have an Ansible task that creates new users on a remote box, makes that user a <code>sudo</code> user, then disables the <code>root</code> user's SSH login. Subsequently all the tasks on the remote box(es) are run as this new user. Is there a method to switch to the new user in the same play/playbook?</p>
  
  <p>For instance, this is the what the current directory structure looks like:</p>
  
  <pre><code>|-- initial_setup
  |   |-- change_hostname.yml
  |   |-- main.yml
  |   `-- newuser.yml
  |-- main.yml
  |-- README.md
  |-- roles
  |   `-- apache
  |       |-- conf
  |       |   `-- httpd.conf
  |       |-- handlers
  |       |   `-- main.yml
  |       `-- tasks
  |           `-- main.yml
  |          
  `-- start_install.sh
  </code></pre>
  
  <p>At the moment, I run the <strong><code>start_install.sh</code></strong> script to begin proceedings:</p>
  
  <pre><code>#!/bin/bash
  
  # Install a new remote user with 'sudo' privileges
  ansible-playbook initial_setup/main.yml
  
  # Start main installation process
  ansible-playbook main.yml
  </code></pre>
  
  <p>As shown above, it first executes <code>initial_setup/main.yml</code> and then proceeds to the "proper" playbook. Both of these are listed below:</p>
  
  <p><strong><code>initial_setup/main.yml</code></strong></p>
  
  <pre><code>[root@testserver record1]# cat initial_setup/main.yml 
  - include: newuser.yml
  - include: change_hostname.yml
  </code></pre>
  
  <p><strong><code>initial_setup/newuser.yml</code></strong></p>
  
  <pre><code>---
  - hosts: redbox1
    remote_user: root
  
    vars: 
      NEW_SUDO_USER: 'ansibleuser'
  
    tasks:
      - name: Create a new secondary, non-root, sudo user
        user: name={{ NEW_SUDO_USER }}
              password='testpass'
              shell='/bin/bash'
    # followed by the tasks to give the user sudo privileges, 
    # allow SSH access to the new user, remove root SSH etc.
  </code></pre>
  
  <p>and then the playbook proper (<strong><code>./main.yml</code></strong>) begins, like so:</p>
  
  <pre><code>[root@testserver record1]# cat main.yml 
  ---
  - hosts: redbox1
    remote_user: ansibleuser
    become: yes
    become_method: sudo
  
    roles:
      - apache
  </code></pre>
  
  <p>I'm not sure that this is the proper way to get these tasks in done in Ansible (that is, using a shell script to execute different <em>plays</em>, each of which makes use of a different <code>remote_user</code>). Is there another, cleaner solution to achieve the same result?</p>