Answer the question
In order to leave comments, you need to log in
How to append a line to a file once using Ansible?
Given:
File /etc/network/interfaces
Conditions:
The file already contains settings that should not be changed.
Task:
Add the line foo after the line bar to the file, but only once. The second run of the playbook should not add anything. Only one string foo needed
My attempts:
Know how to do it with command module and sed, but looking for a native solution in Ansible
Trying to solve with lineinfile either destroyed the string bar or added foo on every run of ansible-playbook.
Thanks in advance for your valuable advice.
Answer the question
In order to leave comments, you need to log in
Now I tried to add a line to the file using lineinfile and everything works as it should. The row is added and when restarted, there is no re-adding.
Here is an example as described for ansible.
- name: insert line in file
lineinfile: dest=/tmp/ans insertafter="^bar" line="foo"
Make a template for the interfaces file and just use the template module which in your template will replace {{ foo }} with what you need and replace /etc/network/interfaces. Because the result of rendering the template with the same values of foo is the same - you can safely run the playbook any number of times.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question