Ansible ssh as user and execute has root (expect like)

ansibleexpectrootsudo

I have to administer an important number of hosts where there is only one user able to access from SSH (let's call him foo) and then have to login as root to execute privilegied commands.

Foo user doesn't have any kind of sudo privileges so I'm forced to login as root to execute privilegied commands. I'm actually using an expect script to do this job (ssh login as foo, login as root via su) and I want to switch to Ansible. I know I could create a new user and give him sudo privileges or basically give sudo privileges to foo but is it possible to do the same thing I'm doing with expect with Ansible?

I would like to do the ssh connection as foo and then execute playbooks or any kind of adhoc command as root. I didn't found any information in the Ansible documentation about that so I'm asking here if someone already had this kind of interrogation.

Best Answer

With ansible, you can use sudo or su:

- hosts: example.com
  gather_facts: False
  su: yes
  su_user: root
  tasks:
    - shell: whoami

You could also do that from the command line:

ansible-playbook --su --su-user=root --ask-su-pass playbook.yml

This functionality has been available since this pull request, and is present in current 1.6.6.