Skip to content

Instantly share code, notes, and snippets.

@msimonin
Created October 27, 2016 14:19
Show Gist options
  • Save msimonin/e7cd271f069d6b3f4650b0f7964dd091 to your computer and use it in GitHub Desktop.
Save msimonin/e7cd271f069d6b3f4650b0f7964dd091 to your computer and use it in GitHub Desktop.
ham_json
#!/usr/bin/env python
DOCUMENTATION = '''
---
module: ham_json
short_description: Module for modifying json/yaml files
description:
- A module targeting at modifying json/yaml files
src:
description:
- source file path
dst:
description:
- destination file path (will be a json file)
keyvalues:
description:
- dict of key values that will update the src file
'''
import json
import yaml
def parse_file(src):
src_o = None
with open(src) as src_file:
try:
src_o = json.load(src_file)
except Exception:
pass
if src_o is None:
with open(src) as src_file:
src_o = yaml.load(src_file)
return src_o
def write_file(obj, dst):
with open(dst, 'w') as dst_file:
json.dump(obj, dst_file)
def update(o, d):
"""place modification of o regarding the dict d"""
if not o:
return
if isinstance(o, list):
for v in o:
update(v, d)
elif isinstance(o, dict):
for k, v in o.items():
if k in d.keys():
o[k] = d[k]
else:
update(v, d)
else:
return
def main():
module = AnsibleModule(
argument_spec = dict(
src = dict(required=True),
dst = dict(required=True),
keyvalues = dict(type='dict'),
)
)
src = module.params.pop('src')
dst = module.params.pop('dst')
keyvalues = module.params.pop('keyvalues')
src_o = parse_file(src)
update(src_o, keyvalues)
write_file(src_o, dst)
module.exit_json(result = src_o)
# import module snippets
from ansible.module_utils.basic import * # noqa
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment