首页 > 解决方案 > 根据现有键为列表中的每个字典设置新键

问题描述

说我有:

[ {a: 'a'}, {a: 'b'}]

而且我要:

[ {a: 'a', b: 'ab'}, {a: 'b', b: 'bb'}]

我将如何在 Ansible 中做到这一点?希望它会像

- set_fact:
    result: "{{ input | map('combine', dict(b=item.a + 'b')) | list }}"

但我不知道item在这种情况下如何访问。

标签: ansibleansible-2.x

解决方案


如果 jinja 中的“单行”不起作用,或者太简洁以至于其他人无法阅读,那么这可能不是一个好主意

- set_fact:
    # we are cloning the input dicts for mutation
    result: >-
      {%- set output = [] -%}
      {%- for d in input: -%}
      {%-   set d2 = dict(d) -%}
      {%-   set _ = d2.update({"b": d2["a"] + "b"}) -%}
      {%-   set _ = output.append(d2) -%}
      {%- endfor -%}
      {{- output -}}

推荐阅读