ansiblerhelrhel7

How to truncate an existing and opened file using Ansible?


I like to truncate or resize an already existing file which is opened and used by an other application. In example, the disk may be cluttered with log files taking up large amounts of space over time like /var/log/secure.

In plain Linux the equivalent would be

truncate -s 0 /var/log/secure
dd if=/dev/zero of=/var/log/secure bs=1M count=0
echo > /var/log/secure

according

and via tail -F /var/log/secure each would result into an

==> /var/log/secure <==
tail: /var/log/secure: file truncated
tail: /var/log/secure: file truncated
tail: /var/log/secure: file truncated

instead of

==> /var/log/secure <==
tail: ‘/var/log/secure’ has been replaced;  following end of new file

After some testing it seems that all in Ansible v2.9 available modules (file, lineinfile, copy, etc.) replace the existing file with a new empty one, but not truncating or resizing and resulting into the already mentioned

==> /var/log/secure <==
tail: ‘/var/log/secure’ has been replaced;  following end of new file

I am aware that rotating, compressing and removing logs files with via logrotate might be a better solution.


Solution

  • It seems that Ansible Issue #902 wasn't implemented in that way.

    However, as of Ansible v3.0.0, with filesize_module, a simple wrapper around dd to create, extend or truncate a file, given its size, was introduced.

    It can be used to manage swap files (that require contiguous blocks) or alternatively, huge sparse files.

    See filesize.py under /ansible-collections/community.general/blob/main/plugins/modules/ for more information.