How to automate fail2ban with Ansible Part 4
In previous parts we have looked at how we can automate fail2ban using custom ansible module, we wrote few playbooks and created ansible role, however it is not necessary to create ansible module just to automate fail2ban. Fail2ban has a single config file and ansible has all the necessary means to interact with that out of the box. In this article we will take a closer look at this.
Creating Ansible Role for fail2ban
Here is an example of how the playbooks we have created so far could be organized as an ansible role. To create an ansible role using the ansible-galaxy
CLI, you can use the following command:
ansible-galaxy init fail2ban
This will create a new directory called fail2ban
but the structure is going to generic and we need to ensure we end up with the following structure:
fail2ban/
├── defaults
│ └── main.yml
├── handlers
│ └── main.yml
├── tasks
│ └── main.yml
├── templates
│ └── jail.local.j2
└── vars
└── main.yml
The handlers
directory contains tasks that are only run when notified by other tasks. The vars
directory contains variables that can be used throughout the role.
Here is an example of a handler task that restarts the fail2ban service:
# fail2ban/handlers/main.yml
- name: Restart fail2ban service
service:
name: fail2ban
state: restarted
And here is an example of a variables file that defines some default values for the role:
# fail2ban/vars/main.yml
fail2ban_enabled: true
fail2ban_bantime: 10m
fail2ban_findtime: 10m
fail2ban_maxretry: 3
In the tasks/main.yml
file, you can reference these variables like this:
# fail2ban/tasks/main.yml
- name: Install fail2ban package
package:
name: fail2ban
state: present
- name: Configure fail2ban
template:
src: jail.local.j2
dest: /etc/fail2ban/jail.local
notify:
- Restart fail2ban service
The jail.local.j2
template file can reference the variables like this:
[DEFAULT]
bantime = {{ fail2ban_bantime }}
findtime = {{ fail2ban_findtime }}
maxretry = {{ fail2ban_maxretry }}
To use this role in a playbook, you would include it like this:
- hosts: all
roles:
- role: fail2ban
This would install and configure fail2ban on all of the hosts in the all
group, using the default values for the role. You can also override default values by specifying them in the playbook, like this:
- hosts: all
roles:
- role: fail2ban
vars:
fail2ban_enabled: false
fail2ban_bantime: 5m
This would disable fail2ban and set the ban time to 5 minutes on all of the hosts in the all
group, even if the default values for fail2ban_enabled
and fail2ban_bantime
are true
and 10m
, respectively.
Summary
In this article we took a different approach and used template
module to achieve the same we have done in Part 1. Although it is always better to have more knowledge to achieve the same and have more cards up in your sleeve the best practices is "don't reinvent the wheel" and go with the simplest approach that is available out of the box.