Ansible Playbook to deploy user with SSH Key
We will create a new user with sudo privilege and deploy it with their SSH Public Key to all the targeted hosts through ansible-playbook. After that, he/she doesn’t need to type an SSH password while login server.
I hope you have already installed ansible on your control host and you able to connect all your target hosts through ansible admin user. When a new System Administrator joins the company, manually creating his/her user account on multiple hosts is a tedious job. So to overcome this issue I have created a playbook which will create his/her user account, add the user to the admin privileged group and also copy their SSH public key to the remote servers.
Generate SSH Key
First generate SSH key for new user.
[newuser@srv-01 ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/newuser/.ssh/id_rsa):
Created directory '/home/newuser/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/newuser/.ssh/id_rsa.
Your public key has been saved in /home/newuser/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:+Z/N055jsnrr2s/k7zg3IWA6SaURTmETeWFqC803vhM
The key's randomart image is:
+---[RSA 2048]----+
| =+o. |
| +++. |
| .o=oo |
| oo+o.o |
| .SEo . |
| o +o . . |
| . .oo .o.|
| . ...**=+|
| oB=X@B|
+----[SHA256]-----+
Inventory File
This is an inventory file for our playbook. Here I have defined 2 groups CentOS and Ubuntu for our all hosts. To give admin privileges to a normal user, in Ubuntu users should be in sudo group and in CentOS users should be in wheel group, so I’ve defined variable super_group for this. I have also defined common variables for both groups.
To run the playbook we are using an ansible admin user “ansible_admin”.
[CentOS]
srv-02
srv-03
[Ubuntu]
srv-04
[all:vars]
ansible_ssh_user = ansible_admin
ansible_ssh_pass = Pass123$
[CentOS:vars]
super_group = wheel
[Ubuntu:vars]
super_group = sudo
Check Connection
Now check whether remote hosts are reachable or not. If it’s ok then you should get SUCCESS in output.
[root@srv-01]# ansible all -m ping -i inventory.ini
srv-02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
srv-03 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
srv-04 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
All servers are reachable through ansible admin user.
Ansible Playbook
This is our playbook file.