pyinfra icon indicating copy to clipboard operation
pyinfra copied to clipboard

systemd.service operation: support masking/unmasking

Open bauen1 opened this issue 1 year ago • 2 comments

Is your feature request related to a problem? Please describe

I have some systemd units that I need to stop and mask, to prevent them from being started at all.

Currently I do something like this:

def systemd_unit_enabled_state(unit: str) -> str | None:
    enabled_state = host.get_fact(Command, command=f"systemctl is-enabled {unit} || true")
    return enabled_state


def mydeploy() -> None:
    if systemd_unit_enabled_state("myunit.service") != "masked":
        server.shell(commands=['systemctl mask myunit.service'],
                     _sudo=True)

Describe the solution you'd like

Probably adding a masked argument to the systemd.service operation. I suspect this might require improving some of the things going on behind the scenes, specifically querying unit status.

bauen1 avatar Dec 19 '24 15:12 bauen1

The systemctl mask command creates a symlink to /dev/null (and it's a documented behaviour), so you can use this custom operation that will apply faster:

def mask_unit(unit_name: str) -> OperationMeta:
    return files.link(f"/etc/systemd/system/{unit_name}", "/dev/null", name=f"Mask {unit_name}")

Still worth adding to the built-in operation though.

xvello avatar Dec 28 '24 10:12 xvello

Right, I forgot about that, now I have the following:

def systemd_unit_enabled_state(unit: str) -> str | None:
    enabled_state = host.get_fact(Command, command=f"systemctl is-enabled {unit} || true")
    return enabled_state

@operation()
def systemd_mask_unit(unit_name: str) -> Generator:
    if systemd_unit_enabled_state(unit_name) == "masked":
        host.noop(f"unit '{unit_name}' is already masked")
    else:
        yield from files.link(f"/etc/systemd/system/{unit_name}", "/dev/null")

I don't think I will have to time to work on integrating it, but with the "directly symlink it" approach it should be much easier.

bauen1 avatar Dec 31 '24 14:12 bauen1