首页 > 解决方案 > 在循环中使用 ansible jinja2 组合过滤器

问题描述

我得到了这个简单的剧本,我试图使用combine过滤器从键/值对列表中构造一个字典。问题是在循环对时它似乎不起作用(我试过循环,with_dict,with_items)。

- name: test jinja2 combine filter
  hosts: localhost    
    - name: test combine
      vars:
        x: {'three', 3}
      set_fact:
        x: "{{ x | combine(item) }}"
      with_items: [{'one': 1},{'two': 2}]

    # I am expecting to see the two new dicts here,
    # but only the last one in the list is added
    - name: print x
      debug: msg={{ x }}

预期输出:

ok: [localhost] => {
    "msg": {
        "three": 3,
        "one": 1,
        "two": 2
    }
}

我的结果:

ok: [localhost] => {
    "msg": {
        "three": 3, 
        "two": 2
    }
}

这篇文章来看,似乎没有针对此类问题的开箱即用解决方案。虽然编写自定义插件并不难,但我仍然想知道是否有不编写插件的标准解决方案。

标签: filteransiblejinja2combine

解决方案


希望您已经找到了可行的解决方案...如果没有,这可以帮助您:

- name: test jinja2 combine filter
  hosts: localhost   
  vars:
    x: 
      three: 3
    xx: 
      one: 1
      two: 2

  tasks: 
    - debug: 
        var: x
    - debug: 
        var: xx
    - name: test combine
      set_fact:
        z: "{{ x | combine(xx) | to_nice_json }}"
    - debug: 
        var: z

这给了我:

PLAY [test jinja2 combine filter] ***************************

TASK [debug] ***************************
ok: [localhost] => {
    "x": {
        "three": 3
    }
}

TASK [debug] ***************************
ok: [localhost] => {
    "xx": {
        "one": 1,
        "two": 2
    }
}

TASK [test combine] ***************************
ok: [localhost]

TASK [debug] ***************************
ok: [localhost] => {
    "z": {
        "one": 1,
        "three": 3,
        "two": 2
    }
}

PLAY RECAP ***************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

推荐阅读