Can anyone help ?
I am trying to add an additional item to a dictionary in yaml using Ansible.
Here is the current file (site_vars.yaml)
test: hello
sites:
- name: site 1
site: www.site1.com
- name: site 2
site: www.site2.com
And I am trying to add
sites:
- name: site 3
site: www.site3.com
So it would become
sites:
- name: site 1
site: www.site1.com
- name: site 2
site: www.site2.com
- name: site 3
site: www.site3.com
Here is what I have for my playbook, but it isn't working.
tasks:
- name: Setup temporary dictionary item to be merged into yaml
ansible.builtin.set_fact:
new_item:
sites:
- name: site 3
site: www.site3.com
delegate_to: localhost
- name: read in the yaml file
ansible.builtin.set_fact:
current_file: "{{ lookup('file', inventory_dir +'/group_vars/all/site_vars.yaml') | from_yaml }}"
- name: Add items to dictionary
set_fact:
current_file: "{{ current_file | default({}) | combine (new_item) }}"
- name: Make new file
copy:
dest: "{{ inventory_dir +'/group_vars/all/vars_new.yaml' }}"
content: "{{ current_file | to_nice_yaml }}"
delegate_to: localhost
What would be ideal is if the token "sites:" doesn't exist then it is created, otherwise it is added to.
Above the "new_item", it just for testing, this will actually come from template. ALthough I thought if I get it working via a standard variable first then the rest would be easy.
I am also writing the contents "copy module" to a new file, this will eventually will override the original file but for the sake of testing - I decided to copy it to a new file.
Maybe I am approaching this the wrong way.
What I end up with my new file is the following, also it loses the white space, although I can live with that.
sites:
- name: site 3
site: www.site3.com
test: hello
Any ideas ?
Thanks in advance.