2
votes

As a common security habit, I learned that you shouldn't allow root login through ssh on machines open to the world. The way to go is to ssh to your server with a user account, then use sudo. Also Ubuntu disabled ssh-ing as root account by default.

When I'm configuring a server manually I usually execute sudo -i to have a persistent root shell, so that I don't have to type sudo in front of every command.

Now I'm not completely sure what's the best way to do it with Ansible. In Ansible's inventory files, you can specify the user to use for ssh-ing with the ansible_ssh_user variable. In Ansible playbooks and tasks you have these options:

  • remote_user - The user to ssh to the machine with for the specific playbook/task
  • sudo - If yes, runs the commands in the playbook/task with sudo
  • sudo_user - Sudo to a different user and then execute the commands in the playbook/task

So I specified the user I use for ssh-ing with ansible_ssh_user and then I have a couple of tasks that need root privileges.

I have a two of options to do this, but I don't really like them:

  1. I could use sudo: yes for every single task that needs root privileges.

    I don't really like this way because I will have to use this for almost every task.

  2. I could put sudo: yes in the playbook that includes the roles/tasks.

    I doubt if this should be the correct way, because like this, all roles/tasks should assume that they always have root privileges. Also, if we would do it like this, why can't I then just set this as an option in the Ansible config, so that all my playbooks (and it's roles/tasks) will always use sudo?

So I wonder, what is the correct way to do this?

2

2 Answers

2
votes

Others may have better suggestions, but I also do your option 2 above. Every playbook that I want to be runnable top-level typically starts with this boilerplate:

---
-
  hosts: all
  gather_facts: no
  sudo: yes

My thought is if you want re-usable tasks and maybe also playbooks, you are probably right that it is better not to specify sudo and allow the end-user to make that determination within their own setup.

It seems most accurate to the real world to make the sudo/root decision on a per-role or per-server basis, since it's the server configuration that ultimately determines which approach will actually work on the server. AFAIK ansible doesn't encourage/support that, but maybe another answer will point to a better way.

2
votes

sudo: yes is deprecated in new version of Ansible, in new version they are using become: yes

Example:
  ---
   - hosts: all
     become: yes
     gather_facts: yes
     roles:
       - common

Hope this will help you. Thanks