2014-10-12 00:20:00 +02:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# (c) 2014, GeekChimp - Franck Nijhof <franck@geekchimp.com>
|
|
|
|
#
|
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
2014-10-12 14:41:57 +02:00
|
|
|
module: osx_defaults
|
2015-06-17 01:19:16 +02:00
|
|
|
author: Franck Nijhof (@frenck)
|
2014-10-12 14:41:57 +02:00
|
|
|
short_description: osx_defaults allows users to read, write, and delete Mac OS X user defaults from Ansible
|
2014-10-12 00:20:00 +02:00
|
|
|
description:
|
2014-10-12 14:41:57 +02:00
|
|
|
- osx_defaults allows users to read, write, and delete Mac OS X user defaults from Ansible scripts.
|
2014-10-12 00:20:00 +02:00
|
|
|
Mac OS X applications and other programs use the defaults system to record user preferences and other
|
|
|
|
information that must be maintained when the applications aren't running (such as default font for new
|
|
|
|
documents, or the position of an Info panel).
|
2015-06-17 01:19:16 +02:00
|
|
|
version_added: "2.0"
|
2014-10-12 00:20:00 +02:00
|
|
|
options:
|
|
|
|
domain:
|
|
|
|
description:
|
|
|
|
- The domain is a domain name of the form com.companyname.appname.
|
|
|
|
required: false
|
|
|
|
default: NSGlobalDomain
|
2015-12-12 18:19:32 +01:00
|
|
|
host:
|
|
|
|
description:
|
|
|
|
- The host on which the preference should apply. The special value "currentHost" corresponds to the
|
|
|
|
"-currentHost" switch of the defaults commandline tool.
|
|
|
|
required: false
|
|
|
|
default: null
|
2016-03-19 13:17:43 +01:00
|
|
|
version_added: "2.1"
|
2014-10-12 00:20:00 +02:00
|
|
|
key:
|
|
|
|
description:
|
|
|
|
- The key of the user preference
|
|
|
|
required: true
|
|
|
|
type:
|
|
|
|
description:
|
|
|
|
- The type of value to write.
|
|
|
|
required: false
|
|
|
|
default: string
|
|
|
|
choices: [ "array", "bool", "boolean", "date", "float", "int", "integer", "string" ]
|
|
|
|
array_add:
|
|
|
|
description:
|
|
|
|
- Add new elements to the array for a key which has an array as its value.
|
|
|
|
required: false
|
2015-06-17 01:19:16 +02:00
|
|
|
default: false
|
2014-10-12 00:20:00 +02:00
|
|
|
choices: [ "true", "false" ]
|
|
|
|
value:
|
|
|
|
description:
|
|
|
|
- The value to write. Only required when state = present.
|
|
|
|
required: false
|
|
|
|
default: null
|
|
|
|
state:
|
|
|
|
description:
|
|
|
|
- The state of the user defaults
|
|
|
|
required: false
|
|
|
|
default: present
|
|
|
|
choices: [ "present", "absent" ]
|
|
|
|
notes:
|
|
|
|
- Apple Mac caches defaults. You may need to logout and login to apply the changes.
|
|
|
|
'''
|
|
|
|
|
|
|
|
EXAMPLES = '''
|
2014-10-12 14:41:57 +02:00
|
|
|
- osx_defaults: domain=com.apple.Safari key=IncludeInternalDebugMenu type=bool value=true state=present
|
|
|
|
- osx_defaults: domain=NSGlobalDomain key=AppleMeasurementUnits type=string value=Centimeters state=present
|
2015-12-12 18:19:32 +01:00
|
|
|
- osx_defaults: domain=com.apple.screensaver host=currentHost key=showClock type=int value=1
|
2014-10-12 14:41:57 +02:00
|
|
|
- osx_defaults: key=AppleMeasurementUnits type=string value=Centimeters
|
|
|
|
- osx_defaults:
|
2014-10-12 00:20:00 +02:00
|
|
|
key: AppleLanguages
|
|
|
|
type: array
|
|
|
|
value: ["en", "nl"]
|
2014-10-12 14:41:57 +02:00
|
|
|
- osx_defaults: domain=com.geekchimp.macable key=ExampleKeyToRemove state=absent
|
2014-10-12 00:20:00 +02:00
|
|
|
'''
|
|
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
# exceptions --------------------------------------------------------------- {{{
|
2014-10-12 14:41:57 +02:00
|
|
|
class OSXDefaultsException(Exception):
|
2014-10-12 00:20:00 +02:00
|
|
|
pass
|
|
|
|
# /exceptions -------------------------------------------------------------- }}}
|
|
|
|
|
|
|
|
# class MacDefaults -------------------------------------------------------- {{{
|
2014-10-12 14:41:57 +02:00
|
|
|
class OSXDefaults(object):
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
""" Class to manage Mac OS user defaults """
|
|
|
|
|
|
|
|
# init ---------------------------------------------------------------- {{{
|
|
|
|
""" Initialize this module. Finds 'defaults' executable and preps the parameters """
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
|
|
|
# Initial var for storing current defaults value
|
|
|
|
self.current_value = None
|
|
|
|
|
|
|
|
# Just set all given parameters
|
|
|
|
for key, val in kwargs.iteritems():
|
|
|
|
setattr(self, key, val)
|
|
|
|
|
|
|
|
# Try to find the defaults executable
|
|
|
|
self.executable = self.module.get_bin_path(
|
|
|
|
'defaults',
|
|
|
|
required=False,
|
|
|
|
opt_dirs=self.path.split(':'),
|
|
|
|
)
|
|
|
|
|
|
|
|
if not self.executable:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Unable to locate defaults executable.")
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# When state is present, we require a parameter
|
|
|
|
if self.state == "present" and self.value is None:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Missing value parameter")
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# Ensure the value is the correct type
|
|
|
|
self.value = self._convert_type(self.type, self.value)
|
|
|
|
|
|
|
|
# /init --------------------------------------------------------------- }}}
|
|
|
|
|
|
|
|
# tools --------------------------------------------------------------- {{{
|
|
|
|
""" Converts value to given type """
|
|
|
|
def _convert_type(self, type, value):
|
|
|
|
|
|
|
|
if type == "string":
|
|
|
|
return str(value)
|
|
|
|
elif type in ["bool", "boolean"]:
|
2016-01-14 18:44:05 +01:00
|
|
|
if isinstance(value, basestring):
|
|
|
|
value = value.lower()
|
|
|
|
if value in [True, 1, "true", "1", "yes"]:
|
2014-10-12 00:20:00 +02:00
|
|
|
return True
|
2016-01-14 18:44:05 +01:00
|
|
|
elif value in [False, 0, "false", "0", "no"]:
|
2014-10-12 00:20:00 +02:00
|
|
|
return False
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Invalid boolean value: {0}".format(repr(value)))
|
2014-10-12 00:20:00 +02:00
|
|
|
elif type == "date":
|
|
|
|
try:
|
|
|
|
return datetime.strptime(value.split("+")[0].strip(), "%Y-%m-%d %H:%M:%S")
|
|
|
|
except ValueError:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException(
|
2014-10-12 00:20:00 +02:00
|
|
|
"Invalid date value: {0}. Required format yyy-mm-dd hh:mm:ss.".format(repr(value))
|
|
|
|
)
|
|
|
|
elif type in ["int", "integer"]:
|
|
|
|
if not str(value).isdigit():
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Invalid integer value: {0}".format(repr(value)))
|
2014-10-12 00:20:00 +02:00
|
|
|
return int(value)
|
|
|
|
elif type == "float":
|
|
|
|
try:
|
|
|
|
value = float(value)
|
|
|
|
except ValueError:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Invalid float value: {0}".format(repr(value)))
|
2014-10-12 00:20:00 +02:00
|
|
|
return value
|
|
|
|
elif type == "array":
|
|
|
|
if not isinstance(value, list):
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Invalid value. Expected value to be an array")
|
2014-10-12 00:20:00 +02:00
|
|
|
return value
|
|
|
|
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException('Type is not supported: {0}'.format(type))
|
2014-10-12 00:20:00 +02:00
|
|
|
|
2015-12-12 18:19:32 +01:00
|
|
|
""" Returns a normalized list of commandline arguments based on the "host" attribute """
|
|
|
|
def _host_args(self):
|
|
|
|
if self.host is None:
|
|
|
|
return []
|
|
|
|
elif self.host == 'currentHost':
|
|
|
|
return ['-currentHost']
|
|
|
|
else:
|
|
|
|
return ['-host', self.host]
|
|
|
|
|
|
|
|
""" Returns a list containing the "defaults" executable and any common base arguments """
|
|
|
|
def _base_command(self):
|
|
|
|
return [self.executable] + self._host_args()
|
|
|
|
|
2014-10-12 00:20:00 +02:00
|
|
|
""" Converts array output from defaults to an list """
|
|
|
|
@staticmethod
|
|
|
|
def _convert_defaults_str_to_list(value):
|
|
|
|
|
|
|
|
# Split output of defaults. Every line contains a value
|
|
|
|
value = value.splitlines()
|
|
|
|
|
|
|
|
# Remove first and last item, those are not actual values
|
|
|
|
value.pop(0)
|
|
|
|
value.pop(-1)
|
|
|
|
|
|
|
|
# Remove extra spaces and comma (,) at the end of values
|
|
|
|
value = [re.sub(',$', '', x.strip(' ')) for x in value]
|
|
|
|
|
|
|
|
return value
|
|
|
|
# /tools -------------------------------------------------------------- }}}
|
|
|
|
|
|
|
|
# commands ------------------------------------------------------------ {{{
|
|
|
|
""" Reads value of this domain & key from defaults """
|
|
|
|
def read(self):
|
|
|
|
# First try to find out the type
|
2015-12-12 18:19:32 +01:00
|
|
|
rc, out, err = self.module.run_command(self._base_command() + ["read-type", self.domain, self.key])
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# If RC is 1, the key does not exists
|
|
|
|
if rc == 1:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# If the RC is not 0, then terrible happened! Ooooh nooo!
|
|
|
|
if rc != 0:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("An error occurred while reading key type from defaults: " + out)
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# Ok, lets parse the type from output
|
|
|
|
type = out.strip().replace('Type is ', '')
|
|
|
|
|
|
|
|
# Now get the current value
|
2015-12-12 18:19:32 +01:00
|
|
|
rc, out, err = self.module.run_command(self._base_command() + ["read", self.domain, self.key])
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# Strip output
|
2014-10-13 07:34:24 +02:00
|
|
|
out = out.strip()
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# An non zero RC at this point is kinda strange...
|
|
|
|
if rc != 0:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("An error occurred while reading key value from defaults: " + out)
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# Convert string to list when type is array
|
|
|
|
if type == "array":
|
|
|
|
out = self._convert_defaults_str_to_list(out)
|
|
|
|
|
|
|
|
# Store the current_value
|
|
|
|
self.current_value = self._convert_type(type, out)
|
|
|
|
|
|
|
|
""" Writes value to this domain & key to defaults """
|
|
|
|
def write(self):
|
|
|
|
|
|
|
|
# We need to convert some values so the defaults commandline understands it
|
|
|
|
if type(self.value) is bool:
|
2015-06-17 15:07:18 +02:00
|
|
|
if self.value:
|
|
|
|
value = "TRUE"
|
|
|
|
else:
|
|
|
|
value = "FALSE"
|
2014-10-12 00:20:00 +02:00
|
|
|
elif type(self.value) is int or type(self.value) is float:
|
|
|
|
value = str(self.value)
|
|
|
|
elif self.array_add and self.current_value is not None:
|
|
|
|
value = list(set(self.value) - set(self.current_value))
|
|
|
|
elif isinstance(self.value, datetime):
|
|
|
|
value = self.value.strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
else:
|
|
|
|
value = self.value
|
|
|
|
|
|
|
|
# When the type is array and array_add is enabled, morph the type :)
|
|
|
|
if self.type == "array" and self.array_add:
|
|
|
|
self.type = "array-add"
|
|
|
|
|
|
|
|
# All values should be a list, for easy passing it to the command
|
|
|
|
if not isinstance(value, list):
|
|
|
|
value = [value]
|
|
|
|
|
2015-12-12 18:19:32 +01:00
|
|
|
rc, out, err = self.module.run_command(self._base_command() + ['write', self.domain, self.key, '-' + self.type] + value)
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
if rc != 0:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException('An error occurred while writing value to defaults: ' + out)
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
""" Deletes defaults key from domain """
|
|
|
|
def delete(self):
|
2015-12-12 18:19:32 +01:00
|
|
|
rc, out, err = self.module.run_command(self._base_command() + ['delete', self.domain, self.key])
|
2014-10-12 00:20:00 +02:00
|
|
|
if rc != 0:
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("An error occurred while deleting key from defaults: " + out)
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# /commands ----------------------------------------------------------- }}}
|
|
|
|
|
|
|
|
# run ----------------------------------------------------------------- {{{
|
|
|
|
""" Does the magic! :) """
|
|
|
|
def run(self):
|
|
|
|
|
|
|
|
# Get the current value from defaults
|
|
|
|
self.read()
|
|
|
|
|
|
|
|
# Handle absent state
|
|
|
|
if self.state == "absent":
|
|
|
|
print "Absent state detected!"
|
|
|
|
if self.current_value is None:
|
|
|
|
return False
|
2016-02-02 15:19:33 +01:00
|
|
|
if self.module.check_mode:
|
|
|
|
return True
|
2014-10-12 00:20:00 +02:00
|
|
|
self.delete()
|
|
|
|
return True
|
|
|
|
|
|
|
|
# There is a type mismatch! Given type does not match the type in defaults
|
|
|
|
if self.current_value is not None and type(self.current_value) is not type(self.value):
|
2014-10-12 14:41:57 +02:00
|
|
|
raise OSXDefaultsException("Type mismatch. Type in defaults: " + type(self.current_value).__name__)
|
2014-10-12 00:20:00 +02:00
|
|
|
|
|
|
|
# Current value matches the given value. Nothing need to be done. Arrays need extra care
|
|
|
|
if self.type == "array" and self.current_value is not None and not self.array_add and \
|
|
|
|
set(self.current_value) == set(self.value):
|
|
|
|
return False
|
|
|
|
elif self.type == "array" and self.current_value is not None and self.array_add and \
|
|
|
|
len(list(set(self.value) - set(self.current_value))) == 0:
|
|
|
|
return False
|
|
|
|
elif self.current_value == self.value:
|
|
|
|
return False
|
|
|
|
|
2016-02-02 15:19:33 +01:00
|
|
|
if self.module.check_mode:
|
|
|
|
return True
|
|
|
|
|
2014-10-12 00:20:00 +02:00
|
|
|
# Change/Create/Set given key/value for domain in defaults
|
|
|
|
self.write()
|
|
|
|
return True
|
|
|
|
|
|
|
|
# /run ---------------------------------------------------------------- }}}
|
|
|
|
|
|
|
|
# /class MacDefaults ------------------------------------------------------ }}}
|
|
|
|
|
|
|
|
|
|
|
|
# main -------------------------------------------------------------------- {{{
|
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec=dict(
|
|
|
|
domain=dict(
|
|
|
|
default="NSGlobalDomain",
|
|
|
|
required=False,
|
|
|
|
),
|
2015-12-12 18:19:32 +01:00
|
|
|
host=dict(
|
|
|
|
default=None,
|
|
|
|
required=False,
|
|
|
|
),
|
2014-10-12 00:20:00 +02:00
|
|
|
key=dict(
|
|
|
|
default=None,
|
|
|
|
),
|
|
|
|
type=dict(
|
|
|
|
default="string",
|
|
|
|
required=False,
|
|
|
|
choices=[
|
|
|
|
"array",
|
|
|
|
"bool",
|
|
|
|
"boolean",
|
|
|
|
"date",
|
|
|
|
"float",
|
|
|
|
"int",
|
|
|
|
"integer",
|
|
|
|
"string",
|
|
|
|
],
|
|
|
|
),
|
|
|
|
array_add=dict(
|
|
|
|
default=False,
|
|
|
|
required=False,
|
2015-12-21 23:39:20 +01:00
|
|
|
type='bool',
|
2014-10-12 00:20:00 +02:00
|
|
|
),
|
|
|
|
value=dict(
|
|
|
|
default=None,
|
|
|
|
required=False,
|
|
|
|
),
|
|
|
|
state=dict(
|
|
|
|
default="present",
|
|
|
|
required=False,
|
|
|
|
choices=[
|
|
|
|
"absent", "present"
|
|
|
|
],
|
|
|
|
),
|
|
|
|
path=dict(
|
|
|
|
default="/usr/bin:/usr/local/bin",
|
|
|
|
required=False,
|
|
|
|
)
|
|
|
|
),
|
|
|
|
supports_check_mode=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
domain = module.params['domain']
|
2015-12-12 18:19:32 +01:00
|
|
|
host = module.params['host']
|
2014-10-12 00:20:00 +02:00
|
|
|
key = module.params['key']
|
|
|
|
type = module.params['type']
|
|
|
|
array_add = module.params['array_add']
|
|
|
|
value = module.params['value']
|
|
|
|
state = module.params['state']
|
|
|
|
path = module.params['path']
|
|
|
|
|
|
|
|
try:
|
2015-12-12 18:19:32 +01:00
|
|
|
defaults = OSXDefaults(module=module, domain=domain, host=host, key=key, type=type,
|
2014-10-12 00:20:00 +02:00
|
|
|
array_add=array_add, value=value, state=state, path=path)
|
|
|
|
changed = defaults.run()
|
|
|
|
module.exit_json(changed=changed)
|
2015-06-17 15:22:10 +02:00
|
|
|
except OSXDefaultsException, e:
|
2014-10-12 00:20:00 +02:00
|
|
|
module.fail_json(msg=e.message)
|
|
|
|
|
|
|
|
# /main ------------------------------------------------------------------- }}}
|
|
|
|
|
|
|
|
from ansible.module_utils.basic import *
|
|
|
|
main()
|