I'm new to Ansible and I need to work with some yaml files. For example. the yaml file I need to edit has the following structure:
Test-ABC:
artifact: Test-ABC
repository:
Test-1:
name: Test123
release: 2024
version: 1.1.0
type: a
Test-2:
name: Test456
release: 2023
version: 2.0.1
type: bs
So what I want to do is first remove all the entries under "repository:". So like this:
Test-ABC:
artifact: Test-ABC
repository:
And then add some new values with input parameters that I defined earlier, e.g.
Test-ABC:
artifact: Test-ABC
repository:
New-Test:
name: newTest123
release: new2024
version: new1.1.0
type: new a
I should also mention that the yaml file has more entries than I've shown you, and they should not be affected by the changes.
I tried regexp and replace, but that just removed the Test-ABC line and so on.
- name: "remove entries"
replace:
path: "file.yaml"
regexp: "^\\s*{{ item.key }}:.*$"
replace: ""
loop: "{{ file['repository'] | dict2items }}"
A minimal example playbook
---
- hosts: localhost
become: false
gather_facts: false
tasks:
- include_vars:
file: some.yml
name: imported
- debug:
msg: "{{ imported['Test-ABC'] }}"
- name: Update the fact
ansible.utils.update_fact:
updates:
- path: "imported['Test-ABC'].repository"
value:
New-Test:
name: newTest123
release: new2024
version: new1.1.0
type: new a
register: updated
- copy:
content: "{{ updated.imported | to_nice_yaml('indent=2') }}"
dest: other.yml
will result into an file content of
Test-ABC:
artifact: Test-ABC
more: entry
not_shown: here
repository:
New-Test:
name: newTest123
release: new2024
type: new a
version: new1.1.0
should: not be affected
Documentation