Reputation: 625
I was adding few elements to an array, which is fetched from a file The file contents are like
#shipping.yml
shipping.enabled: true
shipping.method: "postal"
country.states.availability: ["ST1", "ST2", "ST3"]
I'm trying to extract country.states.available
from the file and add entries from another list to have more states and update the file back with new list
my playbook is something like
- include_vars:
file: shipping.yml
name: shipping_var
- set_fact:
shipping_var['country.states.availability']: "shipping_var['country.states.availability'] + ['{{ item }}'] "
loop: "{{ lookup ('file', 'new_state_list_per_line').splitlines()}}"
# And then I've to update the filename back to have the list with new states.availability
But getting error:
The variable name 'shipping_var['country.states.availability']' is not valid.
Variables must start with letter or underscore and contain only letters, numbers, underscore
Any chance on how to update a variable with dot in the key-name?
Upvotes: 2
Views: 1689
Reputation: 44789
You cannot use set_fact
to update directly a nested element. You have to use the top level element and work your way around. Note that your loop is not needed since you get a list you can directly concatenate to the existing one.
In your current situation you can fix the issue with the following. I broke the vars in different pieces in the task to have a readable final expression. I also added the unique
and sort
filter so that you produce the same result each time, even when running the task on an already updated file.
- name: update var with new countries
vars:
new_states: "{{ lookup ('file', 'new_state_list_per_line').splitlines()}}"
all_states: "{{ shipping_var['country.states.availability'] + new_states | unique | sort }}"
set_fact:
shipping_var: "{{ shipping_var | combine({'country.states.availability': all_states}) }}"
To push the content back into the original file, you just have to write out the content of the var back to the file in yaml format with the copy
module for example:
- name: Update file with new content if needed
copy:
dest: path/to/shipping.yml
content: "{{ shipping_var | to_yaml }}"
owner: someuser
group: somegroup
mode: 0640
delegate_to: localhost
run_once: true
Upvotes: 1