After only three hours of hacking yesterday morning, I’m quite satisfied with my initial results. I was quite surprised and excited to find out that ufw’s CLI parsing is smart enough to realize that the following rules are all identical:
ufw allow 22
ufw allow to any port 22
ufw allow from any to any port 22
This means I don’t have to parse anything myself and can just run the command and trust ufw’s output to determine whether or not applying this changed the firewall state.
Well, almost. Apparently removing a rule that doesn’t actually exist always generates output as if the firewall state had changed. So this is my first bug. But otherwise, it’s functional. This kind of false positive is the same thing that would happen if the command module was used to manipulate ufw, so I don’t consider it a huge detriment, but it’s still something I’d like to fix somehow. (I haven’t checked if this is a known bug with ufw; it’s certainly a bug in my opinion!)
I’m posting this here as a status update and to see if there’s any interest or suggestions. It is not meant as a submission at this point. It’s not documented like the official modules yet but the source is trivial enough to you should be able to follow it.
When I wrote this the general discussion was iptables should be managed with templates. We’ve ultimately moved to a combination: templates as a basis + complex chains while using this module to punch holes for different services/apps that may or may not be on the server.
There are still a few other minor things here and there missing, so its definitely still a work in progress. For example, default policies, and in|out on INTERFACE.
At first I was certain this was not a useful feature, given that insert NUM is only meaningful if you know the ordering of all existing rules. However, I just remembered that ansible’s register clause can be used to access stdout of previous tasks. So I guess this is useful if you grep the output of “ufw status numbered” to determine where to insert your rules. ufw will not re-insert a rule if the only difference is the number.
The alternative to this is to use ansible to insert both rules. Playbook’s tasks are executed in order, so you know the ordering will be correct. However, I guess there is an issue if for some reason the first rule (assuming a pair of rules) gets deleted after the fact… Hmm.
Anyway, I’ve updated my fork today with support for your request as well as “in|out on INTERFACE” which was required for my organization.
What’s the status of the ufw module? I’m looking into how to manage firewalls in Ansible, and since I already somewhat understand the basics of ufw, this sounded good.
I was wondering exactly that, moments ago. I’d love to have a ufw module, even if it’s not perfect.
I found another ufw module in ansible-examples’s riak playbook. I’m glad you’ve pointed out this one though, it looks less hacky than the one in the examples.