I am looking for a way to modify a configuration file while preserving local modifications. The format of the configuration file is similar to this:
entry1: This is a local
entry2: modification.
entry3:
The file consists of a variable number of keys (entry1, entry2, entry3, and possibly later entry4, etc. - it could go up to 100, and in the future maybe even up to 2000 or so) that should be set up by Ansible, followed by additional options that another program will add to the configuration file.
I want Ansible to be able to add new keys to the file, while preserving any of the existing local modifications.
The most natural fit seems lineinfile - but unfortunately it only gives me the option of either preserving the local modifications (using backref=yes), or adding new keys (backref=yes will not add new lines).
Is there a good way to accomplish what I need?
I can modify the existing entries with lineinfile and backref enabled:
- lineinfile:
path: myfile.conf
regexp: "^{{ item }}: (.*)"
backref: yes
line: "{{ item }}: \1"
with_items:
- entry1
- entry2
- entry3
- entry4
But this will not add entry4 to my file.
Or I can use backref: no
- lineinfile:
path: myfile.conf
regexp: "^{{ item }}: (.*)"
backref: no
line: "{{ item }}:"
with_items:
- entry1
- entry2
- entry3
- entry4
But this will clobber local modifications for entry1, entry2 and entry3.
Or I could change the regexp:
- lineinfile:
path: myfile.conf
regexp: "^"
backref: no
line: "{{ item }}:"
with_items:
- entry1
- entry2
- entry3
- entry4
But this will of course add each key on every run.
I've also looked at using a template (but have not found an easy way to use it to manipulate an existing file).
Of course I can write my own Python module, but there must be an easier way to do this?