使用以下 json:
msg: [
{
"name": "Primary_colors",
"sub_attrs": [
{
"name": "Red",
},
{
"name": "Blue",
},
{
"name": "Yellow",
}
],
},
{
"name": "Secondary_colors",
"sub_attrs": [
{
"name": "Green",
},
{
"name": "Orange",
},
{
"name": "Purple",
}
],
}
]
使用 Ansible 如何映射每种颜色类型的名称以使其成为字典键,并使 sub_attrs 的名称属性作为每个颜色类型的列表的值
我已经能够提取我想要的数据,但我不知道如何使 types_of_colors 成为键并将 sub_attrs 中的名称映射到正确的颜色类型,这应该是一个列表
- name: Set facts
set_fact:
types_of_colors: '{{ msg | map(attribute='name') | list }}'
names_of_colors: '{{ msg | map(attribute='sub_attrs') | sum(start=[]) | map(attribute='name') | list }}'
如何将颜色类型作为键并根据类型将颜色名称分组到列表中并将其转换为字典
预期结果数据结构:
Primary_colors:
- Red
- Blue
- Yellow
Secondary_colors:
- Green
- Orange
- Purple
最佳答案
从字典列表中提取键名:
my_keys: {{ msg | map(attribute='name' }}
这给出:
"my_keys": [
"Primary_colors",
"Secondary_colors"
]
提取sub_attrs
列表并将其转换为列表列表:
my_values: "{{ msg | map(attribute='sub_attrs') | map('map', attribute='name') }}"
这给出:
"my_values": [
[
"Red",
"Blue",
"Yellow"
],
[
"Green",
"Orange",
"Purple"
]
]
此时,我们有两个同步列表,一侧为键,另一侧为值。在预期结果字典中重新排列键和值:
my_colors_dict: "{{ my_keys | zip(my_values) | community.general.dict }}"
# or using python's `dict()` directly
my_colors_dict: "{{ dict(my_keys | zip(my_values)) }}"
两个表达式是等价的并且给出:
"my_colors_dict": {
"Primary_colors": [
"Red",
"Blue",
"Yellow"
],
"Secondary_colors": [
"Green",
"Orange",
"Purple"
]
}
您可以使用以下完整的剧本来测试上述内容:
---
- name: Transform data demo
hosts: localhost
gather_facts: false
vars:
msg: [
{
"name": "Primary_colors",
"sub_attrs": [
{
"name": "Red",
},
{
"name": "Blue",
},
{
"name": "Yellow",
}
],
},
{
"name": "Secondary_colors",
"sub_attrs": [
{
"name": "Green",
},
{
"name": "Orange",
},
{
"name": "Purple",
}
],
}
]
my_keys: "{{ msg | map(attribute='name') }}"
my_values: "{{ msg | map(attribute='sub_attrs') | map('map', attribute='name') }}"
my_colors_dict: "{{ my_keys | zip(my_values) | community.general.dict }}"
# Alternative syntax whith python's `dict()`
# my_colors_dict: "{{ dict(my_keys | zip(my_values)) }}"
tasks:
- name: Show extracted list of keys
ansible.builtin.debug:
var: my_keys
- name: Show the extracted and reworked list of values
ansible.builtin.debug:
var: my_values
- name: Show the result dict
ansible.builtin.debug:
var: my_colors_dict
关于list - 如何将属性映射到 Ansible 中的列表字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77128463/