将词典合并成可以 [英] merging dictionaries in ansible

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

问题描述

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

 #一个vars文件:
my_default_values:
key = value

my_values:
my_key = my_value


#在一个playbook ,我创建一个任务来尝试合并
#两个字典(不起作用):

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

#我也尝试过:

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

#我有/一些/成功使用j2的更新,
#但你不能使用j2语法在with_dict中出现。
#这样做:

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

#但是这不是:

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

有没有办法合并两个字典,所以我可以使用with_dict?

解决方案

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

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

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)

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

解决方案

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) }}"

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

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