# add 2 lines with lineinfile but only if not already there

**URL:** <https://forum.ansible.com/t/add-2-lines-with-lineinfile-but-only-if-not-already-there/17836>\
**Category:** Ansible Project\
**Created:** [March 25, 2015, 2:14pm UTC](https://forum.ansible.com/t/add-2-lines-with-lineinfile-but-only-if-not-already-there/17836 "2015-03-25T14:14:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Cevyn\_E](https://avatars.discourse-cdn.com/v4/letter/c/e480ec/32.png) [@Cevyn\_E](https://forum.ansible.com/u/Cevyn_E)\
**Post date:** [March 25, 2015, 2:14pm UTC](https://forum.ansible.com/t/add-2-lines-with-lineinfile-but-only-if-not-already-there/17836/1 "2015-03-25T14:14:29Z")

</div>

I’m new to Ansible and learning a lot but I have a stupid question. I just can not quite see the answer.  
I have a file

aaa  
bbb  
ccc

I want to add  
ddd  
eee

but only if it does not already exist. So I can rerun playbook without creating dups.

I’ve tried register and when.  
I have tried using backrefs=yes

It is just slipping though my fingers. I’m sure this is child’s play for many of you . Please instruct…

---

<div class="post-metadata">

**Author:** ![J-P\_Methot](https://avatars.discourse-cdn.com/v4/letter/j/848f3c/32.png) [@J-P\_Methot](https://forum.ansible.com/u/J-P_Methot)\
**Post date:** [March 25, 2015, 4:54pm UTC](https://forum.ansible.com/t/add-2-lines-with-lineinfile-but-only-if-not-already-there/17836/2 "2015-03-25T16:54:55Z")

</div>

You would need to use regexp. So, if you are trying to write ddd, the defined regexp would be :

regexp:‘^ddd’

This way lineinfile will look for a line matching that regexp before writting. If it finds that line, it will get overwritten with the same content. Else, it will be added. state = present also needs to be specified.
