Skip to content

Context manager for operation delegation #2116

Backlog

Description

@vegas503

Is your feature request related to a problem? Please describe

Partially related to #1649

Pyinfra currently runs all operations on all hosts. In order to run a command on one host only (e. g. @local), a condition has to be used:

op1()
if "local" in host.groups:
    op2()
op3()

This has several implications and inconveniences:

  • "local" has to be added to the inventory.

  • Third-party operations have no way of knowing which host is a "local" host - the contract is through implicit naming (user must know to add "local" to their)

  • This gets uglier when all operations except one have to run on remote hosts:

    # This sequence is linear, but visually it does not seem as such:
    
    op1()
    op2()
    if "local" in host.groups:
        server.shell("docker build ... && docker image save > tmp.tar") # build images locally
    else:
        files.rsync(...)  # upload images...
        server.shell("docker image load ...")
        server.file(...)  # write compose.yml
        server.run("docker compose up")
    
    if "local" in host.groups:
        # Cleanup
        server.shell("rm -f tmp.tar")

    Each new operation adds another branch. Furthermore, forgetting a guard is not just ugly, but a disaster: an unguarded server.shell("docker compose up") would silently execute on the wrong host, including the developer's machine.

Workarounds

  • As mentioned in second item, a third-party operation that has to do some local work and some remote work cannot reliably run commands unless a python.call escape hatch is used:

    # This allows to run certain commands 
    op1()
    op2()
    
    def deploy():
        pyinfra.local.shell("docker build...")
    python.call(deploy, _run_once=True)
    
    files.rsync(...)  # upload images...
    ...
  • Another workaround is to directly invoke all local commands in the beginning of the script, but this means that slow local commands like "docker build" will run before the deployment is executed.

  • Yet another workaround is to have 2 separate scripts, but this also requires 2 separate inventories, so it escalates to a grand total of 4 files for such a simple case.

Describe the solution you'd like

I suggest to add a context manager that retargets the operations queued inside it without the target having to be part of the inventory. It could look like this:

op1()
op2()

with pyinfra.api.delegate("@local"):
    server.shell("docker build")

files.rsync(...)  # upload images...
...

Benefits

  • Such script is linear and nicely reads top to bottom. Third-party operations can express "some local work, some remote work" without an inventory-side naming contract. This would allow patterns similar to ansible's delegate_to, where e.g. "localhost" does not have to be defined in the inventory.
  • It's not just localhost: other connectors keep working too. with delegate("@docker:...") and with delegate("@ssh:builder.internal:") utilize the same flexibility that the CLI inventory argument already offers, but inline.
  • Context managers are inherently pythonic.
  • "Wrong host" footguns become a non-issue.

Semantics

  • Operations inside the block are queued for the delegated host instead of the current one. Ordering relative to surrounding operations is preserved: operation order is derived from the call stack, so the block slots between its neighbors in the execution order.
  • host inside the block remains the originating host, so host.data keeps working. This is the Ansible delegate_to split discussed in Running operation on another host? #1649: the task belongs to the current host but executes elsewhere. (The alternative of retargeting host entirely would make host.data the usually-empty data of @local and make the pattern much less useful.)
  • The block runs once per inventory host during load, like all deploy code. When its operations do not depend on the originating host (the common case), they should collapse into a single execution on the delegated host; effectively delegate_to + run_once, for free. When they do depend on it (data-driven arguments), they produce one delegated operation per origin host - delegate_to without run_once.
  • The delegated host is created from the connector spec and connected during the prepare stage like any other host: @local does not need any connection. Results, failures, --dry/diff output, and progress - all report it under the delegated host's name.
  • All existing change-detecting semantics are inherited for free.

Activity

  1. added
    bug
    operations
    connectors
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugconnectorsoperations

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions