智能的执行任务(roles、execute)

该篇文章来源于 Fabric 的官方文档,原文为Intelligently executing tasks with execute
注:该功能只在 Fabric 1.3 版本中有效,主要是使用 execute 功能

在 Fabric 1.3 版本中,你可以通过 roles 来给服务器定义一组角色,然后根据角色 使用 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

在 Fabric <= 1.2 版本的时候,这唯一让 migrate操作 在 db组 服务器生效, update 操作在 web 组服务器生效的方法如下:

$ 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)

然后执行如下命令:

fab deploy

这样的话,roles 装饰符会如预期的那样生效。执行的结果如下:

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

这个技巧让任务仅仅只运行一次,是因为它们自己没有主机列表(包含全局主机列表设置),如果将在多个主机上运行使用 一个 'regular' 任务,调用 execute 将多次运行,结果就是成子任务调用数量乘数级的增加 -- 小心

注:主机数量很大,容易造成 “执行风暴”?多次重复执行?把本机弄死?还是客户端的任务会被重复执行。需要找一组测试机测试下,目前还未测试。有测试过的同学可以给个最终的答案。
注: reguar 翻译为 普通?定期的?合格的。欢迎各位指正下。

如果你想让你的 exeute 调用 仅仅只执行一次,你可以使用 runs_once 装饰符。

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!

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

使用 Vagrant 和 Fabric 用于集成测试

Fabric:Python远程部署工具

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c337ee1f78eaf614286247c45b8c3326.html