Ansible Jinja2 template to replace only a few lines for a configuration file? (Jinja2 template doesn't cover the whole content of the target file)

Viewed 816

For example, the configuration file is as below:

    # debug flags = 0x0000000000000000
    # debug log = /var/log/netdata/debug.log
    # error log = /var/log/netdata/error.log
    # access log = /var/log/netdata/access.log
    # facility log = daemon
    # errors flood protection period = 1200
    # errors to trigger flood protection = 200
    # OOM score = 1000

I know I can make a Jinja file as below to achieve the task easily to define certain parameter as a variable:

    # debug flags = 0x0000000000000000
    # debug log = /var/log/netdata/debug.log
    # error log = /var/log/netdata/error.log
    # access log = /var/log/netdata/access.log
    # facility log = daemon
    # errors flood protection period = 1200
    # errors to trigger flood protection = 200
     OOM score = {{ variable }}

but if the base file itself is not totally definitive, where some of the other portion of the text may change over time(we don't wish to freeze the change due to Ansible/Jinja2 to make it static), so can I just define a Jinja2 template file only with the lines I care about, logic may like this:

  1. ignoring the lines which is not matched with OOM score =
  2. if the line matches OOM score =, change the line to OOM score = {{ variable }} with variable to substitute of course.
#jinja template
#ignore lines if it's not matched
     OOM score = {{ variable }}

I know the above case can be easily achieved by lineinfile, but let's say many lines need to do the same(not a block, scattered in a text file), is there a way to achieve by template/Jinja2 instead of lineinfile with loops?

1 Answers

Q: "Is there a way to achieve by template/Jinja2 to replace only a few lines for a configuration file instead of lineinfile with loops?"

A: No. Modul template creates a temporary file from the template first. Then compares this temporary file with the current file, if any, and writes the file, if the files are different.

What you are looking for is to take the current file and create a template by adding lines which is defacto the functionality of the lineinfile module.

Related