Problem
You would like to automatically delete old releases from your rails app server using a puppet crontab resource.
Solution
Add the following to your modules/crontab/manifests/init.pp file and modify some of the values to what you need:
# use // to suppress warning: Warning: Unrecognised escape sequence '\;' cron { remove_old_releases: command => "test $(find /var/www/your/path/to/ror/app/ -maxdepth 1 -type d | wc -l) -gt 10 && find /var/www/your/path/to/ror/app/ -maxdepth 1 -type d -mtime +14 -exec rm -rf '{}' \\;", user => ubuntu, hour => 0, minute => 15 }
You should need to change the following:
/var/www/your/path/to/ror/app/ to your application’s release path
-gt 10 this is the number of minimum old releases you want to keep
-mtime +14 releases older than 14 days are deleted
UPDATE
There is chance that when you do not calculate the frequency of the releases right the above script can potentially delete all of your releases, so you end up with no releases 🙁
A better solution to keep the -n number of releases (based on the solution from here:
find /var/www/your/path/to/ror/app/* -type d -printf '%T@ %p\n' | sort -nr | tail -n+6 | cut -f 2- -d " " | xargs -i rm -rf {}
and the explanation of each step:
- find /var/www/your/path/to/ror/app/* -maxdepth 0 -type d -printf ‘%T@ %p\n’ find all the directories (-maxdepth 0 -type d) in the search path (/var/www/your/path/to/ror/app/*) excluding the . and .. directories (/*) and add to them the time information (‘%T %p\n’)
- sort -nr sort them in numeric and reverse order – newer first, oldest last
- tail -n+6 keep only the first 5 directories, starting from line 6 (tail -n+6)
- cut -f 2- -d ” “ Remove the first field (ie the date information) keeping the file from the second field using the space as the delimiter (-d ” “)
- xargs -i rm -rf {} Pass the rm -rf command to delete the directory for each line produced in the previous steps
So the puppet script should be as follows (including the escape characters \ for the % and the additional \):
# use // to suppress warning: Warning: Unrecognised escape sequence '\;' cron { remove_old_releases: command => "find /var/www/your/path/to/ror/app/* -maxdepth 0 -type d -printf '\\%T@ \\%p\\n' | sort -nr | tail -n+6 | cut -f 2- -d ' ' | xargs -i rm -rf '{}' \\;", user => ubuntu, hour => 0, minute => 15 }