I have some code which basically searches some YAML files for Jinja2 variables and replaces them where appropriate. I want to be able to combine to YAML dicts together and was looking for a way to do this using the default Jinja2 library.
Here is some example YAML of what I am trying to a achieve:
vars.yml
vars:
default:
name: test1
location: UK
new:
name: test2
country: UK
template.yml
test: {{ vars.default.update(vars.new) }}
This would ideally output something like:
output.yml
test:
name: test2
location : UK
country: UK
I am looking for a way to merge two dictionaries together using this method. The Jinja2 documentation don't appear to have an inbuilt function like the Ansible combine filter.
Is it possible that I just import this feature into my code or create a similar feature? I noticed that it is not included in the standard library for Ansible Jinja2 filters
When trying to use the update filter (which doesn't appear to exist in the Jinja2 documentation) I get a None
result.
The update
method of a dictionary is actually updating the source dictionary, not returning the merged dictionaries.
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. ReturnNone
.
Source: https://docs.python.org/3/library/stdtypes.html#dict.update
So, you have two ways of achieving it:
{% do ... %}
construct:
{% do vars.default.update(vars.new) -%}
test: {{ vars.default }}
{% set noop = vars.default.update(vars.new) -%}
test: {{ vars.default }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With