Host firewall configuration backup & restore

Zakir Hossain
2 min readAug 21, 2023

--

Backup is a most important part for any kind of service. Only backup can save if anything goes wrong in service label. It is not possible to take host firewall configuration backup centrally by using any backup solution. First of all we have to take backup manually then we have to copy the backup files to the remote location. But in this case ansible can take place to resolve this issue. We are able to backup the host firewall of the entire Linux system through the use of Ansible.

Scenario:

Pre-requisite

  • ansible installed
  • admin user should be available on each host
  • sudo privileges should be available on each host

Step 01: Ensure admin user and sudo privileges on each host.

Here user could be any user.

# visudo
User_Alias ADMINS = admin
ADMINS ALL=(ALL) ALL

Step 02: Write ansible playbook

# mkdir -p /etc/ansible/backups

# vim /etc/ansible/playbooks/iptables-backup.yaml

---
- hosts: all
become: yes
become_user: root
become_method: sudo
remote_user: admin

tasks:
- name: Take backup of firewall
shell: iptables-save > /tmp/iptables_{{ inventory_hostname }}.txt
register: config

- name: Save output to /etc/ansible/backups
fetch:
src: /tmp/iptables_{{ inventory_hostname }}.txt
dest: /etc/ansible/backups/
flat: yes

Step 03: Prepare host file for ansible

# vim /etc/ansible/hosts

[iptables]
192.168.2.39
192.168.2.105

Step 04: Check syntax of playbook and run.

# ansible-playbook --syntax-check iptables-backup.yaml
# ansible-playbook -l iptables -k -K iptables-backup.yaml

After successfully execution playbook you will get backup file under /etc/ansible/backups directory like below:

iptables_192.168.2.105.txt

Restore procedure:

If you required to restore firewall backup then copy your backup file from ansible server to your respective.

## Login to ansible host
# cd /etc/ansible/backups
# scp iptables_192.168.2.105.txt admin@192.168.2.105:~/

Restore firewall backup.

## Login to 192.168.2.105 server 
# iptables-restore < iptables_192.168.2.105.txt

Above command will replace your exiting firewall rules.

--

--

Zakir Hossain
Zakir Hossain

Written by Zakir Hossain

I'm a tech enthusiast and system administrator with a focus on Open Source application and automation.