Ansible lineinfile insertafter injects line at end of file

23,048

Solution 1

use:

lineinfile:
  dest: "./hosts_exp"
  line: "xxxxxxxxx"
  insertafter: '^\[hosts1\]'
  state: present

Solution 2

It appears redundant, but you need to specify the regex too:

lineinfile:
  dest: ./hosts_exp
  insertafter: '\[hosts1\]'
  regexp: '\[hosts1\]'
  line: "xxxxxxxxx"
  state=present

Why? The regexp says "look for this line". The insertafter says "inject the line here".

I tested this; here's the commit. There are a few minor changes in my commit from the line above, use as necessary.

Solution 3

example:

- name: "blah"
  lineinfile:
    dest: "/test.sh"
    insertafter: 'test text'
    line: "text add"
    state: present
Share:
23,048
theharshest
Author by

theharshest

Machine Learning and Data Mining enthusiast. Interested in Python, C++, Data Structures and Algorithms. Metalhead! SOreadytohelp

Updated on July 09, 2022

Comments

  • theharshest
    theharshest almost 2 years

    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].