| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2017, Branko Majic <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: dconf |
| 11 |
author: |
| 12 |
- "Branko Majic (@azaghal)" |
| 13 |
short_description: Modify and read dconf database |
| 14 |
description: |
| 15 |
- This module allows modifications and reading of C(dconf) database. The module is implemented as a wrapper around C(dconf) |
| 16 |
tool. Please see the dconf(1) man page for more details. |
| 17 |
- Since C(dconf) requires a running D-Bus session to change values, the module tries to detect an existing session and reuse |
| 18 |
it, or run the tool using C(dbus-run-session). Both C(dbus-daemon) and C(dbus-broker) are supported. |
| 19 |
requirements: |
| 20 |
- Optionally the C(gi.repository) Python library (usually included in the OS on hosts which have C(dconf)); this is to become |
| 21 |
a non-optional requirement in a future major release of community.general. |
| 22 |
notes: |
| 23 |
- This module depends on C(psutil) Python library (version 4.0.0 and upwards), C(dconf), and either C(dbus-send) or C(busctl) |
| 24 |
for D-Bus session validation, and C(dbus-run-session) as a fallback when no existing session is found. |
| 25 |
Depending on distribution you are using, you may need to install additional packages to have these available. |
| 26 |
Both the reference C(dbus-daemon) implementation and C(dbus-broker) are supported. |
| 27 |
- This module uses the C(gi.repository) Python library when available for accurate comparison of values in C(dconf) to values |
| 28 |
specified in Ansible code. C(gi.repository) is likely to be present on most systems which have C(dconf) but may not be |
| 29 |
present everywhere. When it is missing, a simple string comparison between values is used, and there may be false positives, |
| 30 |
that is, Ansible may think that a value is being changed when it is not. This fallback is to be removed in version 15.0.0 |
| 31 |
of this collection, at which point the module C(gi.repository) is going to be required. |
| 32 |
- The library C(gi.repository) is usually provided by operating system packages (C(python3-gi) for Ubuntu/Debian, |
| 33 |
C(python3-gobject) for Red Hat/Fedora, C(python-gobject) for Arch Linux, to mention a few). |
| 34 |
It is available in PyPI as C(PyGObject) but it only provides bindings for system libraries, so using the system packages |
| 35 |
is highly recommended over installing it with C(pip). |
| 36 |
- Detection of existing, running D-Bus session, required to change settings using C(dconf), is not 100% reliable due to |
| 37 |
implementation details of D-Bus daemon itself. This might lead to running applications not picking-up changes on-the-fly |
| 38 |
if options are changed using Ansible and C(dbus-run-session). |
| 39 |
- Keep in mind that the C(dconf) CLI tool, which this module wraps around, utilises an unusual syntax for the values (GVariant). |
| 40 |
For example, if you wanted to provide a string value, the correct syntax would be O(value="'myvalue'") - with single quotes |
| 41 |
as part of the Ansible parameter value. |
| 42 |
- When using loops in combination with a value like V("[('xkb', 'us'\), ('xkb', 'se'\)]"), you need to be aware of possible |
| 43 |
type conversions. Applying a filter V({{ item.value | string }}) to the parameter variable can avoid potential conversion |
| 44 |
problems. |
| 45 |
- The easiest way to figure out exact syntax/value you need to provide for a key is by making the configuration change in |
| 46 |
application affected by the key, and then having a look at value set using commands C(dconf dump /path/to/dir/) or C(dconf |
| 47 |
read /path/to/key). |
| 48 |
extends_documentation_fragment: |
| 49 |
- community.general._attributes |
| 50 |
attributes: |
| 51 |
check_mode: |
| 52 |
support: full |
| 53 |
diff_mode: |
| 54 |
support: none |
| 55 |
options: |
| 56 |
key: |
| 57 |
type: str |
| 58 |
required: true |
| 59 |
description: |
| 60 |
- A dconf key to modify or read from the dconf database. |
| 61 |
value: |
| 62 |
type: raw |
| 63 |
description: |
| 64 |
- Value to set for the specified dconf key. Value should be specified in GVariant format. Due to complexity of this |
| 65 |
format, it is best to have a look at existing values in the dconf database. |
| 66 |
- Required for O(state=present). |
| 67 |
- Although the type is specified as "raw", it should typically be specified as a string. However, boolean values in |
| 68 |
particular are handled properly even when specified as booleans rather than strings (in fact, handling booleans properly |
| 69 |
is why the type of this parameter is "raw"). |
| 70 |
state: |
| 71 |
type: str |
| 72 |
default: present |
| 73 |
choices: ['read', 'present', 'absent'] |
| 74 |
description: |
| 75 |
- The action to take upon the key/value. |
| 76 |
""" |
| 77 |
|
| 78 |
RETURN = r""" |
| 79 |
value: |
| 80 |
description: Value associated with the requested key. |
| 81 |
returned: success, state was "read" |
| 82 |
type: str |
| 83 |
sample: "'Default'" |
| 84 |
""" |
| 85 |
|
| 86 |
EXAMPLES = r""" |
| 87 |
- name: Configure available keyboard layouts in Gnome |
| 88 |
community.general.dconf: |
| 89 |
key: "/org/gnome/desktop/input-sources/sources" |
| 90 |
value: "[('xkb', 'us'), ('xkb', 'se')]" |
| 91 |
state: present |
| 92 |
|
| 93 |
- name: Read currently available keyboard layouts in Gnome |
| 94 |
community.general.dconf: |
| 95 |
key: "/org/gnome/desktop/input-sources/sources" |
| 96 |
state: read |
| 97 |
register: keyboard_layouts |
| 98 |
|
| 99 |
- name: Reset the available keyboard layouts in Gnome |
| 100 |
community.general.dconf: |
| 101 |
key: "/org/gnome/desktop/input-sources/sources" |
| 102 |
state: absent |
| 103 |
|
| 104 |
- name: Configure available keyboard layouts in Cinnamon |
| 105 |
community.general.dconf: |
| 106 |
key: "/org/gnome/libgnomekbd/keyboard/layouts" |
| 107 |
value: "['us', 'se']" |
| 108 |
state: present |
| 109 |
|
| 110 |
- name: Read currently available keyboard layouts in Cinnamon |
| 111 |
community.general.dconf: |
| 112 |
key: "/org/gnome/libgnomekbd/keyboard/layouts" |
| 113 |
state: read |
| 114 |
register: keyboard_layouts |
| 115 |
|
| 116 |
- name: Reset the available keyboard layouts in Cinnamon |
| 117 |
community.general.dconf: |
| 118 |
key: "/org/gnome/libgnomekbd/keyboard/layouts" |
| 119 |
state: absent |
| 120 |
|
| 121 |
- name: Disable desktop effects in Cinnamon |
| 122 |
community.general.dconf: |
| 123 |
key: "/org/cinnamon/desktop-effects" |
| 124 |
value: "false" |
| 125 |
state: present |
| 126 |
""" |
| 127 |
|
| 128 |
|
| 129 |
import os |
| 130 |
import sys |
| 131 |
|
| 132 |
from ansible.module_utils.basic import AnsibleModule |
| 133 |
from ansible.module_utils.common.respawn import ( |
| 134 |
has_respawned, |
| 135 |
probe_interpreters_for_module, |
| 136 |
respawn_module, |
| 137 |
) |
| 138 |
|
| 139 |
from ansible_collections.community.general.plugins.module_utils import _deps as deps |
| 140 |
|
| 141 |
glib_module_name = "gi.repository.GLib" |
| 142 |
|
| 143 |
try: |
| 144 |
from gi.repository.GLib import GError, Variant |
| 145 |
except ImportError: |
| 146 |
Variant = None |
| 147 |
GError = AttributeError |
| 148 |
|
| 149 |
with deps.declare("psutil"): |
| 150 |
import psutil |
| 151 |
|
| 152 |
|
| 153 |
class DBusWrapper: |
| 154 |
""" |
| 155 |
Helper class that can be used for running a command with a working D-Bus |
| 156 |
session. |
| 157 |
|
| 158 |
If possible, command will be run against an existing D-Bus session, |
| 159 |
otherwise the session will be spawned via dbus-run-session. |
| 160 |
|
| 161 |
Discovery order: |
| 162 |
1. DBUS_SESSION_BUS_ADDRESS in the current process environment |
| 163 |
2. /run/user/<uid>/bus -- canonical socket for systemd and dbus-broker |
| 164 |
3. Process scan for DBUS_SESSION_BUS_ADDRESS -- legacy fallback |
| 165 |
|
| 166 |
Validation uses C(dbus-send) if available, C(busctl) otherwise. |
| 167 |
|
| 168 |
Example usage: |
| 169 |
|
| 170 |
dbus_wrapper = DBusWrapper(ansible_module) |
| 171 |
dbus_wrapper.run_command(["printenv", "DBUS_SESSION_BUS_ADDRESS"]) |
| 172 |
""" |
| 173 |
|
| 174 |
def __init__(self, module): |
| 175 |
self.module = module |
| 176 |
self.dbus_session_bus_address = self._get_existing_dbus_session() |
| 177 |
|
| 178 |
if self.dbus_session_bus_address is None: |
| 179 |
self.dbus_run_session_cmd = self.module.get_bin_path("dbus-run-session", required=True) |
| 180 |
|
| 181 |
def _validate_address(self, address): |
| 182 |
dbus_send = self.module.get_bin_path("dbus-send") |
| 183 |
if dbus_send: |
| 184 |
rc, dummy, dummy = self.module.run_command( |
| 185 |
[dbus_send, f"--address={address}", "--type=signal", "/", "com.example.test"] |
| 186 |
) |
| 187 |
if rc == 0: |
| 188 |
return True |
| 189 |
|
| 190 |
busctl = self.module.get_bin_path("busctl") |
| 191 |
if busctl: |
| 192 |
rc, dummy, dummy = self.module.run_command([busctl, f"--address={address}", "list"]) |
| 193 |
if rc == 0: |
| 194 |
return True |
| 195 |
|
| 196 |
if not dbus_send and not busctl: |
| 197 |
self.module.fail_json(msg="Neither dbus-send nor busctl is available. Please install one of them.") |
| 198 |
|
| 199 |
return False |
| 200 |
|
| 201 |
def _get_existing_dbus_session(self): |
| 202 |
""" |
| 203 |
Detects and returns an existing D-Bus session bus address. |
| 204 |
|
| 205 |
:returns: string -- D-Bus session bus address. If a running D-Bus session was not detected, returns None. |
| 206 |
""" |
| 207 |
|
| 208 |
# We'll be checking the processes of current user only. |
| 209 |
uid = os.getuid() |
| 210 |
|
| 211 |
# Step 1: current process environment |
| 212 |
address = os.environ.get("DBUS_SESSION_BUS_ADDRESS") |
| 213 |
if address: |
| 214 |
self.module.debug(f"Trying D-Bus address from environment: {address}") |
| 215 |
if self._validate_address(address): |
| 216 |
self.module.debug(f"Using D-Bus session from environment: {address}") |
| 217 |
return address |
| 218 |
|
| 219 |
# Step 2: canonical systemd/dbus-broker socket path |
| 220 |
canonical_path = f"/run/user/{uid}/bus" |
| 221 |
if os.path.exists(canonical_path): |
| 222 |
address = f"unix:path={canonical_path}" |
| 223 |
self.module.debug(f"Trying canonical D-Bus socket: {canonical_path}") |
| 224 |
if self._validate_address(address): |
| 225 |
self.module.debug(f"Using canonical D-Bus socket: {canonical_path}") |
| 226 |
return address |
| 227 |
|
| 228 |
# Step 3: process scan (legacy fallback) |
| 229 |
self.module.debug(f"Scanning processes for D-Bus session (uid={uid})") |
| 230 |
for pid in psutil.pids(): |
| 231 |
try: |
| 232 |
process = psutil.Process(pid) |
| 233 |
process_real_uid, dummy, dummy = process.uids() |
| 234 |
if process_real_uid == uid and "DBUS_SESSION_BUS_ADDRESS" in process.environ(): |
| 235 |
dbus_session_bus_address_candidate = process.environ()["DBUS_SESSION_BUS_ADDRESS"] |
| 236 |
self.module.debug( |
| 237 |
f"Found D-Bus user session candidate at address: {dbus_session_bus_address_candidate}" |
| 238 |
) |
| 239 |
if self._validate_address(dbus_session_bus_address_candidate): |
| 240 |
self.module.debug( |
| 241 |
f"Verified D-Bus user session candidate as usable at address: {dbus_session_bus_address_candidate}" |
| 242 |
) |
| 243 |
return dbus_session_bus_address_candidate |
| 244 |
|
| 245 |
# This can happen with things like SSH sessions etc. |
| 246 |
except psutil.AccessDenied: |
| 247 |
pass |
| 248 |
# Process has disappeared while inspecting it |
| 249 |
except psutil.NoSuchProcess: |
| 250 |
pass |
| 251 |
|
| 252 |
self.module.debug("Failed to find running D-Bus user session, will use dbus-run-session") |
| 253 |
return None |
| 254 |
|
| 255 |
def run_command(self, command): |
| 256 |
""" |
| 257 |
Runs the specified command within a functional D-Bus session. Command is |
| 258 |
effectively passed-on to AnsibleModule.run_command() method, with |
| 259 |
modification for using dbus-run-session if necessary. |
| 260 |
|
| 261 |
:param command: Command to run, including parameters. Each element of the list should be a string. |
| 262 |
:type module: list |
| 263 |
|
| 264 |
:returns: tuple(result_code, standard_output, standard_error) -- Result code, standard output, and standard error from running the command. |
| 265 |
""" |
| 266 |
|
| 267 |
if self.dbus_session_bus_address is None: |
| 268 |
self.module.debug("Using dbus-run-session wrapper for running commands.") |
| 269 |
command = [self.dbus_run_session_cmd] + command |
| 270 |
rc, out, err = self.module.run_command(command) |
| 271 |
if rc == 127: |
| 272 |
self.module.fail_json( |
| 273 |
msg=f"Failed to run passed-in command, dbus-run-session faced an internal error: {err}" |
| 274 |
) |
| 275 |
else: |
| 276 |
extra_environment = {"DBUS_SESSION_BUS_ADDRESS": self.dbus_session_bus_address} |
| 277 |
rc, out, err = self.module.run_command(command, environ_update=extra_environment) |
| 278 |
|
| 279 |
return rc, out, err |
| 280 |
|
| 281 |
|
| 282 |
class DconfPreference: |
| 283 |
def __init__(self, module, check_mode=False): |
| 284 |
""" |
| 285 |
Initialises instance of the class. |
| 286 |
|
| 287 |
:param module: Ansible module instance used to signal failures and run commands. |
| 288 |
:type module: AnsibleModule |
| 289 |
|
| 290 |
:param check_mode: Specify whether to only check if a change should be made or if to actually make a change. |
| 291 |
:type check_mode: bool |
| 292 |
""" |
| 293 |
|
| 294 |
self.module = module |
| 295 |
self.check_mode = check_mode |
| 296 |
# Check if dconf binary exists |
| 297 |
self.dconf_bin = self.module.get_bin_path("dconf", required=True) |
| 298 |
|
| 299 |
@staticmethod |
| 300 |
def variants_are_equal(canonical_value, user_value): |
| 301 |
"""Compare two string GVariant representations for equality. |
| 302 |
|
| 303 |
Assumes `canonical_value` is "canonical" in the sense that the type of |
| 304 |
the variant is specified explicitly if it cannot be inferred; this is |
| 305 |
true for textual representations of variants generated by the `dconf` |
| 306 |
command. The type of `canonical_value` is used to parse `user_value`, |
| 307 |
so the latter does not need to be explicitly typed. |
| 308 |
|
| 309 |
Returns True if the two values are equal. |
| 310 |
""" |
| 311 |
if canonical_value is None: |
| 312 |
# It's unset in dconf database, so anything the user is trying to |
| 313 |
# set is a change. |
| 314 |
return False |
| 315 |
try: |
| 316 |
variant1 = Variant.parse(None, canonical_value) |
| 317 |
variant2 = Variant.parse(variant1.get_type(), user_value) |
| 318 |
return variant1 == variant2 |
| 319 |
except GError: |
| 320 |
return canonical_value == user_value |
| 321 |
|
| 322 |
def read(self, key): |
| 323 |
""" |
| 324 |
Retrieves current value associated with the dconf key. |
| 325 |
|
| 326 |
If an error occurs, a call will be made to AnsibleModule.fail_json. |
| 327 |
|
| 328 |
:returns: string -- Value assigned to the provided key. If the value is not set for specified key, returns None. |
| 329 |
""" |
| 330 |
command = [self.dconf_bin, "read", key] |
| 331 |
|
| 332 |
rc, out, err = self.module.run_command(command, environ_update={"LANGUAGE": "C", "LC_ALL": "C"}) |
| 333 |
|
| 334 |
if rc != 0: |
| 335 |
self.module.fail_json(msg=f"dconf failed while reading the value with error: {err}", out=out, err=err) |
| 336 |
|
| 337 |
if out == "": |
| 338 |
value = None |
| 339 |
else: |
| 340 |
value = out.rstrip("\n") |
| 341 |
|
| 342 |
return value |
| 343 |
|
| 344 |
def write(self, key, value): |
| 345 |
""" |
| 346 |
Writes the value for specified key. |
| 347 |
|
| 348 |
If an error occurs, a call will be made to AnsibleModule.fail_json. |
| 349 |
|
| 350 |
:param key: dconf key for which the value should be set. Should be a full path. |
| 351 |
:type key: str |
| 352 |
|
| 353 |
:param value: Value to set for the specified dconf key. Should be specified in GVariant format. |
| 354 |
:type value: str |
| 355 |
|
| 356 |
:returns: bool -- True if a change was made, False if no change was required. |
| 357 |
""" |
| 358 |
# If no change is needed (or won't be done due to check_mode), notify |
| 359 |
# caller straight away. |
| 360 |
if self.variants_are_equal(self.read(key), value): |
| 361 |
return False |
| 362 |
elif self.check_mode: |
| 363 |
return True |
| 364 |
|
| 365 |
# Set-up command to run. Since DBus is needed for write operation, wrap |
| 366 |
# dconf command dbus-launch. |
| 367 |
command = [self.dconf_bin, "write", key, value] |
| 368 |
|
| 369 |
# Run the command and fetch standard return code, stdout, and stderr. |
| 370 |
dbus_wrapper = DBusWrapper(self.module) |
| 371 |
rc, out, err = dbus_wrapper.run_command(command) |
| 372 |
|
| 373 |
if rc != 0: |
| 374 |
self.module.fail_json( |
| 375 |
msg=f"dconf failed while writing key {key}, value {value} with error: {err}", out=out, err=err |
| 376 |
) |
| 377 |
|
| 378 |
# Value was changed. |
| 379 |
return True |
| 380 |
|
| 381 |
def reset(self, key): |
| 382 |
""" |
| 383 |
Returns value for the specified key (removes it from user configuration). |
| 384 |
|
| 385 |
If an error occurs, a call will be made to AnsibleModule.fail_json. |
| 386 |
|
| 387 |
:param key: dconf key to reset. Should be a full path. |
| 388 |
:type key: str |
| 389 |
|
| 390 |
:returns: bool -- True if a change was made, False if no change was required. |
| 391 |
""" |
| 392 |
|
| 393 |
# Read the current value first. |
| 394 |
current_value = self.read(key) |
| 395 |
|
| 396 |
# No change was needed, key is not set at all, or just notify user if we |
| 397 |
# are in check mode. |
| 398 |
if current_value is None: |
| 399 |
return False |
| 400 |
elif self.check_mode: |
| 401 |
return True |
| 402 |
|
| 403 |
# Set-up command to run. Since DBus is needed for reset operation, wrap |
| 404 |
# dconf command dbus-launch. |
| 405 |
command = [self.dconf_bin, "reset", key] |
| 406 |
|
| 407 |
# Run the command and fetch standard return code, stdout, and stderr. |
| 408 |
dbus_wrapper = DBusWrapper(self.module) |
| 409 |
rc, out, err = dbus_wrapper.run_command(command) |
| 410 |
|
| 411 |
if rc != 0: |
| 412 |
self.module.fail_json(msg=f"dconf failed while resetting the value with error: {err}", out=out, err=err) |
| 413 |
|
| 414 |
# Value was changed. |
| 415 |
return True |
| 416 |
|
| 417 |
|
| 418 |
def main(): |
| 419 |
# Setup the Ansible module |
| 420 |
module = AnsibleModule( |
| 421 |
argument_spec=dict( |
| 422 |
state=dict(default="present", choices=["present", "absent", "read"]), |
| 423 |
key=dict(required=True, type="str", no_log=False), |
| 424 |
# Converted to str below after special handling of bool. |
| 425 |
value=dict(type="raw"), |
| 426 |
), |
| 427 |
supports_check_mode=True, |
| 428 |
required_if=[ |
| 429 |
("state", "present", ["value"]), |
| 430 |
], |
| 431 |
) |
| 432 |
|
| 433 |
if Variant is None: |
| 434 |
# This interpreter can't see the GLib module. To try to fix that, we'll |
| 435 |
# look in common locations for system-owned interpreters that can see |
| 436 |
# it; if we find one, we'll respawn under it. Otherwise we'll proceed |
| 437 |
# with degraded performance, without the ability to parse GVariants. |
| 438 |
# Later (in a different PR) we'll actually deprecate this degraded |
| 439 |
# performance level and fail with an error if the library can't be |
| 440 |
# found. |
| 441 |
|
| 442 |
if has_respawned(): |
| 443 |
# This shouldn't be possible; short-circuit early if it happens. |
| 444 |
module.fail_json(msg=f"{glib_module_name} must be installed and visible from {sys.executable}.") |
| 445 |
|
| 446 |
interpreters = ["/usr/bin/python3", "/usr/bin/python"] |
| 447 |
|
| 448 |
interpreter = probe_interpreters_for_module(interpreters, glib_module_name) |
| 449 |
|
| 450 |
if interpreter: |
| 451 |
# Found the Python bindings; respawn this module under the |
| 452 |
# interpreter where we found them. |
| 453 |
respawn_module(interpreter) |
| 454 |
# This is the end of the line for this process, it will exit here |
| 455 |
# once the respawned module has completed. |
| 456 |
|
| 457 |
# Try to be forgiving about the user specifying a boolean as the value, or |
| 458 |
# more accurately about the fact that YAML and Ansible are quite insistent |
| 459 |
# about converting strings that look like booleans into booleans. Convert |
| 460 |
# the boolean into a string of the type dconf will understand. Any type for |
| 461 |
# the value other than boolean is just converted into a string directly. |
| 462 |
if module.params["value"] is not None: |
| 463 |
if isinstance(module.params["value"], bool): |
| 464 |
module.params["value"] = "true" if module.params["value"] else "false" |
| 465 |
else: |
| 466 |
module.params["value"] = str(module.params["value"]) |
| 467 |
|
| 468 |
if Variant is None: |
| 469 |
module.deprecate( |
| 470 |
"The gi.repository Python library is not available; " |
| 471 |
"using string comparison to check value equality. This fallback " |
| 472 |
"will be removed in community.general 15.0.0.", |
| 473 |
version="15.0.0", |
| 474 |
collection_name="community.general", |
| 475 |
) |
| 476 |
|
| 477 |
deps.validate(module) |
| 478 |
|
| 479 |
# Create wrapper instance. |
| 480 |
dconf = DconfPreference(module, module.check_mode) |
| 481 |
|
| 482 |
# Process based on different states. |
| 483 |
if module.params["state"] == "read": |
| 484 |
value = dconf.read(module.params["key"]) |
| 485 |
module.exit_json(changed=False, value=value) |
| 486 |
elif module.params["state"] == "present": |
| 487 |
changed = dconf.write(module.params["key"], module.params["value"]) |
| 488 |
module.exit_json(changed=changed) |
| 489 |
elif module.params["state"] == "absent": |
| 490 |
changed = dconf.reset(module.params["key"]) |
| 491 |
module.exit_json(changed=changed) |
| 492 |
|
| 493 |
|
| 494 |
if __name__ == "__main__": |
| 495 |
main() |