在ansible中合并字典 [英] merging dictionaries in ansible

查看:25
本文介绍了在ansible中合并字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个使用 ansible 安装 PHP 的角色,但我在合并词典时遇到了一些困难.我已经尝试了几种方法,但我无法让它像我想要的那样工作:

I'm currently building a role for installing PHP using ansible, and I'm having some difficulty merging dictionaries. I've tried several ways to do so, but I can't get it to work like I want it to:

# A vars file:
my_default_values:
  key = value

my_values:
  my_key = my_value


# In a playbook, I create a task to attempt merging the
# two dictionaries (which doesn't work):

- debug: msg="{{ item.key }} = {{ item.value }}"
  with_dict: my_default_values + my_values

# I have also tried:

- debug: msg="{{ item.key }} = {{ item.value }}"
  with_dict: my_default_values|union(my_values)

# I have /some/ success with using j2's update,
# but you can't use j2 syntax in "with_dict", it appears.
# This works:

- debug: msg="{{ my_default_values.update(my_values) }}"

# But this doesn't:

- debug: msg="{{ item.key }} = {{ item.value }}"
  with_dict: my_default_values.update(my_values)

有没有办法合并两个字典,以便我可以将它与with_dict"一起使用?

Is there a way to merge two dictionaries, so I can use it with "with_dict"?

推荐答案

在 Ansible 2.0 中,有一个 Jinja 过滤器,combine,为此:

In Ansible 2.0, there is a Jinja filter, combine, for this:

- debug: msg="{{ item.key }} = {{ item.value }}"
  with_dict: "{{ my_default_values | combine(my_values) }}"

这篇关于在ansible中合并字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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