如何在Python脚本中调用fabfile

0 投票
2 回答
978 浏览
提问于 2025-04-18 08:02

我在我的Python脚本中启动fabfile时遇到了困难。我查阅了Stack Overflow上类似的问题,但都没有解决我的问题……或者说它们可能解决了,但我没理解……不太确定。

我的脚本会根据用户想要在远程主机上运行的内容来写入fab文件。这里有一个fabfile的例子:

[root@ip-50-50-50-50 bakery]# cat fabfile.py
from fabric.api import run
def deploy():
    run('wget -P /tmp https://s3.amazonaws.com/MyBucket/httpd-2.2.26-1.1.amzn1.x86_64.rpm')
    run('sudo yum localinstall /tmp/httpd-2.2.26-1.1.amzn1.x86_64.rpm')

接下来,我需要从我的脚本中运行这个fabfile。如果我在命令行中手动运行以下命令,那是可以正常工作的:

fab -f fabfile.py -u ec2-user -i id_rsa -H 10.10.15.150 deploy

1) 我该如何在我的脚本中运行这个命令,并且带上所有的选项? 2) IP地址是一个叫“bakery_internalip”的变量。我该如何在fab命令中使用这个变量?

2 个回答

0

你可以直接在代码中调用启用fabric的命令。通常,你需要先设置一个环境字典来指定一些键和主机,但这个过程非常简单:

# the settings for the env dict
from fabric.api import env, execute
env.hosts = ["10.10.15.150", ]
env.user = "ec2-user"
env.key = "id_rsa"

# and call the function itself
from fabfile import deplot
execute(deploy, hosts=env.hosts)

你可以在fabric的文档中找到更多灵感: http://docs.fabfile.org/en/1.11/usage/execution.html#using-execute-with-dynamically-set-host-lists

0

试试用 subprocess 这个方法:

import subprocess
subprocess.call(['fab', '-f', 'fabfile.py', '-u ec2-user', '-i', 'id_rsa', '-H', bakery_internalip, 'deploy'])

这样应该就能解决问题了

撰写回答