Managing iptables using ansible (V2)

Stephen Shirley
1 min readFeb 16, 2019

After some helpful feedback on my previous version (thanks gus!) of making it safe to remotely apply iptables changes using ansible, here’s an updated approach.

My first attempt was a bit overly complex thanks to trying to use iptables-apply (which expects interactive input), but more importantly, it was fundamentally racy. It assumed that the background job spawned by the “Apply rules.v4” task would have run iptables-apply before the task that signalled that connectivity still worked. While this would be true in 99% of cases, there’s still a tiny chance that you’re deploying a broken rule set and the machine is heavily loaded, the failsafe could get bypassed and you lose connectivity.

With the above in mind, it became clear that the task that applies the updated rules must not return before the background task has executed iptables-restore. This meant that iptables-apply could no longer be used, so I might as well write an equivalent just for this sort of automated environment.

Below is the github repo the new version. It contains 2 files, the ansible role, and ansible-iptables-apply.sh. It requires ansible version ≥ 2.6.8.

--

--