Skip to content

Instantly share code, notes, and snippets.

@chadh
Created June 23, 2020 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadh/9fcbd29effd6d1144c3e61f6652bfb6a to your computer and use it in GitHub Desktop.
Save chadh/9fcbd29effd6d1144c3e61f6652bfb6a to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Script to purge /etc/cron.d of stale cron::entry resources.
#
# cron::entry resource filenames begin with "pup_".
#
# shellcheck disable=SC1091
export PATH="/opt/puppetlabs/bin:${PATH}:/usr/local/bin"
# The format/spacing of the report file changed from puppet 3 to 4
if [[ $(puppet --version | cut -d. -f1) -ge 4 ]]; then
spacer="^"
q='.resources[] | select(.type == "Cron::Entry") | select(.parameters.persistent == false) | .title'
else
spacer="^ "
q='.data.resources[] | select(.type == "Cron::Entry") | select(.parameters.persistent == false) | .title'
fi
lastrunreport="$(puppet config print lastrunreport)"
catalog="$(puppet config print client_datadir)/catalog/$(hostname).json"
# if there is no lastrunreport (new install) or if the last run was a failed run, just exit
[[ -r "$lastrunreport" ]] || exit
grep -q "${spacer}status: failed" "$lastrunreport" && exit
# if we get here, it would seem that we successfully downloaded a catalog from the master
# let's pull out the Cron::Entry resources and check them against the ones we currently have
[[ -r "$catalog" ]] || exit
declare -A mycrons
for e in $(jq -r "$q" "$catalog"); do
mycrons[$e]=""
done
if [[ ${#mycrons[@]} -eq 0 ]]; then
logger "purge_cron: Found 0 Cron::Entry resources in catalog. Bailing!!"
exit
fi
for e in /etc/cron.d/pup_*; do
taskname=$(basename "$e" .cron | sed 's/^pup_\(.*\)/\1/')
if [ ! ${mycrons[$taskname]+_} ]; then
logger "purge_cron: removing ${taskname} (${e})"
rm -f "$e"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment