pyinfra icon indicating copy to clipboard operation
pyinfra copied to clipboard

Context manager for local/temporary config overrides.

Open plattrap opened this issue 6 months ago • 1 comments

Is your feature request related to a problem? Please describe

I have a set of steps that require the _sudo=True option but not all steps do, and without having to add that setting to each step affected.

Describe the solution you'd like

Would like to know if there is the equivalent of the code below in the codebase?

from contextlib import contextmanager

from pyinfra.context import config
from pyinfra.operations import apt

@contextmanager
def config_override(**kwargs):
    old_settings_state = config.get_current_state()
    for k,v in kwargs.items():
        setattr(config, k, v)
    try:
        yield
    finally:
        config.set_current_state(old_settings_state)

with config_override(SUDO = True):
    # Works
    apt.update(name=f"apt.update with {config.SUDO = }")
    apt.upgrade()
    apt.dist_upgrade()

# Expect fail
apt.update(name=f"apt.update with {config.SUDO = }")

plattrap avatar Jun 04 '25 03:06 plattrap

All operations should support _sudo?

I like this idea though, config in general needs some love.

Fizzadar avatar Jun 08 '25 12:06 Fizzadar