合并Ansible中的字符串列表

时间:2019-04-24 01:28:27

标签: ansible

我在Ansible中有两个字符串列表:

vars:
  pre:
    - one
    - two
  post:
    - alpha
    - beta

我可以轻松获得这些列表的笛卡尔积:

set_fact: prods="{{pre|product(post)|list}}"

然后如何合并各个部分以获取如下列表:

prods:
  - one-alpha
  - one-beta
  - two-alpha
  - two-beta

1 个答案:

答案 0 :(得分:0)

循环播放!

---
- hosts: localhost
  gather_facts: false

  vars:
    pre:
      - one
      - two
    post:
      - alpha
      - beta

  tasks:
    - set_fact:
        prods: "{{ prods|default([]) + ['{}-{}'.format(item.0, item.1)] }}"
      loop: "{{ pre|product(post)|list }}"

    - debug:
        var: prods

这将产生输出:

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "prods": [
        "one-alpha", 
        "one-beta", 
        "two-alpha", 
        "two-beta"
    ]
}