We’ll be using Ansible to change and maintain our firewall settings on a server.
The playbook will do the following.
- Set the default zone to drop (Drops all external traffic to server)
- Set a zone for internal access
- Allow access from RFC1918 addresses to internal zone (Any local IP address will be able to access the server)
- Enable the services and ports specified in the vars section
- Disable the services listed in firewall_disable_services variable
Modify the variables as needed for your server(s). You can also add or move the variables to the inventory or host_vars files.
If you need to create an inventory file, refer to the first part of this post
BE CAREFUL CHANGING FIREWALL SETTINGS!!! IMPROPER SETTINGS COULD RENDER THE SERVER INACCESSIBLE!!!
Playbook for firewalld
Change the variables under the vars section
---
- name: Configure firewalld
hosts: rhel
gather_facts: yes
become: yes
vars:
firewall_allowed_ips:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
firewall_allowed_services:
- ssh
- https
- snmp
firewall_allowed_ports:
- "2222/tcp"
firewall_disable_services:
- cockpit
- dhcpv6-client
- mdns
- samba-client
tasks:
- name: Set default zone to drop
ansible.builtin.command: firewall-cmd --set-default-zone=drop
register: default_zone_set
changed_when:
- '"ZONE_ALREADY_SET" not in default_zone_set.stderr'
- name: Enable and allow access to internal zone from RFC1918 addresses
ansible.posix.firewalld:
source: "{{ item }}"
zone: internal
permanent: true
immediate: true
state: enabled
with_items: "{{ firewall_allowed_ips }}"
- name: Disable unused services for internal zone
ansible.posix.firewalld:
service: "{{ item }}"
zone: internal
permanent: true
immediate: true
state: disabled
with_items: "{{ firewall_disable_services }}"
- name: Set services for internal zone
ansible.posix.firewalld:
service: "{{ item }}"
zone: internal
permanent: true
immediate: true
state: enabled
with_items: "{{ firewall_allowed_services }}"
- name: Set custom ports for internal zone
ansible.posix.firewalld:
port: "{{ item }}"
zone: internal
permanent: true
immediate: true
state: enabled
with_items: "{{ firewall_allowed_ports }}"
Helpful links
https://stackoverflow.com/questions/51563643/how-to-change-firewalld-zone-using-ansible