Ansible-将set_fact模块与with_items一起使用时,如何继续将新关键字附加到字典中? [英] Ansible - How to keep appending new keys to a dictionary when using set_fact module with with_items?

查看:306
本文介绍了Ansible-将set_fact模块与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 }}"

推荐答案

使用过滤器插件.

首先,在您的基础目录中创建一个名为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中的c1>选项.

You can customize the location of the filter plugin using the filter_plugins option in ansible.cfg.

这篇关于Ansible-将set_fact模块与with_items一起使用时,如何继续将新关键字附加到字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆