Skip to content

Instantly share code, notes, and snippets.

@DazWorrall
Created July 22, 2016 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DazWorrall/379605c9fe2967c8f8682fe422568b77 to your computer and use it in GitHub Desktop.
Save DazWorrall/379605c9fe2967c8f8682fe422568b77 to your computer and use it in GitHub Desktop.
Ansible module to set the default policy on an iptables chain, tested on Debian and derivatives
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
import re
def get_policy(module, table, chain):
command = ['iptables', '-t{}'.format(table), '-L{}'.format(chain)]
rc, out, err = module.run_command(command)
if rc != 0:
raise RuntimeError("Unable to get policy: {}".format(err))
line = out.split('\n')[0].strip()
r = r'Chain \w+ \(policy (\w+)\)'
m = re.search(r, line)
if not m:
raise RuntimeError("Unable to find policy in line: {}".format(line))
return m.group(1)
def set_policy(module, table, chain, policy):
command = ['iptables', '-t{}'.format(table), '-P{}'.format(chain), policy]
rc, out, err = module.run_command(command)
if rc != 0:
raise RuntimeError("Unable to set policy: {}".format(err))
def main() :
module = AnsibleModule(
argument_spec = {
'table': {'required': False, 'default': 'filter'},
'chain': {'required': True},
'policy': {'required': True},
},
supports_check_mode = True,
)
changed = False
p = module.params
table, chain, policy = p['table'], p['chain'].upper(), p['policy'].upper()
try:
current = get_policy(module, table, chain)
if current != policy:
changed = True
if not module.check_mode:
set_policy(module, table, chain, policy)
module.exit_json(changed=changed)
except Exception, e:
msg = 'Failed to set policy {} on chain {} in table {}: {}'
module.fail_json(msg=msg.format(policy, chain, table, str(e)))
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment