EdgeRouter Fail2Ban settings persistence after upgrades

A prior post details installing and configure Fail2Ban on a Ubiquiti EdgeRouter. Additions installed on EdgeRouters do not persist through upgrades because new install images overwrite the filesystem. The following method automatically re-installs Fail2Ban and restores prior settings.

Copy Fail2Ban configurations from the previous post into /config and create symlinks from the old location to the new:

sudo -i
mkdir /config/fail2ban
mkdir /config/fail2ban/filter.d
mv /etc/fail2ban/filter.d/openvpn.local /config/fail2ban/filter.d/
mv /etc/fail2ban/jail.local /config/fail2ban/
rm /etc/fail2ban/jail.local
ln -s /config/fail2ban/jail.local /etc/fail2ban/jail.local
ln -s /config/fail2ban/filter.d/openvpn.local /etc/fail2ban/filter.d/openvpn.local
You may wish to confirm that Fail2Ban still works after a service fail2ban restart

Next, use vi to create a file at /config/scripts/post-config.d/install_fail2ban.sh with the content:

if [ -e $doneit ]; then
exit 0
mount -t tmpfs -o size=30% tmpfs /var/lib/apt/lists
if [ $? != 0 ]; then
echo Could not mount tmpfs on /var/lib/apt/lists
exit 1
DEBIAN_FRONTEND=noninteractive apt-get update apt-get –no-install-recommends install -y $packages

if [ $? == 0 ]; then
echo Package install successful
ln -s /config/fail2ban/jail.local /etc/fail2ban/jail.local
ln -s /config/fail2ban/filter.d/openvpn.local /etc/fail2ban/filter.d/openvpn.local
service fail2ban restart
touch $doneit
echo Package install failed
umount /var/lib/apt/lists
exit 0
Make sure that the script is executable via chmod 744 /config/scripts/post-config.d/install_fail2ban.sh

You should now be able to upgrade the router normally and the package and configuration will be automatically restored.

Note: If you are running an ER-X or ER-X-SFP, these may not have enough storage space to successfully install the software, in which case, you will need to delete the old system image via delete system image before the script can run successfully. After doing so, run the script manually via sudo /config/scripts/post-config.d/install_fail2ban.sh or reboot the router again.