Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging dictionaries in ansible

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"?

like image 768
Berry Langerak Avatar asked Aug 21 '14 09:08

Berry Langerak


People also ask

How to merge two dicts in Ansible?

If you have two or more lists of dictionaries and want to combine them into a list of merged dictionaries, where the dictionaries are merged by an attribute, you can use the lists_mergeby filter. The output of the examples in this section use the YAML callback plugin.

Can I use two dictionaries to merge?

You can merge two dictionaries using the | operator. It is a very convenient method to merge dictionaries; however, it is only used in the python 3.9 version or more.

How do I merge two dictionaries in a single expression?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.


1 Answers

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) }}" 
like image 169
augurar Avatar answered Sep 20 '22 18:09

augurar