Lineinfile Module in ansible

Ansible lineinfile module is helpful when we want to add, remove, modify a single line in a file. we can also use conditions to match the line before modifying or removing using regular expressions. we can reuse and modify the matched line using the backreference parameter.

Let's see some examples,
# cat lineinfile.yaml
- hosts: all
  - name: create file
      path: /home/ansible/hostname.conf
      state: touch
  - name: add a line if not present
      path: /home/ansible/hostname.conf
      regexp: '^Hostname'
      line: hostname={{ ansible_hostname }}
      state: present

Lets run playbook,
# ansible-playbook lineinfile.yaml
PLAY [all] **************************************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: []

TASK [create file] ******************************************************************************************************************************************
changed: []

TASK [add a line if not present] ****************************************************************************************************************************

PLAY RECAP **************************************************************************************************************************************************               : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

It is recommended to always have the backup: yes parameter in the playbook when we are using the lineinfile. This would make sure the file is backed up before any changes are made. This would help in case if you want to roll back.

Recent Comments

No comments

Leave a Comment