lineinfile module to replace a string

Hi,

I am trying to replace a line/string in a 224 lines file .
Trying with replace and lineinfile module , but seems i am missing a bit…

below is the string to consider:

logging.files:

Configure the path where the logs are written. The default is the logs directory

under the home path (the binary location).

path: /var/log/original

.
Here I want to replace the " /var/log/original" to " /var/log/newfile" and I have to search based on the string “logging.files:” which is 3 lines above.

- name: Configuring the inputs for the file
replace:
path: /etc/myagent/myfile
after: ‘logging.files:’ here i want to search 4th line below the match… similar to grep -A3)
regexp: ’ path: /var/log/original ’
replace: " path: /var/log/newfile "

I have multiple lines with similar entries and I cannot replace directly (based on first match too)

What kind of file is this?
It looks like yaml?

Yes… It’s basically another yaml file.

I’m asking because string manipulation of otherwise structured data will become messy quickly - as you have found out.
If you must keep all the comments then you’ll have to use logic to handle that.
Whenever someone edits the file, or by some software update, your logic might break.
I would either template the entire thing out, based on a config that you have in your ansible code.
Or, use a combination of slurp and write out the structure. This will remove any comments, but one could argue that that is not required anyway.
For example:

vars:
filename: /etc/myagent/myfile
config_opts:
logging.files:
path: /var/log/newfile

tasks:

  • slurp:
    src: “{{ filename }}”
    register: foo

  • set_fact:
    foo: “{{ foo.content | b64decode | from_yaml | combine(config_opts) }}”

  • copy:
    content: “{{ foo | to_nice_yaml }}”
    dest: “{{ filename }}”

Thanks . It worked as expected