如何使用结构在具有不同参数的多个主机上并行运行相同的任务?

时间:2016-06-07 18:07:16

标签: python fabric

demo.py

from fabric.api import env, run,execute

env.hosts = ['10.1.1.100','10.1.1.200']
env.remotePath = {'10.1.1.100':'/home','10.1.1.200':'/var'}
env.parallel=True

def mytask(remotePath):
    run('ls %s' % remotePath)

def test():
    execute(mytask,env.remotePath[env.host])

fab -f demo.py test

我想使用@parallel装饰器在10.1.1.100执行命令ls /home,在10.1.1.200并行执行ls /var,有没有办法让它成为可能?

1 个答案:

答案 0 :(得分:0)

使用host_string获取当前主机,然后使用您要使用的命令/参数。

@parallel
def mytask():
  host_ip = env.host_string
  remote_path = env.remotePath[host_ip]
  run('ls %s' % remote_path)

根据Fabric的API文档:host_string

  

定义Fabric将连接到的当前用户/主机/端口   执行run,put等等。这是由fab在迭代时设置的   在先前设置的主机列表上,也可以在何时手动设置   使用Fabric作为库。

希望这会有所帮助:)

相关问题