Ansible and User Accounts

I keep getting confused by Ansible’s default_user, become, become_method and become_user. I wrote this note to make things quicker next time.

No user specified

If you do not specify a user, Ansible uses the user that runs the ansible-playbook command.

For example, if I run ansible-playbook as jirka, Ansible tries to log in to the remote machine as jirka. That works only if an account of the same name exists on the remote machine, and if I supply its password or the remote jirka has my public key in /home/jirka/.ssh/authorized_keys.

remote_user

If remote_user is set, Ansible uses it. There are three ways to set it.

The first is in the playbook:

---
- hosts: thor.example.com
  remote_user: root
  roles:
    - apache

The second is in Ansible’s configuration file, ansible.cfg. Adding this sets remote_user to root:

[defaults]
remote_user = root

Which ansible.cfg is used? If there is one in the directory you run Ansible from, it takes priority. Otherwise Ansible uses the default, usually /etc/ansible/ansible.cfg. Check it with ansible --version:

$ ansible --version | grep ansible.cfg
  config file = /etc/ansible/ansible.cfg

The third way is on the command line, with -u:

ansible-playbook -u root -i inventory.ini myplaybook.yaml
ansible-playbook -u jiri -i inventory.ini myplaybook.yaml

become

To elevate privileges, or to switch to a different user than the one Ansible connected as, use become: true.

become: true on its own uses sudo to become root.

You can also set the method and user explicitly. Explicit is usually better than implicit:

become: yes
become_method: sudo
become_user: root

become_method

Sudo is the default method, but not the only one.

Other methods are su, pbrun, runas and more. In practice you only need su and sudo.

The difference between become_method: sudo and become_method: su mirrors the difference between sudo and su. For su you need the password of the user you want to become (here root). For sudo you need sudo privileges, configured in /etc/sudoers on the remote machine.

Tags: