该篇文章来源于 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.