在Ansible中,可以使用dict2items
过滤器将字典转换为键值对的列表。然后,你可以使用selectattr
过滤器选择具有特定属性的项目,并使用map
过滤器将它们的属性组合在一起。
以下是一个示例代码:
- name: Select and combine attributes from a dictionary
hosts: localhost
gather_facts: false
vars:
my_dict:
- name: John
age: 30
city: New York
- name: Jane
age: 25
city: London
- name: Mike
age: 35
city: Sydney
tasks:
- name: Convert dictionary to list of key-value pairs
set_fact:
dict_items: "{{ my_dict | dict2items }}"
- name: Select items with specific attributes and combine them
set_fact:
combined_attributes: "{{ dict_items | selectattr('value.age', 'defined') | selectattr('value.city', 'defined') | map(attribute='value') | list }}"
- name: Print combined attributes
debug:
var: combined_attributes
在上面的示例中,我们首先使用dict2items
过滤器将my_dict
转换为列表dict_items
。然后,我们使用selectattr
过滤器选择具有age
和city
属性的项目。接下来,我们使用map
过滤器从选择的项目中提取value
属性,并将它们组合在一起。最后,我们打印出组合的属性combined_attributes
。
这将输出:
combined_attributes:
- name: John
age: 30
city: New York
- name: Jane
age: 25
city: London
- name: Mike
age: 35
city: Sydney
可以看到,我们只选择了具有age
和city
属性的项目,并将它们的属性组合在一起。