Petr OspalĂ˝ | 5946751 | 2018-12-19 13:28:29 +0100 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | from ansible.module_utils.basic import AnsibleModule |
| 4 | import json |
| 5 | import os |
| 6 | |
| 7 | DOCUMENTATION=""" |
| 8 | --- |
| 9 | module: json_add |
| 10 | descritption: |
| 11 | - This module will search top level objects in json and adds specified |
| 12 | value into list for specified key. |
| 13 | - If file does not exists module will create it automatically. |
| 14 | |
| 15 | options: |
| 16 | path: |
| 17 | required: true |
| 18 | aliases=[name, destfile, dest] |
| 19 | description: |
| 20 | - The json file to modify. |
| 21 | key: |
| 22 | required: true |
| 23 | description: |
| 24 | - Top level object. |
| 25 | value: |
| 26 | required: true |
| 27 | description: |
| 28 | - Value to add to specified key. |
| 29 | """ |
| 30 | |
| 31 | def load_json(path): |
| 32 | if os.path.exists(path): |
| 33 | with open(path, 'r') as f: |
| 34 | return json.load(f) |
| 35 | else: |
| 36 | return {} |
| 37 | |
| 38 | def value_is_set(path, key, value, json_obj): |
| 39 | return value in json_obj.get(key, []) |
| 40 | |
| 41 | def insert_to_json(path, key, value, check_mode=False): |
| 42 | json_obj = load_json(path) |
| 43 | if not value_is_set(path, key, value, json_obj): |
| 44 | if not check_mode: |
| 45 | json_obj.setdefault(key, []).append(value) |
| 46 | store_json(path, json_obj) |
| 47 | return True, 'Value %s added to %s.' % (value, key) |
| 48 | else: |
| 49 | return False, '' |
| 50 | |
| 51 | def store_json(path, json_obj): |
| 52 | with open(path, 'w') as f: |
| 53 | json.dump(json_obj, f, indent=4) |
| 54 | |
| 55 | def check_file_attrs(module, changed, message, diff): |
| 56 | file_args = module.load_file_common_arguments(module.params) |
| 57 | if module.set_fs_attributes_if_different(file_args, False, diff=diff): |
| 58 | |
| 59 | if changed: |
| 60 | message += ' ' |
| 61 | changed = True |
| 62 | message += 'File attributes changed.' |
| 63 | |
| 64 | return changed, message |
| 65 | |
| 66 | def run_module(): |
| 67 | module = AnsibleModule( |
| 68 | argument_spec=dict( |
| 69 | path=dict(type='path', required=True, aliases=['name', 'destfile', 'dest']), |
| 70 | key=dict(type='str', required=True), |
| 71 | value=dict(type='str', required=True), |
| 72 | ), |
| 73 | add_file_common_args=True, |
| 74 | supports_check_mode=True |
| 75 | ) |
| 76 | params = module.params |
| 77 | path = params['path'] |
| 78 | key = params['key'] |
| 79 | value = params['value'] |
| 80 | try: |
| 81 | changed, msg = insert_to_json(path, key, value, module.check_mode) |
| 82 | fs_diff = {} |
| 83 | changed, msg = check_file_attrs(module, changed, msg, fs_diff) |
| 84 | module.exit_json(changed=changed, msg=msg, file_attr_diff=fs_diff) |
| 85 | except IOError as e: |
| 86 | module.fail_json(msg=e.msg) |
| 87 | |
| 88 | if __name__ == '__main__': |
| 89 | run_module() |
| 90 | |