Search code examples
textansible

Ansible insert line after match


I'm trying to insert a line in a file after it matched the regex for the last time. It's actually adding the line but at the end of the file.

  tasks:
  - name: add to ansible hosts file
    lineinfile:
      dest: "hosts"
      insertafter: '^\[ansible_ssh_host\]'
      line: " test ansible_ssh_host=172.0.0.3"

I want it to be added after the last line containing "ansible_ssh_host"

Destination file

ansible-server ansible_ssh_host=172.0.0.1
template-server ansible_ssh_host=172.0.0.2

[tag_ansible-servers]
ansible-server

[tag_template-servers]
template-server   

Solution

  • '^\[ansible_ssh_host\]' means search for a line that begins with [ansible_ssh_hosts], but none of your lines actually start with that. You need a regexp which matches anywhere in the line.

    Try this:

    - name: add to ansible hosts file
      lineinfile:
        dest: "hosts"
        insertafter: 'ansible_ssh_host='
        line: " test ansible_ssh_host=172.0.0.3"