theharshest
theharshest

Reputation: 7867

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

Upvotes: 8

Views: 32416

Answers (4)

Tayyab Khan
Tayyab Khan

Reputation: 1

Use backrefs: yes

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

This flag changes the operation of the module slightly; insertbefore and insertafter will be ignored, and if the regexp doesn't match anywhere in the file, the file will be left unchanged. If the regexp does match, the last matching line will be replaced by the expanded line parameter.

Upvotes: 0

300D7309EF17
300D7309EF17

Reputation: 24573

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.

Upvotes: 7

fkoessler
fkoessler

Reputation: 7257

use:

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

Upvotes: 7

xsor
xsor

Reputation: 1074

example:

- name: "blah"
  lineinfile:
    dest: "/test.sh"
    insertafter: 'test text'
    line: "text add"
    state: present

Upvotes: 2

Related Questions