Setting up Ansible for the first time
From: https://www.howtoforge.com/tutorial/setup-new-user-and-ssh-key-authentication-using-ansible/
On the Provisioning server:
Install Ansbile
sudo apt install python ansible sshpass whois -y
SSHPass is just for testing
Set up Provisioning User on master machine
useradd -m -s /bin/bash provision
passwd provision
Set your Provisioning User password
echo -e 'provision\tALL=(ALL)\tNOPASSWD:\tALL' > /etc/sudoers.d/provision
Define Provisioning user for slave machines
For each server we need to also create a host user
su - privision
sudo su
mkpasswd --method=SHA-512
#Enter Password and copy the output - you will need it for the deploy-ssh.yml file later
su - provision
Create SSH Key
ssh-keygen -t rsa
Add hosts
sudo nano /etc/ansible/hosts
[piservers]
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
[piservers:vars]
ansible_user=provision
ansible_password=Yourpassword
Edit ansible.cfg
sudo nano /etc/ansible/ansible.cfg
set
[defaults]
inventory = /etc/ansible/hosts
Add client ssh fingerprints
ssh-keyscan 192.168.1.2 >> ~/.ssh/known_hosts
ssh-keyscan 192.168.1.3 >> ~/.ssh/known_hosts
ssh-keyscan 192.168.1.4 >> ~/.ssh/known_hosts
ssh-keyscan 192.168.1.5 >> ~/.ssh/known_hosts
For a lot of hosts
for i in $(cat list-hosts.txt)
do
ssh-keyscan $i >> ~/.ssh/known_hosts
done
Create Playbook
sudo nano deploy-ssh.yml
Replace the provisioning password below with the one you generated
---
- hosts: all
vars:
- provision_password: '$6$w9S3t7x1kRtmG0u$6nVU9KZsC12Q8DYI4FtgKPy.e/cq/jseB/.DViTO1SpUnoCy.dxcOf8hyfitGq5V0yhgXccxzlqm2o.I3SlDJ0'
gather_facts: no
tasks:
- name: Add a new user named provision
user:
name=provision
password={{ provision_password }}
- name: Add provision user to the sudoers
copy:
dest: "/etc/sudoers.d/provision"
content: "provision ALL=(ALL) NOPASSWD: ALL"
- name: Deploy SSH Key
authorized_key: user=provision
key="{{ lookup('file', '/home/provision/.ssh/id_rsa.pub') }}"
state=present
- name: Disable Password Authentication
lineinfile:
dest=/etc/ssh/sshd_config
regexp='^PasswordAuthentication'
line="PasswordAuthentication no"
state=present
backup=yes
notify:
- restart ssh
- name: Disable Root Login
lineinfile:
dest=/etc/ssh/sshd_config
regexp='^PermitRootLogin'
line="PermitRootLogin no"
state=present
backup=yes
notify:
- restart ssh
handlers:
- name: restart ssh
service:
name=sshd
state=restarted
Run the Ansible Playbook
ansible-playbook deploy-ssh.yml --user root --ask-pass --become --ask-become-pass