如何收集结构任务输出并打印多个主机的摘要?
How can I collect fabric task output and print a summary for multiple hosts?
在 fabric 中,我有一个任务是在每个主机的基础上收集一些东西(小例子)。
from fabric.api import task, run, hide
env.hosts['h1', 'h2', 'h3']
@task
def info():
with hide('everything'):
info = run("who | tail -n 1")
print("On host {0} last user was {1}".format(env.host_string, info))
运行 和
fab info
会给出类似
[h1] Executing task 'info'
On host h1 last user was userXX pts/29 2015-07-29 15:57 (:0)
[h2] Executing task 'info'
On host h2 last user was userXX pts/29 2015-07-29 16:57 (:0)
[h3] Executing task 'info'
On host h3 last user was userXX pts/29 2015-07-29 17:57 (:0)
虽然这对于 3 或 5 个主机来说很好,但是对于 20 个或更多主机(或更复杂的输出)来说很难查看。我想要做的是累积每台主机的所有输出,并在每台主机上执行任务后使用它最终创建一个 summary/overview。
我该怎么做?
...在写这个问题时,经过至少一个小时 googleing 不同的短语,我终于找到了这个:
http://docs.fabfile.org/en/1.14/usage/execution.html#leveraging-execute-to-access-multi-host-results
虽然我浏览了这个网站几次,但我错过了相关部分,因此想 post 在这里,希望如果不在上搜索确切的短语,它更容易找到google:
from fabric.api import task, execute, run, runs_once
@task
def workhorse():
return run("get my infos")
@task
@runs_once
def go():
results = execute(workhorse)
print results
因此问题中的示例可以通过以下方式解决:
from fabric.api import task, run, hide, execute, runs_once
env.hosts['h1', 'h2', 'h3']
@task
def collect_info():
with hide('everything'):
info = run("who | tail -n 1")
return info
@task
@runs_once
def info():
collected_output = execute(collect_info)
for host, info in collected_output.iteritems():
print("On host {0} last user was {1}".format(host, info))
在 fabric 中,我有一个任务是在每个主机的基础上收集一些东西(小例子)。
from fabric.api import task, run, hide
env.hosts['h1', 'h2', 'h3']
@task
def info():
with hide('everything'):
info = run("who | tail -n 1")
print("On host {0} last user was {1}".format(env.host_string, info))
运行 和
fab info
会给出类似
[h1] Executing task 'info'
On host h1 last user was userXX pts/29 2015-07-29 15:57 (:0)
[h2] Executing task 'info'
On host h2 last user was userXX pts/29 2015-07-29 16:57 (:0)
[h3] Executing task 'info'
On host h3 last user was userXX pts/29 2015-07-29 17:57 (:0)
虽然这对于 3 或 5 个主机来说很好,但是对于 20 个或更多主机(或更复杂的输出)来说很难查看。我想要做的是累积每台主机的所有输出,并在每台主机上执行任务后使用它最终创建一个 summary/overview。
我该怎么做?
...在写这个问题时,经过至少一个小时 googleing 不同的短语,我终于找到了这个:
http://docs.fabfile.org/en/1.14/usage/execution.html#leveraging-execute-to-access-multi-host-results
虽然我浏览了这个网站几次,但我错过了相关部分,因此想 post 在这里,希望如果不在上搜索确切的短语,它更容易找到google:
from fabric.api import task, execute, run, runs_once
@task
def workhorse():
return run("get my infos")
@task
@runs_once
def go():
results = execute(workhorse)
print results
因此问题中的示例可以通过以下方式解决:
from fabric.api import task, run, hide, execute, runs_once
env.hosts['h1', 'h2', 'h3']
@task
def collect_info():
with hide('everything'):
info = run("who | tail -n 1")
return info
@task
@runs_once
def info():
collected_output = execute(collect_info)
for host, info in collected_output.iteritems():
print("On host {0} last user was {1}".format(host, info))