As the title suggest i want to loop over an existing dictionary and change some values, based on the answer to this question i came up with the code below but it doesn't work as the values are unchanged in the second debug call, I'm thinking it is because in the other question they are creating a new dictionary from scratch, but I've also tried it without the outer curly bracket which i would have thought would have caused it to change the existing value.
- set_fact:
uber_dict:
a_dict:
some_key: "abc"
another_key: "def"
b_dict:
some_key: "123"
another_key: "456"
- debug: var="uber_dict"
- set_fact: "{ uber_dict['{{ item }}']['some_key'] : 'xyz' }"
with_items: "{{ uber_dict }}"
- debug: var="uber_dict"
To solve this problem, Ansible offers us one module named “include_vars” which loads variables from files dynamically within the task. This module can load the YAML or JSON variables dynamically from a file or directory, recursively during task runtime.
The variables are referenced through the Jinja2 template system, known to many from the Python language. It is very flexible. It supports both conditional expressions and loops. We reference the value of a variable in Jinja2 by placing its name inside double curly braces “{{ }}“.
Variable Scopes Global: this is set by config, environment variables and the command line. Play: each play and contained structures, vars entries, include_vars, role defaults and vars. Host: variables directly associated to a host, like inventory, facts or registered task outputs.
You can not change existing variable, but you can register new one with the same name.
Check this example:
---
- hosts: localhost
gather_facts: no
vars:
uber_dict:
a_dict:
some_key: "abc"
another_key: "def"
b_dict:
some_key: "123"
another_key: "456"
tasks:
- set_fact:
uber_dict: "{{ uber_dict | combine(new_item, recursive=true) }}"
vars:
new_item: "{ '{{ item.key }}': { 'some_key': 'some_value' } }"
with_dict: "{{ uber_dict }}"
- debug:
msg: "{{ uber_dict }}"
result:
ok: [localhost] => {
"msg": {
"a_dict": {
"another_key": "def",
"some_key": "some_value"
},
"b_dict": {
"another_key": "456",
"some_key": "some_value"
}
}
}
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