liab-deployments/liab_deployments/deploy/__init__.py
Michael Hanke 079b3dd1a9
rf: factor out get_user_info()
as a common helper to decode the user specification in inventories.
2026-09-05 20:19:09 +02:00

56 lines
1.8 KiB
Python

from collections.abc import Sequence
from pyinfra import host
from pyinfra.api import DeployError
from pyinfra.operations import server
def check_dependencies(cmds: Sequence[str]):
for cmd in cmds:
if not host.get_fact(server.Which, cmd):
msg = f'Requires {cmd!r}, but it is not available'
raise DeployError(msg)
def check_no_duplicates(records, key_path, *, context=''):
"""Raise ValueError if the value at *key_path* is duplicated across *records*.
key_path is a tuple of keys/indexes to follow into each record,
e.g. ``('user', 0)`` or ``('host_port',)``.
Records where the path cannot be resolved are skipped.
"""
counts = {}
for record in records:
try:
val = record
for key in key_path:
val = val[key]
except (KeyError, IndexError, TypeError):
continue
counts[val] = counts.get(val, 0) + 1
dupes = {v for v, c in counts.items() if c > 1}
if dupes:
label = '.'.join(map(str, key_path))
raise ValueError(
f'{context}: duplicate {label} value(s): '
f'{", ".join(str(v) for v in sorted(dupes, key=str))}',
)
def all_sites(host_data):
"""Yield site dicts from all multi-site services in the inventory."""
for service in sorted(host_data):
svc = host_data[service]
if not isinstance(svc, dict):
continue
for site in svc.get('sites', []):
yield site
def get_user_info(
user_spec: tuple[str, int] | tuple[str, int, str]
) -> tuple[str, int, str]:
"""Returns user name, uid, and HOME diretcory from specification"""
name, uid = user_spec[:2]
home = user_spec[2] if len(user_spec) > 2 else f'/home/{name}'
return name, uid, home