This is an Ansible role I use when I provision new servers, the role add my SSH key, and disable remote root login, password loginm and GSS login to secure down the SSH server and then restart it.
roles/ssh/tasks/main.yml:
---
- name: check remote SSH host is in known_hosts
command: /bin/grep -Fq {{ inventory_hostname }} /home/{{ ansible_ssh_user }}/.ssh/known_hosts
register: check_known_hosts
always_run: True
ignore_errors: True
changed_when: False
tags:
- ssh
- name: add remote host fingerprint to known_hosts if not found
shell: /usr/bin/ssh-keyscan {{ inventory_hostname }} >> /home/{{ ansible_ssh_user }}/.ssh/known_hosts
#debug: msg="I didn't find the {{ inventory_hostname }} in known_hosts and will add it"
when: check_known_hosts.rc != 0
tags:
- ssh
- name: add local public key to remote server
authorized_key: key="{{ lookup('file', '/home/te/.ssh/id_rsa.pub') }}" user={{ ansible_ssh_user }}
tags:
- ssh
- name: disallow root SSH access
lineinfile: dest=/etc/ssh/sshd_config regexp="^PermitRootLogin" line="PermitRootLogin no" state=present
notify:
- restart sshd
- name: disallow SSH password authentication
lineinfile: dest=/etc/ssh/sshd_config regexp="^PasswordAuthentication" line="PasswordAuthentication no" state=present
notify:
- restart sshd
- name: disallow SSH GSS API authentication
lineinfile: dest=/etc/ssh/sshd_config regexp="^GSSAPIAuthentication" line="GSSAPIAuthentication no" state=present
notify:
- restart sshd |
And in the handler section of the role:
handlers:
- name: restart sshd
service: name=sshd state=restarted |