Basically, I have a text file that includes interface information (i.e interface gigabit0/1/2, interface gigabit0/2/3). I need to add an additional block after each interface command. It has to look as below:-

interface gigabit0/1/2
shutdown
!
interface gigabit0/2/3
shutdown
!

I have used an already existing "lineinfile" module to match the regex and add a new line once matched.

---
- hosts: localhost
  tasks:
    - name: Ansible insert
      lineinfile:
        path: ./ha.txt
        line: |
              shutdown
              !
        insertafter: interface?\s[a-z]\w*/[0-9]/[0-9]
        state: present
      with_lines: cat ha.txt

1 Answers

0
Vladimir Botka On Best Solutions

Use replace. The play below

tasks:
  - replace:
      path: ha.txt
      regexp: '(interface?\s[a-z]\w*/[0-9]/[0-9])'
      replace: |-
               \1
               shutdown
               !

with the file

> cat ha.txt
interface gigabit0/1/2
interface gigabit0/2/3

gives:

> cat ha.txt
interface gigabit0/1/2
shutdown
!
interface gigabit0/2/3
shutdown
!