Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- from __future__ import absolute_import, division, print_function
- __author__ = "Sebastian Kroczek"
- __copyright__ = "Copyright 2018"
- __credits__ = ["Sebastian Kroczek"]
- __license__ = "MIT"
- __email__ = "me@xbug.de"
- __status__ = "Prototype"
- import io
- import os
- from configobj import ConfigObj
- from ansible.module_utils.basic import AnsibleModule
- def cmp(d1, d2):
- if d1 == d2:
- return True
- if not isinstance(d1, dict) and not isinstance(d2, dict):
- return False
- for k in d1.keys():
- if k not in d2.keys():
- return False
- elif isinstance(d1[k], dict):
- if not cmp(d1[k], d2[k]):
- return False
- elif d1[k] != d2[k]:
- return False
- return True
- def find(key, cfg):
- parts = key.split(".", 1)
- if len(parts) > 1:
- if isinstance(cfg[parts[0]], dict):
- return find(parts[1], cfg[parts[0]])
- else:
- return None
- return cfg[parts[0]]
- def delete(key, cfg):
- parts = key.split(".", 1)
- if len(parts) > 1:
- delete(parts[1], cfg[parts[0]])
- return
- del (cfg[parts[0]])
- def set_value(key, value, cfg):
- parts = key.split(".", 1)
- if len(parts) > 1:
- try:
- ncfg = cfg[parts[0]]
- except KeyError:
- ncfg = cfg[parts[0]] = {}
- set_value(parts[1], value, ncfg)
- return
- cfg[parts[0]] = value
- def main():
- arg_spec = dict(
- path=dict(required=True, type='path'),
- state=dict(default='present', choices=['present', 'absent', 'read']),
- key=dict(required=True),
- section=dict(type='dict'),
- value=dict(),
- )
- module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True)
- path = str(os.path.expanduser(module.params['path']))
- key = module.params['key']
- state = module.params['state']
- section = module.params['section']
- value = module.params['value']
- if 'present' == state and not section and not value:
- module.fail_json(msg="On state 'present' either section or value is required.")
- if 'present' == state and section and value:
- module.fail_json(msg="On state 'present' either section or value must be set, not both.")
- value = value or section
- # create = module.params['create']
- check_mode = module.check_mode
- diff = {'before': '',
- 'after': '',
- 'before_header': '%s (content)' % path,
- 'after_header': '%s (content)' % path}
- cfg = ConfigObj(path)
- before = io.BytesIO()
- cfg.write(before)
- diff['before'] = before.getvalue()
- before.close()
- try:
- cvalue = find(key, cfg=cfg)
- except KeyError:
- if 'read' == state:
- module.fail_json(msg="Key %s do not exist." % key)
- elif "absent" == state:
- module.exit_json(changed=False)
- else:
- cvalue = float('nan')
- if 'read' == state:
- module.exit_json(value=cvalue, changed=False)
- if "absent" == state:
- delete(key, cfg)
- if not check_mode:
- cfg.write()
- after = io.BytesIO()
- cfg.write(after)
- diff['after'] = after.getvalue()
- after.close()
- module.exit_json(changed=True, diff=diff)
- if 'present' == state:
- if cmp(cvalue, value):
- module.exit_json(changed=False)
- set_value(key, value, cfg)
- if not check_mode:
- cfg.write()
- after = io.BytesIO()
- cfg.write(after)
- diff['after'] = after.getvalue()
- after.close()
- module.exit_json(changed=True, diff=diff)
- module.fail_json(msg="Unknown state %s. Known states are: read, present and absent." % state, changed=False)
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment