Linux – Automatically delete files by writing zeros on Linux

linuxzero-fill

We run thin-provisioned Ubuntu VMs which do a lot of file writes and deletes. Whilst the disk use on the guests increases slowly (net writes – deletes) the size of the virtual disk on the hosts grows much more quickly because the hosts have no way of knowing that many of the blocks are freed-up space.

On a regular basis we take each VM offline and write zeros to the free blocks in the guest filesystem. This allows us to then to shrink the virtual disk on the host.

I was wondering if anybody knows of a utility we can install on the guests which would automatically write zeros every time a file is deleted. If such a utility existed we could then automate the shrinking of the virtual disks on the host without manually writing zeros over deleted files in the guest.

I hope the question is clear and thanks in advance for any help

Best Answer

Use the fstrim command.

I do this for VMs and other thin-provisioned filesystems, ZFS zvols and SSD-based storage with an easy cron script:

#!/bin/bash

for fs in $(lsblk -o MOUNTPOINT,DISC-MAX,FSTYPE | grep -E '^/.* [1-9]+.* ' | awk '{print $1}')
  do fstrim $fs > /dev/null 2>&1
done