What is the best way to manage iptables from one point and have the ability to edit something on local server.
We need to add some rules centralized on all servers, but we have specific servers with specific requirements which should have their own set of rules.
I thought about bash script with multiple include which is managed centralized with ansible and includes managed on local server. Is it good approach? Or maybe there is something better?
We can't create yml2 templates for ansible because there is too much difference between specific hosts.
Please provide examples of centralized management of iptables.
ufw
Ansible
has aufw
module in order to handle firewall rules. Inroles/common/tasks/main.yml
, which is included in all my servers, I have (among other things):Edit: It is necessary to allow ssh before setting default policy to "deny" (originally it was opposite above), otherwise you may be locked out in between the two steps.
Then, in each role, I have additional firewall rules for that role. For example, in
roles/nginx/tasks/main.yml
, I have (among other things) this:So all my nginx servers have ports 80 and 443 opened.
This way you can build whatever common configuration you want and add additional rules in more specific roles.
ferm
If you have rules which
ufw
cannot handle, one solution I think would work nicely isferm
; it can do almost anything, and you can configure it to read rules from directories such as/etc/ferm/input.d/
,/etc/ferm/output.d/
,/etc/ferm/forward.d/
, etc. You could make yourcommon
role prepare the essentialferm
configuration and then have other roles drop files in these directories.plain iptables
Your requirement to have
ansible
specify rules in addition to rules specified in another way is unusual and apparently defies most of the point for usingansible
. Unfortunately I don't see any way to do it other than with plainiptables
, which would be quite ugly. Here is an example of opening up port 80 inroles/nginx/tasks/main.yml
(untested):where
Save iptables
is a handler that executesiptables-save
. All the above is quite tedious to write, but it might be appropriate, especially if you have only a few rules to manage withansible
.lineinfile
If you want to manage rules in your iptables configuration without overwriting existing rules or centrally managing iptables in a template, use Ansible's lineinfile module:
Here's the "restart iptables" handler:
I created a role to manage iptables rules with the following features:
Check out mikegleasonjr.firewall on ansible galaxy or on github
We wrote a special module for this called iptables_raw which allows us to easily manage iptables. Everything is explained in this blog post. Here is an example of how to use the module: