Adithya
Adithya

Reputation: 163

Ansible hosts configuration using private key and sudo user

Hi I have written a playbook for Ansible to install a few application. I am having trouble as I have to run every thing as root which is not a good idea.

So I have created a sudo user and have created a private key for authentication.

Could some one help me in defining the hosts file for this scenario.

My current hosts file is like this:

[webserver]
web-01 ansible_ssh_host=192.168.0.11 ansible_ssh_user=root

Thanks,

Upvotes: 8

Views: 12778

Answers (1)

Arbab Nazar
Arbab Nazar

Reputation: 23791

Your new hosts file will be look like this:

[webserver]
web-01 ansible_ssh_host=192.168.0.11 ansible_ssh_user=USERNAME ansible_ssh_private_key_file=/secure/mykey

But please also make sudo: True in your playbook like this:

  ---
   - hosts: webserver
     sudo: True 
     remote_user: USERNAME
     gather_facts: True
     # Run these tasks  
     tasks:
       - name: Run this task.....

One Important thing that your sudo user should be password less, to achieve that you should edit your sudoer file. If you are using the CentOS, then please edit the /etc/sudoers file and add the following line

USERNAME ALL=(ALL) NOPASSWD: ALL

please add this line after the last line which says

#includedir /etc/sudoers.d

If you are using the Ubuntu, then use the visudo command, find and edit the below line:

# Members of the admin group may gain root privileges
%sudo   ALL=(ALL:ALL) NOPASSWD: ALL

Upvotes: 9

Related Questions