Skip to content

Instantly share code, notes, and snippets.

@Jan-Bart
Last active October 7, 2017 12:33
Show Gist options
  • Save Jan-Bart/e5ecd4a782a9685e4d2bbc6264f1bfb1 to your computer and use it in GitHub Desktop.
Save Jan-Bart/e5ecd4a782a9685e4d2bbc6264f1bfb1 to your computer and use it in GitHub Desktop.
This will do the basic setup after getting your hands on a new server. It will create a new user, disable the root user and install/configure ufw, fail2ban, logwatch and postfix.
# Based on: https://ryaneschinger.com/blog/securing-a-server-with-ansible/
- hosts: all
gather_facts: false
pre_tasks:
- name: install python needed for ansible modules to work
raw: sudo bash -c "test -e /usr/bin/python || (apt -qqy update && apt install -qy python-minimal)"
tasks:
- name: Include vars from config.yml.
include_vars:
file: config.yml
- name: Add server user
user: name={{ ubuntu_common_server_user_name }}
password="{{ ubuntu_common_server_password | password_hash('sha512') }}"
shell=/bin/bash
update_password=always
- name: Add authorized keys for server user
authorized_key: user={{ ubuntu_common_server_user_name }} key="{{ lookup('file', item) }}"
with_items: "{{ ubuntu_common_server_public_keys }}"
- name: Add server user to sudoers
lineinfile: dest=/etc/sudoers
regexp="{{ ubuntu_common_server_user_name }} ALL"
line="{{ ubuntu_common_server_user_name }} ALL=(ALL) ALL"
state=present
- name: update APT package cache
apt: update_cache=yes cache_valid_time=3600
- name: Upgrade APT to the latest packages
apt: upgrade=safe
- name: Install required packages
apt: state=installed pkg={{ item }}
with_items:
"{{ ubuntu_common_required_packages }}"
- name: Setup ufw
ufw: state=enabled policy=deny
- name: Allow ssh traffic
ufw: rule=allow port={{ ubuntu_common_ssh_port}} proto=tcp
- name: Set up Postfix to relay mail
debconf: name=postfix
question='{{ item.question }}'
value='{{ item.value }}'
vtype='{{ item.vtype }}'
with_items:
- { question: 'postfix/mailname', value: "{{ postfix_mailname_domain }}", vtype: 'string' }
- { question: 'postfix/main_mailer_type', value: 'Internet Site', vtype: 'string' }
- name: Email log summary daily
lineinfile: dest=/etc/cron.daily/00logwatch
regexp="^/usr/sbin/logwatch"
line="/usr/sbin/logwatch --output mail --mailto {{ ubuntu_common_logwatch_email }} --detail high"
state=present create=yes
- name: Disallow password authentication
lineinfile: dest=/etc/ssh/sshd_config
regexp="^PasswordAuthentication"
line="PasswordAuthentication no"
state=present
notify: Restart ssh
- name: Disallow root SSH access
lineinfile: dest=/etc/ssh/sshd_config
regexp="^PermitRootLogin"
line="PermitRootLogin no"
state=present
notify: Restart ssh
tags:
- danger
handlers:
- name: Restart ssh
service: name=ssh state=restarted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment