pkaramol
pkaramol

Reputation: 19422

Ansible blockinfile module idempotent?

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.

Upvotes: 5

Views: 5383

Answers (2)

Kevin C
Kevin C

Reputation: 5760

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.

Upvotes: 0

techraf
techraf

Reputation: 68629

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.

Upvotes: 13

Related Questions