summaryrefslogtreecommitdiffstats
path: root/ansible/library/json_add.py
blob: 6aad2d7c53084b230e03100a93a2529bf8fb10f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/python

from ansible.module_utils.basic import AnsibleModule
import json
import os

DOCUMENTATION="""
---
module: json_add
descritption:
  - This module will search top level objects in json and adds specified
    value into list for specified key.
  - If file does not exists module will create it automatically.

options:
  path:
    required: true
    aliases=[name, destfile, dest]
    description:
      - The json file to modify.
  key:
    required: true
    description:
      - Top level object.
  value:
    required: true
    description:
      - Value to add to specified key.
"""

def load_json(path):
    if os.path.exists(path):
        with open(path, 'r') as f:
          return json.load(f)
    else:
        return {}

def value_is_set(path, key, value, json_obj):
    return value in json_obj.get(key, [])

def insert_to_json(path, key, value, check_mode=False):
    json_obj = load_json(path)
    if not value_is_set(path, key, value, json_obj):
        if not check_mode:
            json_obj.setdefault(key, []).append(value)
            store_json(path, json_obj)
        return True, 'Value %s added to %s.' % (value, key)
    else:
        return False, ''

def store_json(path, json_obj):
    with open(path, 'w') as f:
        json.dump(json_obj, f, indent=4)

def check_file_attrs(module, changed, message, diff):
    file_args = module.load_file_common_arguments(module.params)
    if module.set_fs_attributes_if_different(file_args, False, diff=diff):

        if changed:
            message += ' '
        changed = True
        message += 'File attributes changed.'

    return changed, message

def run_module():
    module = AnsibleModule(
        argument_spec=dict(
        path=dict(type='path', required=True, aliases=['name', 'destfile', 'dest']),
        key=dict(type='str', required=True),
        value=dict(type='str', required=True),
        ),
        add_file_common_args=True,
        supports_check_mode=True
    )
    params = module.params
    path = params['path']
    key = params['key']
    value = params['value']
    try:
        changed, msg = insert_to_json(path, key, value, module.check_mode)
        fs_diff = {}
        changed, msg = check_file_attrs(module, changed, msg, fs_diff)
        module.exit_json(changed=changed, msg=msg, file_attr_diff=fs_diff)
    except IOError as e:
        module.fail_json(msg=e.msg)

if __name__ == '__main__':
    run_module()