Home > OS >  ansible - changing a specific line in configuration file using a jinja template
ansible - changing a specific line in configuration file using a jinja template

Time:09-23

I have an .ini config file that I'd like to template, but I only want to manipulate one or two lines with the jinja2 files.

example config file:

[configuration]
config1 = this_is_fine
config2 = to_be_templated
config3 = to_be_templated
config_4 = this_is_fine

What would be the best way to define a configuration.ini.j2 that would only change

config2 = {{ assigned_value }}
config3 = {{ assigned_value }}

while keeping the formatting and remaining configuration in place when running the playbook?

CodePudding user response:

Q: "Manipulate one or two lines with the Jinja2 files."

A: "One or two lines" means a block. Use blockinfile to manipulate a block in a file. You'll need markers to do this, e.g. given the file

shell> cat conf.ini
[configuration]
config1 = this_is_fine
config2 = to_be_templated
config3 = to_be_templated
config_4 = this_is_fine

the two tasks below put markers around the block starting config2 and ending config3

    - replace:
        path: conf.ini
        regexp: '(config2.*)'
        replace: |-
          {{ '#' }} BEGIN ANSIBLE MANAGED BLOCK c2-3
          \g<1>
    - replace:
        path: conf.ini
        regexp: '(config2.*[\s\S]*?config3.*)'
        replace: |-
          \g<1>
          {{ '#' }} END ANSIBLE MANAGED BLOCK c2-3

gives

shell> cat conf.ini
[configuration]
config1 = this_is_fine
# BEGIN ANSIBLE MANAGED BLOCK c2-3
config2 = to_be_templated
config3 = to_be_templated
# END ANSIBLE MANAGED BLOCK c2-3
config_4 = this_is_fine

These two tasks are not idempotent. Run them only once. Either put them in a separate playbook to set up the project or test the presence of the markers.

Now you can use the template

shell> cat conf.ini.j2
config2 = {{ assigned_value }}
config3 = {{ assigned_value }}

For example, the task below

    - blockinfile:
        path: conf.ini
        marker: '# {mark} ANSIBLE MANAGED BLOCK c2-3'
        block: |
          {{ lookup('template', 'conf.ini.j2') }}
      vars:
        assigned_value: AVALUE

gives

shell> cat conf.ini
[configuration]
config1 = this_is_fine
# BEGIN ANSIBLE MANAGED BLOCK c2-3
config2 = AVALUE
config3 = AVALUE
# END ANSIBLE MANAGED BLOCK c2-3
config_4 = this_is_fine
  • Related