How to add new line in ansible playbook

ansibleansible-playbook

I am trying to add new line in yaml configuration file through ansible playbook using lineinfile. What I have tried till now.

#attempt-1
- name: "Configure Node River"
 lineinfile: "dest=/path/to/config.conf line='node.river: river_name'"
#attempt-2
- name: "Configure Node River"
 lineinfile: "dest=/path/to/config.conf state=present regexp='^' line='node.river: river_name'"

Also I have tried as per reference document.

# Add a line to a file if it does not exist, without passing regexp
- lineinfile: dest=/tmp/testfile line="192.168.1.99 foo.lab.net foo"

Can anyone guide me how to add new line which is not present in file. I know I can add End of the File by adding regexp='' insertafter=EOF in my #attempt-1. But I want to add above line in middle of the file.

Best Answer

As I understand you can use insertafter=<regexp>:

--- play.yml
- hosts: localhost                                                              
  gather_facts: False                                                           
  tasks:                                                                        
    - name: "Configure Node River"                                            
      local_action: 'lineinfile dest=/home/ig/test.conf
                     line="node.river: river_name" insertafter="first line"'

test.conf before:

first line
second line

test conf after:

first line
node.river: river_name
second line
Related Topic