Ansible: Find files newer than another
I needed to figure out a way of identifying files newer than another one in Ansible. Here's an outline of the solution I came up with.
First we need to create a bunch of directories and folder, with modified mtime values, that we can work with.
Let's check the mtime value on our files...
stat -x dir2/*.txt | egrep 'File:|Modify:'
File: "dir2/file1.txt" Modify: Mon Jun 18 13:29:00 2018 File: "dir2/file2.txt" Modify: Tue Jun 19 13:29:00 2018 File: "dir2/file3.txt" Modify: Wed Jun 20 13:29:00 2018 File: "dir2/file4.txt" Modify: Thu Jun 21 13:29:00 2018 File: "dir2/file5.txt" Modify: Fri Jun 22 13:29:00 2018 File: "dir2/file6.txt" Modify: Sat Jun 23 13:29:00 2018 File: "dir2/file7.txt" Modify: Sun Jun 24 13:29:00 2018 File: "dir2/file8.txt" Modify: Mon Jun 25 13:29:33 2018
If we want to return files in dir2 than are newer than dir1, which has an mtime of Fri Jun 22 13:29:00 2018, then we would expect to return file6.txt, file7.txt and file8.txt. Here's the playbook that will do just that;
Not the myage variable above has a minus in front of it. This is makes it return files newer than this ‘age’. The documentation page for the find module described the age parameter as follows;
“Select files whose age is equal to or greater than the specified time. Use a negative age to find files equal to or less than the specified time. You can choose seconds, minutes, hours, days, or weeks by specifying the first letter of any of those words (e.g., “1w”).”
I found this explanation to be a little confusing with the mixed up semantics between age and time. Basically specifying a value of ‘1d’ would return all files older than 1 day, while ‘-1d’ would return all files less than a day old.