Ansible and User Accounts
From time to time, I get confused when it comes to Ansible and things like default_user, become, become_method and become_user. To make my life easier the next time, I prepared this note.
default_user
If we specify no user at all, Ansible will use the user that is running the ansible-playbook command.
For instance if I run ansible-playbook as user jirka, it’s going to try logging in as jirka to the remote machine. Of course this will succeed only if the account with the same name exists on the remote machine and if I either provide remote user’s password or the remote account jirka has public key of that account in authorized keys (/home/jirka/.ssh/authorized_keys).
remote_user
If remote_user is configured, Ansible will use it. There are three ways how to configure remote user:
The first is to configure the remote_user in the playbook:
---
- hosts: thor.example.com
remote_user: root
roles:
- apache
The second way how to set value of the remote_user is to do that in Ansible’s configuration file ansible.cfg.
So adding this to the currently used ansible.cfg would set remote_user to root.
[defaults]
remote_user = root
Which ansible.cfg is currently used? If there is an ansible.cfg in the directory from which we are running ansible, it has priority and it is used. Otherwise Ansible uses the default one which usuall is /etc/ansible/ansible.cfg.
The command to check it is: ansible --version
$ ansible --version | grep ansible.cfg
config file = /etc/ansible/ansible.cfg
The third option is to specify the remote_user on the commandline using parameter -u:
ansible-playbook -u root -i inventory.ini myplaybook.yaml
ansible-playbook -u jiri -i inventory.ini myplaybook.yaml
become
If we need to elevate rights or to become other user than the one Ansible used for connection, we can use “become: true” in our playbook.
“become: true” without any other parameter will use sudo to become root.
But we may want to set the method and user explicitly (because explicit is usually better than implicit) or even to change it.
To do that, we can use parameters become method and become user:
become: yes
become_method: sudo
become_user: root
become_method
Sudo is the default method, but not the only one.
Other methods are for instance su, pbrun or runas. There are many more, but we really need only su and sudo.
The difference between become_method: sudo and become_method: su mirrors the difference between sudo and su. Here is worth mentioning that for method su, we need to know password of the user we want to become (here root) and for method sudo we need to have sudo privileges which is configured in /etc/sudoers (of course on the remote machine).