2011-03-17 41 views
30

我有這樣一個fabfile如下:Python結構任務可以調用其他任務並尊重它們的主機列表嗎?

@hosts('host1') 
def host1_deploy(): 
    """Some logic that is specific to deploying to host1""" 

@hosts('host2') 
def host2_deploy(): 
    """Some logic that is specific to deploying to host2""" 

def deploy(): 
    """"Deploy to both hosts, each using its own logic""" 
    host1_deploy() 
    host2_deploy() 

我願做

fab deploy 

,並把它等同於

fab host1_deploy host2_deploy 

換句話說,運行各子任務,併爲每個人使用它指定的主機列表。但是,這不起作用。相反,deploy()任務需要它自己的主機列表,它將傳播給它的所有子任務。

有沒有辦法在這裏更新deploy()任務,所以它會做我想要的,同時留下子任務,讓他們可以單獨運行?

回答

1

有可能是一個更好的方式來處理它,但你可以通過兩臺主機部署(),然後在host1_deploy()和host2_deploy()檢查env.host:

def host1_deploy(): 
    if env.host in ['host1']: 
     run(whatever1) 

def host2_deploy(): 
    if env.host in ['host2']: 
     run(whatever2) 

@hosts('host1','host2') 
def deploy(): 
    host1_deploy() 
    host2_deploy() 
1

試試這一個。顯然你想用runsudo替換本地。最關鍵的是空@hosts裝飾爲deploy

from fabric.api import local 
from fabric.decorators import hosts 

@hosts('host1') 
def host1_deploy(): 
    """Some logic that is specific to deploying to host1""" 
    local('echo foo') 

@hosts('host2') 
def host2_deploy(): 
    """Some logic that is specific to deploying to host2""" 
    local('echo bar') 

@hosts('') 
def deploy(): 
    """"Deploy to both hosts, each using its own logic""" 
    host1_deploy() 
    host2_deploy() 
+0

不起作用... – 2011-08-14 09:55:34

3

這是跛,但它可以作爲面料的1.1.2

def host1_deploy(): 
    """Some logic that is specific to deploying to host1""" 
    if env.host in ["host1"]: 
     pass #this is only on host2 

def host2_deploy(): 
    """Some logic that is specific to deploying to host2""" 
    if env.host in ["host2"]: 
     pass #this is only on host2 

def deploy(): 
    """"Deploy to both hosts, each using its own logic""" 
    host1_deploy() 
    host2_deploy() 

這裏是我的測試代碼:

@task 
@roles(["prod_web","prod_workers"]) 
def test_multi(): 
    test_multi_a() 
    test_multi_b() 

def test_multi_a(): 
    if env.host in env.roledefs["prod_web"]: 
     run('uname -a') 

def test_multi_b(): 
    if env.host in env.roledefs["prod_workers"]: 
     run('uname -a') 
30

由於面料1.3 ,execute幫手現在可以做到這一點。該文檔可在此處獲得:Intelligently executing tasks with execute

這裏是他們使用的例子:

from fabric.api import run, roles 

env.roledefs = { 
    'db': ['db1', 'db2'], 
    'web': ['web1', 'web2', 'web3'], 
} 

@roles('db') 
def migrate(): 
    # Database stuff here. 
    pass 

@roles('web') 
def update(): 
    # Code updates here. 
    pass 

然後運行從另一個任務deploymigrateweb

def deploy(): 
    execute(migrate) 
    execute(update) 

,這將尊重角色和主機列出了這些任務有。

+0

是否可以將該角色添加到類方法中?我使用類來完成結構任務 – 2013-11-28 13:39:45

+1

指向文檔的鏈接已損壞。這是最新版本:http://docs.fabfile.org/en/1.8/usage/execution.html#intelligently-executing-tasks-with-execute – krd 2014-05-21 23:02:16

相關問題