Ansible:使用items2dict将列表转换为字典

2024-10-03 21:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于以下清单:

fruits:
  - fruit: apple
    color: red
    texture: crunchy
    shape: round
  - fruit: grapefruit
    color: yellow
    taste: sour
  - fruit: pear
    color: yellow

如何使用items2dict过滤器更改为字典(如下)? 问题是有多个,并且值的数量是可变的

"{{ fruits | items2dict(key_name='fruit', value_name='??????') }}

预期结果:

fruits:
  - apple:
      color: red
      texture: crunchy
      shape: round
  - grapefruit:
      color: yellow
      taste: sour
  - pear:
      color: yellow

我似乎在这里找不到方法:https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#transforming-lists-into-dictionaries


Tags: appleredcolorpearshapefruityellowround
2条回答

items2dict()函数不适合您的情况,但您可以使用以下简单方法:

rows = """\
fruits:
  - fruit: apple
    color: red
    texture: crunchy
    shape: round
  - fruit: grapefruit
    color: yellow
    taste: sour
  - fruit: pear
    color: yellow"""

rows_changed = "\n".join([2*" " + row if row.startswith(4*" ") else row 
                             for row in rows.split("\n")])
print(rows_changed)

解释:

  1. rows.split("\n")rows多行字符串创建行列表
  2. 然后[](列表理解)中的表达式2*" " + row if row.startswith(4*" ") else row将从4-空间缩进开始的行缩进另一个2-空间缩进
  3. "\n".join()将(修改过的)行列表转换回多行字符串

输出:

fruits:
  - fruit: apple
      color: red
      texture: crunchy
      shape: round
  - fruit: grapefruit
      color: yellow
      taste: sour
  - fruit: pear
      color: yellow

我认为你可以做一些类似的事情:

- name: bla
  set_fact:
    res: "{{ res | default({}) | combine({ item['fruit']: item }) }}"
  loop: "{{ fruits }}"

相关问题 更多 >