I am working with a product on CentOS that occasionally needs to automatically add and remove rules from the iptables configuration. For example, during an update, we want to explicitly refuse inbound service traffic until the update is complete. Currently, the approach being used in the update code is to use sed and other text-handling utilities to comment out the relevant lines in the configuration file, restart the iptables service with the new configuration file, and then reverse the process at the end of the update, and restart the service once again.

It seems to me that a better approach would be to use the iptables -D table rule-specification command at the start of the process, and then iptables -A table rule-specification at the end of the update.

The biggest problem I see with automatically manipulating the configuration file is fragility: there are system tools that rewrite the configuration file, and may reorder parameters etc, possibly breaking the text parsing (service iptables save is an example).

What is the recommended approach to making system configuration changes like this from within code, and why?

1 Answer 1


Most people with this situation handle it with some abstraction.

For example. Instead of having a single file with your rule set, why not build a set of files with your rules and concatenate them together.

For example you might add individual rules into files named like this.


Then just run the rule set with run-parts /etc/iptables-rules. If you need to add another set of rules, just temporarily insert add a file. and then remove as needed.

You should also strongly be looking at setting up and using CHAINS in your configuration. Chains are kind of like sub-routines. You could for example add a rule at the very top of your firewall to jump into a chain. Chains have a default policy of RETURN. So when you needed to add a temporary rule, you just insert it into that CHAIN. When you you longer require it, just flush that particular chain.

  • Thanks for the idea about chains: I will look at that. Breaking the configuration file into multiple sections would make edits less tricky, but really I was looking for pros and cons of editing configuration files and restarting the service, vs adding and subtracting rules dynamically. Oct 3, 2013 at 21:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .