The ansible.utils.replace_keys
filter does exactly what you want, but with keys instead of values. It should be possible to use ansible_collections/ansible/utils/plugins/plugin_utils/replace_keys.py
as a starting point and create a filter that does a similar thing with values.
Another approach would be to convert Starting_situation
to a string with to_yaml
or to_json
, then loop over your To_be_replaced
keys substituting the values with regex_replace
, and finally converting the whole thing back with from_yaml
or from_json
as appropriate. This may be a bit shaky if you have “interesting” strings in To_be_replaced
– i.e. regex meta-characters.
Here’s a working implementation of the latter method:
---
# brainmue01.yml
- name: Swapping values via map
hosts: localhost
gather_facts: false
vars:
Starting_situation:
- Level: x00
Part1:
- Part1-A
Part2: true
Part3:
- A: Info
B: 20%
C: false
- Level: y00
Part1:
- Part1-B
- Part1-C
Part2: true
Part3:
- A: Info
B: 43%
C: true
To_be_replaced:
Part1-A: AAA1234
Part1-B: BBB4321
Part1-C: CBA9876
tasks:
- name: Overwrite Starting_situation variable with a fact
ansible.builtin.set_fact:
Starting_situation: '{{ Starting_situation | to_json | regex_replace("\b" ~ item ~ "\b", To_be_replaced[item]) }}'
loop: '{{ To_be_replaced.keys() }}'
- name: Show the resulting fact
ansible.builtin.debug:
msg: '{{ Starting_situation }}'