Debian Codegraph @

ansible_collections/community/general/plugins/modules/osx_defaults.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, GeekChimp - Franck Nijhof <[email protected]> (DO NOT CONTACT!)
4 # Copyright (c) 2019, Ansible project
5 # Copyright (c) 2019, Abhijeet Kasurde <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: osx_defaults
13 author:
14 # DO NOT RE-ADD GITHUB HANDLE!
15 - Franck Nijhof (!UNKNOWN)
16 short_description: Manage macOS user defaults
17 description:
18 - This module allows users to read, write, and delete macOS user defaults from Ansible scripts.
19 - MacOS applications and other programs use the defaults system to record user preferences and other information that must
20 be maintained when the applications are not running (such as default font for new documents, or the position of an Info
21 panel).
22 extends_documentation_fragment:
23 - community.general._attributes
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29 options:
30 domain:
31 description:
32 - The domain is a domain name of the form C(com.companyname.appname).
33 type: str
34 default: NSGlobalDomain
35 host:
36 description:
37 - The host on which the preference should apply.
38 - The special value V(currentHost) corresponds to the C(-currentHost) switch of the defaults commandline tool.
39 type: str
40 key:
41 description:
42 - The key of the user preference.
43 type: str
44 type:
45 description:
46 - The type of value to write.
47 - V(dict) has been added in community.general 12.5.0.
48 type: str
49 choices: [array, bool, boolean, date, dict, float, int, integer, string]
50 default: string
51 check_type:
52 description:
53 - Checks if the type of the provided O(value) matches the type of an existing default.
54 - If the types do not match, raises an error.
55 type: bool
56 default: true
57 version_added: 8.6.0
58 array_add:
59 description:
60 - Add new elements to the array for a key which has an array as its value.
61 type: bool
62 default: false
63 dict_mode:
64 description:
65 - Defines the write behavior for O(type=dict) values.
66 - V(replace) writes the full dictionary, replacing any existing value.
67 - V(add) merges only the specified keys into the existing dictionary, leaving other keys untouched.
68 type: str
69 choices: [replace, add]
70 default: replace
71 version_added: "12.5.0"
72 value:
73 description:
74 - The value to write.
75 - Only required when O(state=present).
76 type: raw
77 state:
78 description:
79 - The state of the user defaults.
80 - If set to V(list) it queries the given parameter specified by O(key). Returns V(null) is nothing found or misspelled.
81 type: str
82 choices: [absent, list, present]
83 default: present
84 path:
85 description:
86 - The path in which to search for C(defaults).
87 type: str
88 default: /usr/bin:/usr/local/bin
89 notes:
90 - Apple Mac caches defaults. You may need to logout and login to apply the changes.
91 """
92
93 EXAMPLES = r"""
94 - name: Set boolean valued key for application domain
95 community.general.osx_defaults:
96 domain: com.apple.Safari
97 key: IncludeInternalDebugMenu
98 type: bool
99 value: true
100 state: present
101
102 - name: Set string valued key for global domain
103 community.general.osx_defaults:
104 domain: NSGlobalDomain
105 key: AppleMeasurementUnits
106 type: string
107 value: Centimeters
108 state: present
109
110 - name: Set int valued key for arbitrary plist
111 community.general.osx_defaults:
112 domain: /Library/Preferences/com.apple.SoftwareUpdate
113 key: AutomaticCheckEnabled
114 type: int
115 value: 1
116 become: true
117
118 - name: Set int valued key only for the current host
119 community.general.osx_defaults:
120 domain: com.apple.screensaver
121 host: currentHost
122 key: showClock
123 type: int
124 value: 1
125
126 - name: Defaults to global domain and setting value
127 community.general.osx_defaults:
128 key: AppleMeasurementUnits
129 type: string
130 value: Centimeters
131
132 - name: Setting an array valued key
133 community.general.osx_defaults:
134 key: AppleLanguages
135 type: array
136 value:
137 - en
138 - nl
139
140 - name: Setting a dict valued key
141 community.general.osx_defaults:
142 domain: com.apple.finder
143 key: FXInfoPanesExpanded
144 type: dict
145 value:
146 General: true
147 OpenWith: true
148 Privileges: true
149
150 - name: Removing a key
151 community.general.osx_defaults:
152 domain: com.geekchimp.macable
153 key: ExampleKeyToRemove
154 state: absent
155 """
156
157 import json
158 import os
159 import re
160 import tempfile
161 from datetime import datetime
162
163 from ansible.module_utils.basic import AnsibleModule
164
165
166 # exceptions --------------------------------------------------------------- {{{
167 class OSXDefaultsException(Exception):
168 def __init__(self, msg):
169 self.message = msg
170
171
172 # /exceptions -------------------------------------------------------------- }}}
173
174
175 # class MacDefaults -------------------------------------------------------- {{{
176 class OSXDefaults:
177 """Class to manage Mac OS user defaults"""
178
179 # init ---------------------------------------------------------------- {{{
180 def __init__(self, module):
181 """Initialize this module. Finds 'defaults' executable and preps the parameters"""
182 # Initial var for storing current defaults value
183 self.current_value = None
184 self.module = module
185 self.domain = module.params["domain"]
186 self.host = module.params["host"]
187 self.key = module.params["key"]
188 self.check_type = module.params["check_type"]
189 self.type = module.params["type"]
190 self.array_add = module.params["array_add"]
191 self.dict_mode = module.params["dict_mode"]
192 self.value = module.params["value"]
193 self.state = module.params["state"]
194 self.path = module.params["path"]
195
196 # Try to find the defaults executable
197 self.executable = self.module.get_bin_path(
198 "defaults",
199 required=False,
200 opt_dirs=self.path.split(":"),
201 )
202
203 if not self.executable:
204 raise OSXDefaultsException("Unable to locate defaults executable.")
205
206 self.plutil = self.module.get_bin_path(
207 "plutil",
208 required=False,
209 opt_dirs=self.path.split(":"),
210 )
211
212 if self.type == "dict" and not self.plutil:
213 raise OSXDefaultsException("Unable to locate plutil executable (required for dict type).")
214
215 # Ensure the value is the correct type
216 if self.state != "absent":
217 self.value = self._convert_type(self.type, self.value)
218
219 # /init --------------------------------------------------------------- }}}
220
221 # tools --------------------------------------------------------------- {{{
222 @staticmethod
223 def is_int(value):
224 as_str = str(value)
225 if as_str.startswith("-"):
226 return as_str[1:].isdigit()
227 else:
228 return as_str.isdigit()
229
230 @staticmethod
231 def _convert_type(data_type, value):
232 """Converts value to given type"""
233 if data_type == "string":
234 return str(value)
235 elif data_type in ["bool", "boolean"]:
236 if isinstance(value, (bytes, str)):
237 value = value.lower()
238 if value in [True, 1, "true", "1", "yes"]:
239 return True
240 elif value in [False, 0, "false", "0", "no"]:
241 return False
242 raise OSXDefaultsException(f"Invalid boolean value: {value!r}")
243 elif data_type == "date":
244 try:
245 return datetime.strptime(value.split("+")[0].strip(), "%Y-%m-%d %H:%M:%S")
246 except ValueError as e:
247 raise OSXDefaultsException(f"Invalid date value: {value!r}. Required format yyy-mm-dd hh:mm:ss.") from e
248 elif data_type in ["int", "integer"]:
249 if not OSXDefaults.is_int(value):
250 raise OSXDefaultsException(f"Invalid integer value: {value!r}")
251 return int(value)
252 elif data_type == "float":
253 try:
254 value = float(value)
255 except ValueError as e:
256 raise OSXDefaultsException(f"Invalid float value: {value!r}") from e
257 return value
258 elif data_type == "array":
259 if not isinstance(value, list):
260 raise OSXDefaultsException("Invalid value. Expected value to be an array")
261 return value
262 elif data_type in ["dict", "dictionary"]:
263 if not isinstance(value, dict):
264 raise OSXDefaultsException("Invalid value. Expected value to be a dict")
265 return value
266
267 raise OSXDefaultsException(f"Type is not supported: {data_type}")
268
269 def _host_args(self):
270 """Returns a normalized list of commandline arguments based on the "host" attribute"""
271 if self.host is None:
272 return []
273 elif self.host == "currentHost":
274 return ["-currentHost"]
275 else:
276 return ["-host", self.host]
277
278 def _base_command(self):
279 """Returns a list containing the "defaults" executable and any common base arguments"""
280 return [self.executable] + self._host_args()
281
282 @staticmethod
283 def _dict_value_to_args(key, val):
284 """Returns the [key, -type, value] tokens for a single dict entry when writing"""
285 if isinstance(val, bool):
286 return [key, "-bool", "TRUE" if val else "FALSE"]
287 elif isinstance(val, int):
288 return [key, "-int", str(val)]
289 elif isinstance(val, float):
290 return [key, "-float", str(val)]
291 else:
292 return [key, "-string", str(val)]
293
294 @staticmethod
295 def _convert_defaults_str_to_list(value):
296 """Converts array output from defaults to an list"""
297 # Split output of defaults. Every line contains a value
298 value = value.splitlines()
299
300 # Remove first and last item, those are not actual values
301 value.pop(0)
302 value.pop(-1)
303
304 # Remove spaces at beginning and comma (,) at the end, unquote and unescape double quotes
305 value = [re.sub('^ *"?|"?,? *$', "", x.replace('\\"', '"')) for x in value]
306
307 return value
308
309 # /tools -------------------------------------------------------------- }}}
310
311 # commands ------------------------------------------------------------ {{{
312 def read(self):
313 """Reads value of this domain & key from defaults"""
314 # First try to find out the type
315 rc, out, err = self.module.run_command(self._base_command() + ["read-type", self.domain, self.key])
316
317 # If RC is 1, the key does not exist
318 if rc == 1:
319 return None
320
321 # If the RC is not 0, then terrible happened! Ooooh nooo!
322 if rc != 0:
323 raise OSXDefaultsException(f"An error occurred while reading key type from defaults: {err}")
324
325 # Ok, lets parse the type from output
326 data_type = out.strip().replace("Type is ", "")
327
328 # Now get the current value
329 rc, out, err = self.module.run_command(self._base_command() + ["read", self.domain, self.key])
330
331 # Strip output
332 out = out.strip()
333
334 # A non zero RC at this point is kinda strange...
335 if rc != 0:
336 raise OSXDefaultsException(f"An error occurred while reading key value from defaults: {err}")
337
338 # Convert string to list when type is array
339 if data_type == "array":
340 out = self._convert_defaults_str_to_list(out)
341 elif data_type == "dictionary":
342 # Export domain plist to a temp file and use plutil -extract for type-preserving JSON conversion.
343 # Reading via 'defaults read' loses boolean type info (booleans appear as 1/0 in old-style plist text).
344 tmp_fd, tmp_path = tempfile.mkstemp(suffix=".plist")
345 os.close(tmp_fd)
346 try:
347 rc2, out2, err2 = self.module.run_command(self._base_command() + ["export", self.domain, tmp_path])
348 if rc2 != 0:
349 raise OSXDefaultsException(f"An error occurred while exporting domain plist: {err2}")
350 rc3, out3, err3 = self.module.run_command(
351 [self.plutil, "-extract", self.key, "json", "-o", "-", tmp_path]
352 )
353 if rc3 != 0:
354 raise OSXDefaultsException(f"An error occurred while extracting dict value via plutil: {err3}")
355 out = json.loads(out3)
356 finally:
357 if os.path.exists(tmp_path):
358 os.unlink(tmp_path)
359
360 # Store the current_value
361 self.current_value = self._convert_type(data_type, out)
362
363 def write(self):
364 """Writes value to this domain & key to defaults"""
365 if self.type == "dict":
366 effective_type = "dict-add" if (self.dict_mode == "add" and self.current_value is not None) else "dict"
367 tokens = []
368 for k, v in self.value.items():
369 tokens.extend(self._dict_value_to_args(str(k), v))
370 rc, out, err = self.module.run_command(
371 self._base_command() + ["write", self.domain, self.key, f"-{effective_type}"] + tokens,
372 expand_user_and_vars=False,
373 )
374 if rc != 0:
375 raise OSXDefaultsException(f"An error occurred while writing value to defaults: {err}")
376 return
377
378 # We need to convert some values so the defaults commandline understands it
379 if isinstance(self.value, bool):
380 if self.value:
381 value = "TRUE"
382 else:
383 value = "FALSE"
384 elif isinstance(self.value, (int, float)):
385 value = str(self.value)
386 elif self.array_add and self.current_value is not None:
387 value = list(set(self.value) - set(self.current_value))
388 elif isinstance(self.value, datetime):
389 value = self.value.strftime("%Y-%m-%d %H:%M:%S")
390 else:
391 value = self.value
392
393 # When the type is array and array_add is enabled, morph the type :)
394 if self.type == "array" and self.array_add:
395 self.type = "array-add"
396
397 # All values should be a list, for easy passing it to the command
398 if not isinstance(value, list):
399 value = [value]
400
401 rc, out, err = self.module.run_command(
402 self._base_command() + ["write", self.domain, self.key, f"-{self.type}"] + value, expand_user_and_vars=False
403 )
404
405 if rc != 0:
406 raise OSXDefaultsException(f"An error occurred while writing value to defaults: {err}")
407
408 def delete(self):
409 """Deletes defaults key from domain"""
410 rc, out, err = self.module.run_command(self._base_command() + ["delete", self.domain, self.key])
411 if rc != 0:
412 raise OSXDefaultsException(f"An error occurred while deleting key from defaults: {err}")
413
414 # /commands ----------------------------------------------------------- }}}
415
416 # run ----------------------------------------------------------------- {{{
417 """ Does the magic! :) """
418
419 def run(self):
420 # Get the current value from defaults
421 self.read()
422
423 if self.state == "list":
424 self.module.exit_json(key=self.key, value=self.current_value)
425
426 # Handle absent state
427 if self.state == "absent":
428 if self.current_value is None:
429 return False
430 if self.module.check_mode:
431 return True
432 self.delete()
433 return True
434
435 # Check if there is a type mismatch, e.g. given type does not match the type in defaults
436 if self.check_type:
437 value_type = type(self.value)
438 if self.current_value is not None and not isinstance(self.current_value, value_type):
439 raise OSXDefaultsException(f"Type mismatch. Type in defaults: {type(self.current_value).__name__}")
440
441 # Current value matches the given value. Nothing need to be done. Arrays need extra care
442 if (
443 self.type == "array"
444 and self.current_value is not None
445 and not self.array_add
446 and set(self.current_value) == set(self.value)
447 ):
448 return False
449 elif (
450 self.type == "array"
451 and self.current_value is not None
452 and self.array_add
453 and len(list(set(self.value) - set(self.current_value))) == 0
454 ):
455 return False
456 elif (
457 self.type == "dict"
458 and self.current_value is not None
459 and self.dict_mode == "add"
460 and all(self.current_value.get(k) == v for k, v in self.value.items())
461 ):
462 return False
463 elif self.current_value == self.value:
464 return False
465
466 if self.module.check_mode:
467 return True
468
469 # Change/Create/Set given key/value for domain in defaults
470 self.write()
471 return True
472
473 # /run ---------------------------------------------------------------- }}}
474
475
476 # /class MacDefaults ------------------------------------------------------ }}}
477
478
479 # main -------------------------------------------------------------------- {{{
480 def main():
481 module = AnsibleModule(
482 argument_spec=dict(
483 domain=dict(type="str", default="NSGlobalDomain"),
484 host=dict(type="str"),
485 key=dict(type="str", no_log=False),
486 check_type=dict(type="bool", default=True),
487 type=dict(
488 type="str",
489 default="string",
490 choices=["array", "bool", "boolean", "date", "dict", "float", "int", "integer", "string"],
491 ),
492 array_add=dict(type="bool", default=False),
493 dict_mode=dict(type="str", default="replace", choices=["replace", "add"]),
494 value=dict(type="raw"),
495 state=dict(type="str", default="present", choices=["absent", "list", "present"]),
496 path=dict(type="str", default="/usr/bin:/usr/local/bin"),
497 ),
498 supports_check_mode=True,
499 required_if=(("state", "present", ["value"]),),
500 )
501 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
502
503 try:
504 defaults = OSXDefaults(module=module)
505 module.exit_json(changed=defaults.run())
506 except OSXDefaultsException as e:
507 module.fail_json(msg=e.message)
508
509
510 # /main ------------------------------------------------------------------- }}}
511
512 if __name__ == "__main__":
513 main()