Ansible blockinfile module idempotent?
Asked Answered
C

2

5

I want to insert some lines in a file using the blockinfile module.

- name: add some lines
  blockinfile:
    dest: /etc/sysctl.conf
    block: |
      mykey1={{ kernvars['my_value1'] }}
      mykey2={{ kernvars['my_value2'] }}
      mykey3={{ kernvars['my_value3'] }}

Is there a way for the module (or a relevant pattern) to check and insert the specific lines only if they are not already there?

Using ansible 2.0.0.2 on Ubuntu 16.04.01.

Capp answered 9/1, 2017 at 13:56 Comment(0)
W
13

Yes. blockinfile module is idempotent by default.

In addition to the content you specify, it adds two lines: at the beginning of the block and at the end of the block. On subsequent runs it checks the content between these two markers and if content had not changed, it returns the "ok" status and does not insert it again.

These lines should be inserted to the configuration file as comments, so depending on the exact configuration file format you are using, you can customise the character used for marking the comment with the marker argument (by default it's #).

If you use multiple blockinfile tasks on the same destination file you should additionally add a unique string to each task (also in the marker argument), so that Ansible can differentiate between them.

Read more about blockinfile in Ansible documenation.

Watereddown answered 9/1, 2017 at 14:0 Comment(2)
Sometimes it's so sad that I can only vote one time for a answer. @Watereddown Thank you very very much for this clear statement which is missing in the doc.Heddi
@Watereddown how can we make blockinfile idempotent when marker: false ?Teshatesla
F
0

To add to discussion, if custom a marker is used, Ansible adds the line for each run, which is undesired.

You should ensure to use marker_end and marker_begin to keep the task idempotent.

- name: blockinfile w begin and end markers
  blockinfile:
    marker_begin: "begin marker"
    marker_end: "end marker"
    dest: /my/file
    block: whatever

The placed markers will automagicly have a "#" at the beginning of the line.

Farver answered 10/8, 2023 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.