Ansible lineinfile insertafter injects line at end of file
I'm using lineinfile as follows: lineinfile dest=./hosts_exp insertafter='\[hosts1\]' line="xxxxxxxxx" state=present My hosts_exp is as follows: [local] localhost [hosts1] [hosts2] [hosts3] lineinfile inserts the text after [hosts3] instead of inserting it after [hosts1]. use: lineinfile: dest: "./hosts_exp" line: "xxxxxxxxx" insertafter: '^\[hosts1\]' state: present example: - name: "blah" lineinfile: dest: "/test.sh" insertafter: 'test text' line: "text add" state: present tedder42 It appears redundant, but you need to specify the regex too: lineinfile: dest: ./hosts_exp insertafter: '\