Skip to content

Instantly share code, notes, and snippets.

@bibby
Last active May 4, 2016 07:04
Show Gist options
  • Save bibby/10759888a9551d4a875b5343c52697c3 to your computer and use it in GitHub Desktop.
Save bibby/10759888a9551d4a875b5343c52697c3 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import os
from StringIO import StringIO
from ConfigParser import ConfigParser, NoOptionError
DOCUMENTATION = '''
---
module: directadmincfg
short_description: Sets options to a direct admin options conf
description:
- Sets options to a direct admin options config
Returning a list of changed options (with before and after values),
as well as a flag indicating that the software should be recompiled
requirements: [ ]
author:
- "bibby"
options:
dest:
description:
- 'path to the file being managed.'
required: true
default: '/usr/local/directadmin/custombuild/options.conf'
options:
description:
- A dict of config options to apply set within the config file.
New additions are cited as changes.
Does NOT remove unmentioned items.
required: true
'''
EXAMPLES = '''
# set some options to the config at the default location
- name: options test
register: reconfigured
directadmincfg:
options:
foo: yup
bar: nope
- name: recompile if needed
shell: /bin/true
when: reconfigured.recompile
notify: recompile direct admin
- debug:
var: reconfigured
'''
recompile_options = ['bar']
FAKE_SECTION = 'fakesec'
DEFAULT_DA_CONFIG = '/usr/local/directadmin/custombuild/options.conf'
# http://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '['+ FAKE_SECTION +']\n'
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def main():
module = AnsibleModule(
argument_spec = dict(
dest = dict(default=DEFAULT_DA_CONFIG),
options = dict(required=True, type='dict'),
)
)
params = module.params
dest = params['dest']
options = params['options']
changed = False
changed_options = {}
recompile = False
config = ConfigParser()
if os.path.isfile(dest):
config.readfp(FakeSecHead(open(dest)))
else:
config.readfp(FakeSecHead(StringIO()))
for k, v in options.items():
try:
n = config.get(FAKE_SECTION, k)
except NoOptionError:
n = None
v = str(v)
if not n or v != n:
changed_options[k] = dict(before=n, after=v)
changed = True
config.set(FAKE_SECTION, k, v)
if k in recompile_options:
recompile = True
config_str = StringIO()
config.write(config_str)
# chop fake section header
lines = config_str.getvalue().split("\n")[1:]
with open(dest, 'w') as f:
f.write('\n'.join(lines))
module.exit_json(changed=changed,
changed_options=changed_options,
recompile=recompile)
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment