Ansible - 将 set_fact 模块与 with_items 一起使用时,如何继续将新键附加到字典中? [英] Ansible - How to keep appending new keys to a dictionary when using set_fact module with with_items?
问题描述
我想在使用 set_fact 和 with_items 时向字典添加键.这是一个小型 POC,它将帮助我完成一些其他工作.我试图概括 POC,以便从中删除所有不相关的细节.
I want to add keys to a dictionary when using set_fact with with_items. This is a small POC which will help me complete some other work. I have tried to generalize the POC so as to remove all the irrelevant details from it.
当我执行以下代码时,它会显示一个字典,其中只有一个键对应于 with_items 的最后一项.它似乎正在重新创建一个新字典,或者可能正在为 with_items 中的每个项目覆盖现有字典.我想要一个包含所有键的字典.
When I execute following code it is shows a dictionary with only one key that corresponds to the last item of the with_items. It seems that it is re-creating a new dictionary or may be overriding an existing dictionary for every item in the with_items. I want a single dictionary with all the keys.
代码:
---
- hosts: localhost
connection: local
vars:
some_value: 12345
dict: {}
tasks:
- set_fact: {
dict: "{
{{ item }}: {{ some_value }}
}"
}
with_items:
- 1
- 2
- 3
- debug: msg="{{ dict }}"
推荐答案
使用 过滤插件.
首先,在您的 ansible 基础目录中创建一个名为 filter_plugins/makedict.py
的新文件.
First, make a new file in your ansible base dir called filter_plugins/makedict.py
.
现在创建一个名为makedict"(或任何你想要的)的新函数,它接受一个值和一个列表,并返回一个新的字典,其中键是列表的元素,值总是相同的.
Now create a new function called "makedict" (or whatever you want) that takes a value and a list and returns a new dictionary where the keys are the elements of the list and the value is always the same.
class FilterModule(object):
def filters(self):
return { 'makedict': lambda _val, _list: { k: _val for k in _list } }
现在您可以使用剧本中的新过滤器来实现您想要的结果:
Now you can use the new filter in the playbook to achieve your desired result:
- hosts: 127.0.0.1
connection: local
vars:
my_value: 12345
my_keys: [1, 2, 3]
tasks:
- set_fact: my_dict="{{ my_value | makedict(my_keys) }}"
- debug: msg="{{ item.key }}={{ item.value }}"
with_dict: "{{my_dict}}"
您可以使用 自定义过滤器插件的位置ansible.cfg
中的 code>filter_plugins 选项.
You can customize the location of the filter plugin using the filter_plugins
option in ansible.cfg
.
这篇关于Ansible - 将 set_fact 模块与 with_items 一起使用时,如何继续将新键附加到字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!