自動化運維工具Fabric - 智能的執行任務(roles、execute)

該篇文章來源於 Fabric 的官方文檔,原文爲Intelligently executing tasks with execute
注:該功能只在 Fabric 1.3 版本中有效,主要是使用 execute 功能html

在 Fabric 1.3 版本中,你能夠經過 roles 來給服務器定義一組角色,而後根據角色 使用 execute 來執行不一樣的操做。web

代碼一

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

在 Fabric <= 1.2 版本的時候,這惟一讓 migrate操做 在 db組 服務器生效, update 操做在 web 組服務器生效的方法以下:api

$ fab migrate update

代碼二

而在 Fabric 1.3 版本中,你可使用 execute 來啓動一個元任務,你能夠修改代碼以下:服務器

from fabric.api import run, roles, execute
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

# 新增的 execute 模塊
def deploy():
    execute(migrate)
    execute(update)

而後執行以下命令:ide

fab deploy

這樣的話,roles 裝飾符會如預期的那樣生效。執行的結果以下:測試

migrate on db1
migrate on db2
update on web1
update on web2
update on web3

注意

這個技巧讓任務僅僅只運行一次,是由於它們本身沒有主機列表(包含全局主機列表設置),若是將在多個主機上運行使用 一個 'regular' 任務,調用 execute 將屢次運行,結果就是成子任務調用數量乘數級的增長 -- 當心this

注:主機數量很大,容易形成 「執行風暴」?屢次重複執行?把本機弄死?仍是客戶端的任務會被重複執行。須要找一組測試機測試下,目前還未測試。有測試過的同窗能夠給個最終的答案。
注: reguar 翻譯爲 普通?按期的?合格的。歡迎各位指正下。翻譯

若是你想讓你的 exeute 調用 僅僅只執行一次,你可使用 runs_once 裝飾符。code

This technique works because tasks that themselves have no host list (this includes the global host list settings) only run one time. If used inside a 「regular」 task that is going to run on multiple hosts, calls to execute will also run multiple times, resulting in multiplicative numbers of subtask calls – be careful!htm

If you would like your execute calls to only be called once, you may use the runs_once decorator.

相關文章
相關標籤/搜索