我需要对env.hosts进行排序,以按特定顺序运行任务

时间:2016-02-12 02:08:21

标签: python fabric postgresql-bdr

我需要从roledef中对主机进行排序,以便他们可以按特定顺序运行这些任务。

我正在实施PostgreSQL BDR(http://2ndquadrant.com/en-us/resources/bdr/)部署者。要成功,您需要在主机中创建BDR组,然后才能在所有其他主机中加入BDR组。

用户需要从列表中选择哪个是第一个主机。

---- ---- EDITED

我尝试动态设置env.hosts,但它不起作用。

env.roledefs = {
  'array1':    [],
}

env.hostsdefs = {
  'array1': [
    {'host': 'data-03', 'server': 'root@data-03'},
    {'host': 'data-01', 'server': 'root@data-01'},
  ],
}

@serial
def sort_and_echo(default_host):
    sort_host(default_host)
    echoing()

@serial
def sort_host(default_host):
    hostnames = env.hostsdefs[env.roles[0]]
    new_hosts = []
    for host in (hostnames):
        if (host['host'] != default_host):
            new_hosts.append(host['server'])
        else:
            new_hosts = [host['server']] + new_hosts
    env.hosts = new_hosts


@serial
def echoing():
    print env.hosts
    print('current host: %s' % (env.host_string))

这样,如果我尝试:

fab -R array1 sort_and_echo:default_host=data-03
['root@data-03', 'root@data-01']
current host: None

Done.

它不会为列表中的每个服务器运行回显。

但是,如果我尝试一种,然后在同一个命令中回显:

fab -R array1 sort_host:default_host=data-03 echoing

它将提供预期的输出:

[root@data-03] Executing task 'echoing'
['root@data-03', 'root@data-01']
current host: root@data-03
[root@data-01] Executing task 'echoing'
['root@data-03', 'root@data-01']
current host: root@data-01

Done.

如何在运行时更改主机列表?

2 个答案:

答案 0 :(得分:1)

After a while I solve my problem. It was easier than expected. No hacks needed.

Passing the hosts parameter would make the host to be added at the begging of the array. As the standard behaviour of fabric is to throw out deduplication (check Host list deduplication in http://docs.fabfile.org/en/1.10/usage/execution.html#combining-host-lists), it solves the problem.

If you don't pass the parameter, it will use the first one of the array

class A extends React.Component {

}

A.childContextTypes = {
  name: React.PropTypes.string.isRequired
};

So when I try:

env.roledefs = {
'array1': {'hosts': ['root@data-01', 'root@data-03'], }
}

It will run in the correct order:

fab -R array1 -H data-03 echoing

答案 1 :(得分:0)

如果我理解正确,你可以这样做:

@task
def environment(*args):
    env.hosts = args

@task
def dev(*args):
    hosts = list(args)
    hosts.append('dev.host1')
    hosts.append('dev.host2')
    environment(*hosts)

@task
@serial # <--- PS. you dont really need this
def echoing():
    print env.hosts
    print('current host: %s' % (env.host_string))

你现在可以这样称呼它:

fab environment:node1.host.com,node2.host.com echoing

或:

# which is a "predetermined" list
fab dev echoing
# or add stuff to dev
fab dev:qa.node.host.com echoing
# ^^ this will just append the qa host to your existing list