Ansible [ Session - 9 ]
Use Case: Configuring Managed Node Using Non - Root account
In real world scenario, managed node is more critical than controller node. 🕵
So we have to give limited access to user logging into controller node. 🗞
We disable root account on managed node. 📴
We can use sudo to give root privileges to normal user on contorller node. 🦸
Since we login as root user to perform some task in ansible, we have to someway limit the
access to ansible.
You cannot edit ansible configuration file on controller node with non -
❌
/etc/ansible/ansible.cfg
root access.
To resolve this, we create configuration file in home directory. 📂
$ touch ansible.cfg
$ vim ansible.cfg
[defaults]
inventory=/home/chetan/inventory_file.txt
host_key_checking=false
After that we can create required inventory_file containing host names. 📄
$ vim inventory_file.txt
192.168.0.1 ansible_ssh_user=<username> ansible_ssh_pass=<password>
There are certain command which can be only run by root account.
Ansible [ Session - 9 ] 1
As you can see above, it will throw an error, if we try to run package command with non user
account. 😰
Thus, we have to give certain privileges to non-root user to be able to run these commands.
For this, we have to edit /etc/sudoers file on target nodes.
$ sudo vim /etc/sudoers
<username> ALL=(root) /usr/bin/yum
Above command states that for non root user we are giving root privileges on /usr/bin/yum
program.
Now we have to tell ansible to run any command with help of sudo so it will not give an error.
$ ansible all -m package -a "name=vftpd state=present" --become --ask-become-pass
Here, —become is a flag which states to run this command with sudo on target node. 🦸
—ask-become-pass will prompt you for root password. 🔑
sudo will by default give root privileges to user.
we can use —become-user to give privileges of user rather than root.
dzdo is an alternative to sudo command.
We can disable password prompting by writing NOPASSWD ALL in /etc/sudoers file as below.
📄
$ sudo vim /etc/sudoers
<username> ALL=(root) /usr/bin/yum NOPASSWD: ALL
Or we can write password in inventory file using ansible_become_pass variable
$ vim inventory_file.txt
Ansible [ Session - 9 ] 2
192.168.0.1 ansible_ssh_user=<username> ansible_ssh_pass=<password> ansible_become_pass=<root_password>
Instead of using multiple flags while running ansible, we can state all variables in ansible.cfg file.
You can login to target system using key-pair.
ssh-keygen is program used to create public-private key pair.
After both keys are generated, we have to transfer public key to target node. 🔑
ssh-key-id is program used to transfer public key 🔑 from controller system to target system. 🖥
Thus, you won't have to give password each time after using assymetric ( public-private) key
authorization.
Finally, our inventory file would look like this :
Ansible [ Session - 9 ] 3
Ansible [ Session - 9 ] 4