使用jinja2从列表生成对(可翻译)

Generate pairs from list using jinja2 (ansible)

我正在尝试根据ansible中的主机列表生成一对主机
我有以下库存

1
2
3
4
5
6
[webs]
test
test2
test3
test4
test5

如何生成主机对,例如测试和测试2,测试3和测试4,测试5和测试(从第一个重复开始)

我尝试了批处理,切片和with_items之类的过滤器,但似乎不起作用。

有没有一种简便的方法可以生成这些对?


您可以进一步优化。

1
2
3
4
5
6
  tasks:
  - set_fact: total_hosts={{groups['webs'] | length }}
  - debug: msg={{groups['webs'] | slice(total_hosts | int // 2) | list}}
    when:"{{total_hosts |int is divisibleby 2}}"
  - debug: msg={{groups['webs'] | slice(total_hosts | int // 2 + 1, fill_with=groups['webs'][0]) | list}}
    when:"{{total_hosts |int is not divisibleby 2}}"

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
TASK [debug] *******************************************************************
ok: [localhost] => {
   "msg": [
        [
           "test",
           "test2"
        ],
        [
           "test3",
           "test4"
        ],
        [
           "test5",
           "test"
        ]
    ]
}