在不同主机上使用不同的fabric参数

4 投票
1 回答
684 浏览
提问于 2025-04-18 13:32

请告诉我,如何在一组主机上执行fab脚本,使用相同的命令,但参数的值不同。大概是这样的:

from fabric.api import *

def command(parameter):
        run ("command%s" % parameter)

然后执行这个。我不知道怎么做。例如:

fab -H host1,host2,host3 command:param1 command:param2 command:param3

然后Fabric会执行以下操作:

  • 在host1上执行command:param1
  • 在host2上执行command:param2
  • 在host3上执行command:param3

1 个回答

3

我做这件事的方法是把任务参数化。对我来说,这涉及到将代码部署到开发环境、测试环境和生产环境。

fabfile.py:

from ConfigParser import ConfigParser


from fabric.tasks import Task
from fabric.api import execute, task


@task()
def build(**options):
    """Your build function"""


class Deploy(Task):

    name = "dev"

    def __init__(self, *args, **kwargs):
        super(Deploy, self).__init__(*args, **kwargs)

        self.options = kwargs.get("options", {})

    def run(self, **kwargs):
        options = self.options.copy()
        options.update(**kwargs)
        return execute(build, **options)


config = ConfigParser()
config.read("deploy.ini")

sections = [
    section
    for section in config.sections()
    if section != "globals" and ":" not in section
]

for section in sections:
    options = {"name": section}
    options.update(dict(config.items("globals")))
    options.update(dict(config.items(section)))

    t = Deploy(name=section, options=options)
    setattr(t, "__doc__", "Deploy {0:s} instance".format(section))
    globals()[section] = task

deploy.ini:

[globals]
repo = https://github.com/organization/repo

[dev]
dev = yes
host = 192.168.0.1
domain = app.local

[prod]
version = 1.0
host = 192.168.0.2
domain = app.mydomain.tld

希望这很明显,你可以通过简单地编辑你的 deploy.ini 配置文件,来配置各种不同的部署方式,然后自动创建出符合这些参数的新任务。

这个模式也可以适应 YAMLJSON 格式,如果你喜欢这些格式的话。

撰写回答