This repository has been archived by the owner on Aug 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
plist_file.py
116 lines (97 loc) · 2.69 KB
/
plist_file.py
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/python
#
# (c) 2015, Matthias Neugebauer
DOCUMENTATION = '''
---
module: plist_file
author: Matthias Neugebauer
short_description: Manage settings in plist files
description:
- Manage settings in plist files.
options:
dest:
description:
- Domain or absolut path to the plist file; file will be created if required.
required: true
default: null
value:
description:
- Value which sould be set.
required: true
default: null
key:
description:
- Key to manage.
required: false
default: null
requirements: [ "biplist" ]
'''
EXAMPLES = '''
plist_file:
dest: /tmp/ansible.modules.plist.test.plist
key: testString
value: myString
plist_file:
dest: ansible.modules.plist.test
key: testInt
value: 7
'''
import sys
import collections
try:
import biplist
except ImportError:
print("failed=True msg='biplist required for this module'")
sys.exit(1)
def do_plist(module, filename, value, key=None):
working_value = value if key == None else {key: value}
changed = False
try:
f = open(filename)
plist = biplist.readPlist(f)
except:
plist = dict()
changed = not equal(plist, working_value)
if changed and not module.check_mode:
try:
update(plist, working_value)
f = open(filename, 'w')
biplist.writePlist(plist, f)
except Exception as e:
module.fail_json(msg="Can't change %s" % filename, error=str(e))
return changed
def equal(slave, master):
if isinstance(slave, collections.Mapping) and isinstance(master, collections.Mapping):
for k, v in master.iteritems():
if not equal(slave.get(k), v):
return False
else:
return master == slave
return True
def update(d, u):
"""Taken from http://stackoverflow.com/a/3233356"""
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
def main():
module = AnsibleModule(
argument_spec = dict(
dest = dict(required=True),
value = dict(required=True, type='raw'),
key = dict(required=False)
),
supports_check_mode=True
)
if not module.params['dest'].startswith('/'):
module.params['dest'] = os.path.expanduser("~/Library/Preferences/%s.plist" % module.params['dest'])
dest = module.params['dest']
key = module.params['key']
value = module.params['value']
changed = do_plist(module, dest, value, key)
module.exit_json(dest=dest, changed=changed, msg="OK")
from ansible.module_utils.basic import *
main()