I need to scan /etc/fstab
file for an entry and if it is not present append the contents of another file into /etc/fstab
.
Ansible modules that I've seen do not seem to allow appending a file to another file instead just adding a specific "text" line.
The lineinfile module could be used if your use case is simply checking that a specific line is present.
For example, if you want to make sure that there is a /dev/sdb1
partition defined and that it is mapped to /data
and using the ext4 filesystem then you could use:
lineinfile: dest=/etc/fstab regexp="^/dev/sdb1 " line="/dev/sdb1 /data ext4 defaults 1 2"
If there's no line beginning with /dev/sdb1
then it will add it to the end of the file. Helpfully, if the rest of the line doesn't match (for example if it's mounted as ext3
) then it will change it to the provided line.
If you really need it to be using the entire contents of a file then you might be able to get away with using the file lookup which might look something like:
lineinfile: dest=/etc/fstab regexp="^/dev/sdb1 " line="{{ lookup('file', 'files/fstabdata') }}"
I've not tested that though.
If your use case is around mounting disks then you might instead consider using the mount module which will handle things even nicer.
If you're really stuck then you can always shell out with something like:
-name: Check for line in /etc/fstab
command: grep /dev/sdb1
changed_when: False
register: shell_out
-name: Append to /etc/fstab
command: cat /home/ansible/files/fstabdata >> /etc/fstab
when: shell_out.std_out != ''
But in general with Ansible you should always look to use the modules provided before resorting to shelling out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With