Ansible Lineinfile | Everything
- arjun5792
- Nov 9, 2022
- 2 min read
Let's learn more about Ansible's Lineinfile feature. We at Skynats can take care of your Ansible problems with our Server Management Services.
Lineinfile in Ansible
Ansible's lineinfile module modifies a single line in a file. It is helpful to add a new line, alter or replace an existing one, and delete a line from a file after finding a specific text. We can apply search criteria when working with this module by using a regular expression.
Three topics will be examined in this article, namely:
Inserting a line into a file
Removing a line from a file
Changing a line in a file
Inserting a line into a file
The path of the file that needs to be changed can be specified using the path/dest parameter. And specify the line we need to insert using the line parameter.
In the following example, "Inserting a line in a file" will be added to the file "server.txt." The new line will now have the EOF. If the line already exists, it will not combine. The program is prompted to create a new file if the one requested is missing when the create parameter is set. Present is the default value for the state.
E.g
- hosts: loc
tasks:
- name: Ansible insert lineinfile
lineinfile:
dest: /home/javaTpoint/remote_server.txt
line: Inserting a line in a file.
state: present
create: yes
Removing a line from a file
Either remove that particular line or set the state parameter to Absent. No other place will have the line.
E.g
- hosts: loc
tasks:
- name: Ansible lineinfile remove the line
lineinfile:
dest: /home/javaTpoint/remote_server.txt
line: Removed lines.
state: absent
Changing a line in a file
Along with the state of Present, we must also use the Ansible backrefs and regexp parameters. If no lines are matched by the regexp, the file will not be altered. The last matching line will be replaced if the regexp matches one or more lines. The grouped elements of a regexp are filled in and can be altered.
E.g
In the example below, we are making a line-by-line comment. By putting them inside the parenthesis to "1," the entire line is captured. The line is replaced by '#1' and then what was captured. We can have multiple captures and identify them using "1," "2," "3," etc.
Using Ansible lineinfile backrefs to comment a line
- name: Ansible lineinfile regexp replace the example
lineinfile:
dest: /etc/ansible/ansible.cfg
regexp: '(inventory = /home/fedora/inventory.ini.*)'
line: '#\1'
backrefs: yes
By using lineinfile regexp, the line is uncommented.
- name: Ansible lineinfile backrefs example
lineinfile:
dest: /etc/ansible/ansible.cfg
regexp: '#(inventory = /home/fedora/inventory.ini.*)'
line: '\1'
backrefs: yes
Conclusion
The Lineinfile module in Ansible is briefly described in this article. We also provided instructions on how to use lineinfile to add, delete, and modify text.
댓글