2013-10-22 47 views
0

是否有織物execute的方式來尊重裝飾(比hosthostsrolerolesexclude_hosts等---見here),或另一種方式來完成類似的東西)?下面是一個使用案例:結構任務是否可以執行其他任務並尊重諸如runs_once之類的裝飾器?

from fabric.api import task, execute, run, runs_once 

@task 
def setup_environment(): 
    # ... set up env.hosts, env.roledefs, env.use_ssh_config, etc. 

@task 
def provision(): 
    # ... do some stuff on each host here, e.g. install mongodb 

@task 
def is_primary(): 
    return run('mongo --quiet --eval "db.isMaster().ismaster"') == 'true' 

@task 
@runs_once 
def change_to_primary(): 
    env.hosts = [] 
    for host, result in execute(is_primary, roles=('mongo',)).iteritems(): 
     if result: 
      env.hosts.append(host) 

@task 
def add_user(): 
    # ... do something here that needs to be done on primary 

這是好的,如果我運行命令行任務的順序如下:

> fab setup_environment provision change_to_primary add_user 

但因爲我始終運行change_to_primaryadd_user作爲配置的一部分,我想修改provision,這樣我可以運行fab setup_environment provision並有set_primaryadd_user執行,這樣的事:

@task 
def provision(): 
    # ... do some stuff on each host here, e.g. install mongodb 
    execute(change_to_primary) 
    execute(add_user) 

但是,與命令行用法不同,它多次執行change_to_primary(不會運行一次)。有沒有辦法做到這一點?

回答

1

一種方法是執行與使用roles裝飾的mongo角色的所有節點上的任務,並通過檢查開始執行任務,如果該節點實際上是一個初級:

@task 
def provision(): 
    execute(stuff_to_do_on_all_hosts) 
    execute(stuff_to_do_on_mongo_primaries) 

@task 
def stuff_to_do_on_all_hosts(): 
    do_stuff() 

@task 
@roles('mongo') 
def stuff_to_do_on_mongo_primaries(): 
    if not is_primary(): 
     return 
    add_user() 
    do_other_stuff() 

另一種方法是首先建立初選名單,然後使用hosts參數execute

@task 
def provision(): 
    # ... do some stuff on each host here, e.g. install mongodb 
    execute(stuff_to_do_on_all_hosts) 

    # build list of mongo primaries 
    primaries = [host for host, result in execute(is_primary, roles=('mongo',)).iteritems() if result] 

    # run task only on those hosts 
    execute(stuff_to_do_on_mongo_primaries, hosts=primaries) 

@task 
def stuff_to_do_on_all_hosts(): 
    do_stuff() 

@task 
def stuff_to_do_on_mongo_primaries(): 
    add_user() 
    do_other_stuff() 

希望這有助於。

+0

感謝您的迴應,抱歉,我直到現在纔看到它! – mstringer

相關問題