将嵌套的字典列表转换为Ansible中的字典

时间:2019-11-06 10:23:38

标签: list ansible

我正在尝试在字典中转换字典列表。我定义的变量:

  users:
  - name: bruce
    age: 22
    params:
      - key: "k1"
        value: "v1bruce"
      - key: "k2"
        value: "v2bruce"
  - name: alan
    age: 25
    params:
      - key: "k1"
        value: "v1alan"
      - key: "k5"
        value: "v5alan"
  - name: carl
    age: 43
    params:
      - key: "k1"
        value: "v1carl"
      - key: "k2"
        value: "v2carl"
      - key: "k5"
        value: "v5carl"

我需要在Ansible中创建一个新结构,从之前将参数转换为字典的方式开始,如下所示:

  employee:
  - name: bruce
    age: 22
    params:
      "k1": "v1bruce"
      "k2": "v2bruce"
  - name: alan
    age: 25
    params:
      "k1": "v1alan"
      "k5": "v5alan"
  - name: carl
    age: 43
    params:
      "k1": "v1carl"
      "k2": "v2carl"
      "k5": "v5carl"

关键是我不知道我的起始列表由多少元素组成。 可能吗? 谢谢。

2 个答案:

答案 0 :(得分:0)

警告:前面有难看的解决方案。

要理解的基础是,您的params看起来像是通过dict2items过滤器对字典进行的转换。因此,我们必须使用items2dict来反转操作。但是由于它嵌套在您的哈希列表中,所以它并不是那么容易。这是我想出的:

---
- hosts: localhost
  gather_facts: False

  vars:
    users:
      - name: bruce
        age: 22
        params:
          - key: "k1"
            value: "v1bruce"
          - key: "k2"
            value: "v2bruce"
      - name: alan
        age: 25
        params:
          - key: "k1"
            value: "v1alan"
          - key: "k5"
            value: "v5alan"
      - name: carl
        age: 43
        params:
          - key: "k1"
            value: "v1carl"
          - key: "k2"
            value: "v2carl"
          - key: "k5"
            value: "v5carl"

  tasks:
    - name: Show raw
      debug:
        var: users

    - name: Transform
      set_fact:
        user_transformed: >-
          {%- set result = [] -%}
          {%- for user in users -%}
            {{
              result.append({
                 'name': user.name,
                 'age': user.age,
                 'params': user.params | items2dict
               })
            }}
          {%- endfor -%}
          {{ result | to_json | from_json }}

    - name: Show transformed
      debug:
        var: user_transformed

答案 1 :(得分:0)

循环使用items2dict。例如

- set_fact:
    employee: "{{ employee|default([]) +
                  [{'name': item.name,
                    'age': item.age,
                    'params': item.params|items2dict}] }}"
  loop: "{{ users }}"