Execute fabric task for specific host only once

354 views Asked by At

Im trying to execute main task that needs to execute tasks differently for each host. In the following setup, task 'sometask' will get execute twice for each host. What is the best way to prevent that?

@task
@hosts('host1', 'host2')
def test():
    execute(do_something_everywhere)  # execute on both hosts
    execute(sometask, 'arg1', host='host1')  # execute on host1 only
    execute(sometask, 'arg2', host='host2')  # execute on host2 only
1

There are 1 answers

0
quetzaluz On

You can user the @runs_once decorator to remedy this but I find that can cause extra work making wrapper functions to get the execution order you want, so here's a quick fix using the env.host_string value to evaluate which server you are deploying to and adjust your script accordingly:

@hosts('host1', 'host2')
@task
def checkout(branch='master'):
    execute(_test_task_w_arg, 'all-servers')
    execute(_test_task_w_arg, 'arg1' if env.host_string == 'host1' else 'arg2')

def _test_task_w_arg(arg1):
    local("touch test-file-" + arg1)

Results in this output which seems to achieve what you want:

    [host1] Executing task 'checkout'
    [localhost] local: touch test-file-all-servers
    [localhost] local: touch test-file-arg1
    [host2] Executing task 'checkout'
    [localhost] local: touch test-file-all-servers
    [localhost] local: touch test-file-arg2