| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2025, Marco Noce <[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: systemd_info |
| 11 |
short_description: Gather C(systemd) unit info |
| 12 |
description: |
| 13 |
- This module gathers info about systemd units (services, targets, sockets, mounts, timers). |
| 14 |
- Timer units are supported since community.general 10.5.0. |
| 15 |
- It runs C(systemctl list-units) (or processes selected units) and collects properties for each unit using C(systemctl |
| 16 |
show). |
| 17 |
- In case a unit has multiple properties with the same name, only the value of the first one is collected. |
| 18 |
- Even if a unit has a RV(units.loadstate) of V(not-found) or V(masked), it is returned, but only with the minimal properties |
| 19 |
(RV(units.name), RV(units.loadstate), RV(units.activestate), RV(units.substate)). |
| 20 |
- When O(unitname) and O(extra_properties) are used, the module first checks if the unit exists, then check if properties |
| 21 |
exist. If not, the module fails. |
| 22 |
- When O(unitname) is used with wildcard expressions, the module checks for units that match the indicated expressions, |
| 23 |
if units are not present for all the indicated expressions, the module fails. |
| 24 |
version_added: "10.4.0" |
| 25 |
options: |
| 26 |
unitname: |
| 27 |
description: |
| 28 |
- List of unit names to process. |
| 29 |
- It supports C(.service), C(.target), C(.socket), C(.mount) and C(.timer) units type. |
| 30 |
- C(.timer) units are supported since community.general 10.5.0. |
| 31 |
- Each name must correspond to the full name of the C(systemd) unit or to a wildcard expression like V('ssh*') and V('*.service'). |
| 32 |
- Wildcard expressions in O(unitname) are supported since community.general 10.5.0. |
| 33 |
type: list |
| 34 |
elements: str |
| 35 |
default: [] |
| 36 |
extra_properties: |
| 37 |
description: |
| 38 |
- Additional properties to retrieve (appended to the default ones). |
| 39 |
- Note that all property names are converted to lower-case. |
| 40 |
type: list |
| 41 |
elements: str |
| 42 |
default: [] |
| 43 |
author: |
| 44 |
- Marco Noce (@NomakCooper) |
| 45 |
extends_documentation_fragment: |
| 46 |
- community.general._attributes |
| 47 |
- community.general._attributes.info_module |
| 48 |
""" |
| 49 |
|
| 50 |
EXAMPLES = r""" |
| 51 |
--- |
| 52 |
# Gather info for all systemd services, targets, sockets, mount and timer |
| 53 |
- name: Gather all systemd unit info |
| 54 |
community.general.systemd_info: |
| 55 |
register: results |
| 56 |
|
| 57 |
# Gather info for selected units with extra properties. |
| 58 |
- name: Gather info for selected unit(s) |
| 59 |
community.general.systemd_info: |
| 60 |
unitname: |
| 61 |
- systemd-journald.service |
| 62 |
- systemd-journald.socket |
| 63 |
- sshd-keygen.target |
| 64 |
- -.mount |
| 65 |
extra_properties: |
| 66 |
- Description |
| 67 |
register: results |
| 68 |
|
| 69 |
# Gather info using wildcards/expression |
| 70 |
- name: Gather info of units that start with 'systemd-' |
| 71 |
community.general.systemd_info: |
| 72 |
unitname: |
| 73 |
- 'systemd-*' |
| 74 |
register: results |
| 75 |
|
| 76 |
# Gather info for systemd-tmpfiles-clean.timer with extra properties |
| 77 |
- name: Gather info of systemd-tmpfiles-clean.timer and extra AccuracyUSec |
| 78 |
community.general.systemd_info: |
| 79 |
unitname: |
| 80 |
- systemd-tmpfiles-clean.timer |
| 81 |
extra_properties: |
| 82 |
- AccuracyUSec |
| 83 |
register: results |
| 84 |
""" |
| 85 |
|
| 86 |
RETURN = r""" |
| 87 |
units: |
| 88 |
description: |
| 89 |
- Dictionary of systemd unit info keyed by unit name. |
| 90 |
- Additional fields are returned depending on the value of O(extra_properties). |
| 91 |
returned: success |
| 92 |
type: dict |
| 93 |
elements: dict |
| 94 |
contains: |
| 95 |
name: |
| 96 |
description: Unit full name. |
| 97 |
returned: always |
| 98 |
type: str |
| 99 |
sample: systemd-journald.service |
| 100 |
loadstate: |
| 101 |
description: |
| 102 |
- The state of the unit's configuration load. |
| 103 |
- The most common values are V(loaded), V(not-found), and V(masked), but other values are possible as well. |
| 104 |
returned: always |
| 105 |
type: str |
| 106 |
sample: loaded |
| 107 |
activestate: |
| 108 |
description: |
| 109 |
- The current active state of the unit. |
| 110 |
- The most common values are V(active), V(inactive), and V(failed), but other values are possible as well. |
| 111 |
returned: always |
| 112 |
type: str |
| 113 |
sample: active |
| 114 |
substate: |
| 115 |
description: |
| 116 |
- The detailed sub state of the unit. |
| 117 |
- The most common values are V(running), V(dead), V(exited), V(failed), V(listening), V(active), and V(mounted), but |
| 118 |
other values are possible as well. |
| 119 |
returned: always |
| 120 |
type: str |
| 121 |
sample: running |
| 122 |
fragmentpath: |
| 123 |
description: Path to the unit's fragment file. |
| 124 |
returned: always except for C(.mount) units. |
| 125 |
type: str |
| 126 |
sample: /usr/lib/systemd/system/systemd-journald.service |
| 127 |
unitfilepreset: |
| 128 |
description: |
| 129 |
- The preset configuration state for the unit file. |
| 130 |
- The most common values are V(enabled), V(disabled), and V(static), but other values are possible as well. |
| 131 |
returned: always except for C(.mount) units. |
| 132 |
type: str |
| 133 |
sample: disabled |
| 134 |
unitfilestate: |
| 135 |
description: |
| 136 |
- The actual configuration state for the unit file. |
| 137 |
- The most common values are V(enabled), V(disabled), and V(static), but other values are possible as well. |
| 138 |
returned: always except for C(.mount) units. |
| 139 |
type: str |
| 140 |
sample: enabled |
| 141 |
mainpid: |
| 142 |
description: PID of the main process of the unit. |
| 143 |
returned: only for C(.service) units. |
| 144 |
type: str |
| 145 |
sample: 798 |
| 146 |
execmainpid: |
| 147 |
description: PID of the ExecStart process of the unit. |
| 148 |
returned: only for C(.service) units. |
| 149 |
type: str |
| 150 |
sample: 799 |
| 151 |
options: |
| 152 |
description: The mount options. |
| 153 |
returned: only for C(.mount) units. |
| 154 |
type: str |
| 155 |
sample: rw,relatime,noquota |
| 156 |
type: |
| 157 |
description: The filesystem type of the mounted device. |
| 158 |
returned: only for C(.mount) units. |
| 159 |
type: str |
| 160 |
sample: ext4 |
| 161 |
what: |
| 162 |
description: The device that is mounted. |
| 163 |
returned: only for C(.mount) units. |
| 164 |
type: str |
| 165 |
sample: /dev/sda1 |
| 166 |
where: |
| 167 |
description: The mount point where the device is mounted. |
| 168 |
returned: only for C(.mount) units. |
| 169 |
type: str |
| 170 |
sample: / |
| 171 |
sample: |
| 172 |
{ |
| 173 |
"-.mount": { |
| 174 |
"activestate": "active", |
| 175 |
"description": "Root Mount", |
| 176 |
"loadstate": "loaded", |
| 177 |
"name": "-.mount", |
| 178 |
"options": "rw,relatime,seclabel,attr2,inode64,logbufs=8,logbsize=32k,noquota", |
| 179 |
"substate": "mounted", |
| 180 |
"type": "xfs", |
| 181 |
"what": "/dev/mapper/cs-root", |
| 182 |
"where": "/" |
| 183 |
}, |
| 184 |
"sshd-keygen.target": { |
| 185 |
"activestate": "active", |
| 186 |
"description": "sshd-keygen.target", |
| 187 |
"fragmentpath": "/usr/lib/systemd/system/sshd-keygen.target", |
| 188 |
"loadstate": "loaded", |
| 189 |
"name": "sshd-keygen.target", |
| 190 |
"substate": "active", |
| 191 |
"unitfilepreset": "disabled", |
| 192 |
"unitfilestate": "static" |
| 193 |
}, |
| 194 |
"systemd-journald.service": { |
| 195 |
"activestate": "active", |
| 196 |
"description": "Journal Service", |
| 197 |
"execmainpid": "613", |
| 198 |
"fragmentpath": "/usr/lib/systemd/system/systemd-journald.service", |
| 199 |
"loadstate": "loaded", |
| 200 |
"mainpid": "613", |
| 201 |
"name": "systemd-journald.service", |
| 202 |
"substate": "running", |
| 203 |
"unitfilepreset": "disabled", |
| 204 |
"unitfilestate": "static" |
| 205 |
}, |
| 206 |
"systemd-journald.socket": { |
| 207 |
"activestate": "active", |
| 208 |
"description": "Journal Socket", |
| 209 |
"fragmentpath": "/usr/lib/systemd/system/systemd-journald.socket", |
| 210 |
"loadstate": "loaded", |
| 211 |
"name": "systemd-journald.socket", |
| 212 |
"substate": "running", |
| 213 |
"unitfilepreset": "disabled", |
| 214 |
"unitfilestate": "static" |
| 215 |
} |
| 216 |
} |
| 217 |
""" |
| 218 |
|
| 219 |
import fnmatch |
| 220 |
|
| 221 |
from ansible.module_utils.basic import AnsibleModule |
| 222 |
|
| 223 |
from ansible_collections.community.general.plugins.module_utils._systemd import systemd_runner |
| 224 |
|
| 225 |
|
| 226 |
def get_version(runner): |
| 227 |
with runner("version") as ctx: |
| 228 |
rc, stdout, stderr = ctx.run() |
| 229 |
return stdout.strip() |
| 230 |
|
| 231 |
|
| 232 |
def list_units(runner, types_value): |
| 233 |
context = "list_units types all plain no_legend" |
| 234 |
with runner(context) as ctx: |
| 235 |
rc, stdout, stderr = ctx.run(types=types_value) |
| 236 |
return stdout.strip() |
| 237 |
|
| 238 |
|
| 239 |
def show_unit_properties(runner, prop_list, unit): |
| 240 |
context = "show props dashdash unit" |
| 241 |
with runner(context) as ctx: |
| 242 |
rc, stdout, stderr = ctx.run(props=prop_list, unit=unit) |
| 243 |
return stdout.strip() |
| 244 |
|
| 245 |
|
| 246 |
def parse_show_output(output): |
| 247 |
result = {} |
| 248 |
for line in output.splitlines(): |
| 249 |
if "=" in line: |
| 250 |
key, val = line.split("=", 1) |
| 251 |
key = key.lower() |
| 252 |
if key not in result: |
| 253 |
result[key] = val |
| 254 |
return result |
| 255 |
|
| 256 |
|
| 257 |
def get_unit_properties(runner, prop_list, unit): |
| 258 |
output = show_unit_properties(runner, prop_list, unit) |
| 259 |
return parse_show_output(output) |
| 260 |
|
| 261 |
|
| 262 |
def determine_category(unit): |
| 263 |
if unit.endswith(".service"): |
| 264 |
return "service" |
| 265 |
elif unit.endswith(".target"): |
| 266 |
return "target" |
| 267 |
elif unit.endswith(".socket"): |
| 268 |
return "socket" |
| 269 |
elif unit.endswith(".mount"): |
| 270 |
return "mount" |
| 271 |
elif unit.endswith(".timer"): |
| 272 |
return "timer" |
| 273 |
else: |
| 274 |
return None |
| 275 |
|
| 276 |
|
| 277 |
def extract_unit_properties(unit_data, prop_list): |
| 278 |
lowerprop = [x.lower() for x in prop_list] |
| 279 |
return {prop: unit_data[prop] for prop in lowerprop if prop in unit_data} |
| 280 |
|
| 281 |
|
| 282 |
def unit_exists(unit, units_info): |
| 283 |
info = units_info.get(unit, {}) |
| 284 |
loadstate = info.get("loadstate", "").lower() |
| 285 |
return loadstate not in ("not-found", "masked") |
| 286 |
|
| 287 |
|
| 288 |
def get_category_base_props(category): |
| 289 |
base_props = { |
| 290 |
"service": ["FragmentPath", "UnitFileState", "UnitFilePreset", "MainPID", "ExecMainPID"], |
| 291 |
"target": ["FragmentPath", "UnitFileState", "UnitFilePreset"], |
| 292 |
"socket": ["FragmentPath", "UnitFileState", "UnitFilePreset"], |
| 293 |
"mount": ["Where", "What", "Options", "Type"], |
| 294 |
"timer": ["FragmentPath", "UnitFileState", "UnitFilePreset"], |
| 295 |
} |
| 296 |
return base_props.get(category, []) |
| 297 |
|
| 298 |
|
| 299 |
def validate_unit_and_properties(runner, unit, extra_properties, units_info, property_cache): |
| 300 |
if not unit_exists(unit, units_info): |
| 301 |
module.fail_json(msg=f"Unit '{unit}' does not exist or is inaccessible.") |
| 302 |
|
| 303 |
category = determine_category(unit) |
| 304 |
|
| 305 |
if not category: |
| 306 |
module.fail_json(msg=f"Could not determine the category for unit '{unit}'.") |
| 307 |
|
| 308 |
state_props = ["LoadState", "ActiveState", "SubState"] |
| 309 |
props = get_category_base_props(category) |
| 310 |
full_props = set(props + state_props + extra_properties) |
| 311 |
|
| 312 |
if unit not in property_cache: |
| 313 |
unit_data = get_unit_properties(runner, full_props, unit) |
| 314 |
property_cache[unit] = unit_data |
| 315 |
else: |
| 316 |
unit_data = property_cache[unit] |
| 317 |
if extra_properties: |
| 318 |
missing_props = [prop for prop in extra_properties if prop.lower() not in unit_data] |
| 319 |
if missing_props: |
| 320 |
module.fail_json(msg=f"The following properties do not exist for unit '{unit}': {', '.join(missing_props)}") |
| 321 |
|
| 322 |
return True |
| 323 |
|
| 324 |
|
| 325 |
def process_wildcards(selected_units, all_units, module): |
| 326 |
resolved_units = {} |
| 327 |
non_matching_patterns = [] |
| 328 |
|
| 329 |
for pattern in selected_units: |
| 330 |
matches = fnmatch.filter(all_units, pattern) |
| 331 |
if not matches: |
| 332 |
non_matching_patterns.append(pattern) |
| 333 |
else: |
| 334 |
for match in matches: |
| 335 |
resolved_units[match] = True |
| 336 |
|
| 337 |
if not resolved_units: |
| 338 |
module.fail_json(msg=f"No units match any of the provided patterns: {', '.join(non_matching_patterns)}") |
| 339 |
|
| 340 |
return resolved_units, non_matching_patterns |
| 341 |
|
| 342 |
|
| 343 |
def process_unit(runner, unit, extra_properties, units_info, property_cache, state_props): |
| 344 |
if not unit_exists(unit, units_info): |
| 345 |
return units_info.get(unit, {"name": unit, "loadstate": "not-found"}) |
| 346 |
|
| 347 |
validate_unit_and_properties(runner, unit, extra_properties, units_info, property_cache) |
| 348 |
category = determine_category(unit) |
| 349 |
|
| 350 |
if not category: |
| 351 |
module.fail_json(msg=f"Could not determine the category for unit '{unit}'.") |
| 352 |
|
| 353 |
props = get_category_base_props(category) |
| 354 |
full_props = set(props + state_props + extra_properties) |
| 355 |
unit_data = property_cache[unit] |
| 356 |
fact = {"name": unit} |
| 357 |
minimal_keys = ["LoadState", "ActiveState", "SubState"] |
| 358 |
fact.update(extract_unit_properties(unit_data, minimal_keys)) |
| 359 |
ls = unit_data.get("loadstate", "").lower() |
| 360 |
|
| 361 |
if ls not in ("not-found", "masked"): |
| 362 |
fact.update(extract_unit_properties(unit_data, full_props)) |
| 363 |
|
| 364 |
return fact |
| 365 |
|
| 366 |
|
| 367 |
def main(): |
| 368 |
global module |
| 369 |
module_args = dict( |
| 370 |
unitname=dict(type="list", elements="str", default=[]), |
| 371 |
extra_properties=dict(type="list", elements="str", default=[]), |
| 372 |
) |
| 373 |
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) |
| 374 |
systemctl_bin = module.get_bin_path("systemctl", required=True) |
| 375 |
|
| 376 |
base_runner = systemd_runner(module, systemctl_bin) |
| 377 |
|
| 378 |
get_version(base_runner) |
| 379 |
|
| 380 |
state_props = ["LoadState", "ActiveState", "SubState"] |
| 381 |
results = {} |
| 382 |
|
| 383 |
unit_types = ["service", "target", "socket", "mount", "timer"] |
| 384 |
|
| 385 |
list_output = list_units(base_runner, unit_types) |
| 386 |
units_info = {} |
| 387 |
for line in list_output.splitlines(): |
| 388 |
tokens = line.split() |
| 389 |
if len(tokens) < 4: |
| 390 |
continue |
| 391 |
unit_name = tokens[0] |
| 392 |
loadstate = tokens[1] |
| 393 |
activestate = tokens[2] |
| 394 |
substate = tokens[3] |
| 395 |
units_info[unit_name] = { |
| 396 |
"name": unit_name, |
| 397 |
"loadstate": loadstate, |
| 398 |
"activestate": activestate, |
| 399 |
"substate": substate, |
| 400 |
} |
| 401 |
|
| 402 |
property_cache = {} |
| 403 |
extra_properties = module.params["extra_properties"] |
| 404 |
|
| 405 |
if module.params["unitname"]: |
| 406 |
selected_units = module.params["unitname"] |
| 407 |
all_units = list(units_info) |
| 408 |
resolved_units, non_matching = process_wildcards(selected_units, all_units, module) |
| 409 |
units_to_process = sorted(resolved_units) |
| 410 |
else: |
| 411 |
units_to_process = list(units_info) |
| 412 |
|
| 413 |
for unit in units_to_process: |
| 414 |
results[unit] = process_unit(base_runner, unit, extra_properties, units_info, property_cache, state_props) |
| 415 |
module.exit_json(changed=False, units=results) |
| 416 |
|
| 417 |
|
| 418 |
if __name__ == "__main__": |
| 419 |
main() |