传递Fabric环境。
demo.py
#!/usr/bin/env python
from fabric.api import env, run
def deploy(hosts, command):
print hosts
env.hosts = hosts
run(command)
main.py
#!/usr/bin/env python
from demo import deploy
hosts = ['localhost']
command = 'hostname'
deploy(hosts, command)
python main.py ['localhost']
No hosts found. Please specify (single) host string for connection:
但env。hostrongtring作品!
demo.py
#!/usr/bin/env python
from fabric.api import env, run
def deploy(host, command):
print host
env.host_string = host
run(command)
main.py
#!/usr/bin/env python
from demo import deploy
host = 'localhost'
command = 'hostname'
deploy(host, command)
python main.py localhost
[localhost] run: hostname
[localhost] out: heydevops-workspace
但是嫉妒。Hostrongtring对我们来说还不够,它是单个主机。也许我们可以用env。Hostrongtring在循环中,但这不是很好。因为我们还想设置并发任务数并并行运行它们。
现在在ddep(我的部署引擎)中,我只使用MySQLdb来获取参数,然后执行fab命令,如:
os.system("fab -f service/%s.py -H %s -P -z %s %s" % (project,host,number,task))
这是一个简单的方法,但不是很好。因为如果我使用fab命令,我无法在Python中捕获结果的异常和失败,从而使我的ddep可以"重试"失败的主机。如果我使用"from demo import deploy",我可以通过Python中的一些代码来控制和获取它们。
所以现在"env。"主机"就是麻烦。谁能给我一个解决办法?非常感谢。
以下是我的见解。
根据文档,如果你从python脚本调用fabric任务-你应该使用fabric.tasks.execute.
应该是这样的:
-
demo.py
from fabric.api import run from fabric.tasks import execute def deploy(hosts, command): execute(execute_deploy, command=command, hosts=hosts) def execute_deploy(command): run(command)
-
main.py
from demo import deploy hosts = ['localhost'] command = 'hostname' deploy(hosts, command)
然后,运行python main.py
。
最后,我使用execute()和exec解决了这个问题。
main.py
#!/usr/bin/env python
from demo import FabricSupport
hosts = ['localhost']
myfab = FabricSupport()
myfab.execute("df",hosts)
demo.py
#!/usr/bin/env python
from fabric.api import env, run, execute
class FabricSupport:
def __init__(self):
pass
def hostname(self):
run("hostname")
def df(self):
run("df -h")
def execute(self,task,hosts):
get_task = "task = self.%s" % task
exec get_task
execute(task,hosts=hosts)
python main.py [localhost] Executing task 'hostname'
[localhost] run: hostname
[localhost] out: heydevops-workspace