Ansible Lineinfile Module Failure

---
- name: Lineinfile task
  hosts: all
  become: yes
  tasks:
  - name: Install the latest version of Apache
    yum:
      name: httpd
      state: latest
  - name: start and enable httpd
    ansible.builtin.service:
      name: httpd
      state: started
      enabled: true
  - name: Add a line to a file if the file does not exist, without passing regexp
    ansible.builtin.lineinfile:
      path: /var/www/html/index.html
      line: This is a Nautilus sample file, created using Ansible!
      create: true
      owner: apache
      group: apache
      mode: '0777'
  - name: Add one more line
    ansible.builtin.lineinfile:
      path: /var/www/html/index.html
      line: Welcome to xFusionCorp Industries!
      insertbefore: 'BOF'

Failure msg: - incorrect content found in ‘/var/www/html/index.html’ file on stapp01

In the index.html, I see the file contains 3 lines, with Welcome msg at the top of the file.
What I’m doing wrong here?

Hi @Ranit.Chatterjee

Can you share the lab link for review?

The Topic, Level and the task name.

Level 3, Task 4: ansible lineinfile module

There’s a bit of trick involved in this task!

The index.html is already present on all the target nodes. With your use of first lineinfile module you are appending to the existing file. You need to use the copy module with content and dest attributes to overwrite the existing file.

  - name: Create index.html
    copy:
      content: This is a Nautilus sample file, created using Ansible!
      dest: /var/www/html/index.html
      owner: apache
      group: apache
      mode: '0644'
  - name: Add one more line
    lineinfile:
      path: /var/www/html/index.html
      line: Welcome to Nautilus Group!
      insertbefore: 'BOF'

This should resolve your issue.

Happy learning!!

Also, I’ve reviewed your task. Can you please confirm you are getting my response on the review page as well?