I want to insert some lines in a file using the blockinfile
module.
The task goes something like this:
name: add some lines
become: true
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With