I did this a while back, thinking I’d replace it with something more elegant when I have time… honestly, it’s been working so well, I haven’t thought about it again, until you reminded me.
I have a script saved in my ansible git repo: $GIT/ansible/bin/cron_scheduler.sh
#!/bin/bash
PATH=/bin:/usr/bin
helptext() {
echo “Usage: $0 -i ip_address -f frequency” >&2
echo “Example: $0 -i 10.10.5.160 -f 15 # run once every 15 minutes” >&2
exit 1
}
if [ “$#” -ne 4 ] || [ “$1” = “-h” ] || [ “$1” = “–help” ]; then
helptext
fi
while getopts i:f: option
do
case “${option}”
in
i) ip_address=${OPTARG};;
f) frequency=${OPTARG};;
*) helptext;;
esac
done
decimal=$(echo $ip_address | sed ‘s/./+/g’ | bc)
ip_rand=$(expr $decimal % $frequency)
x=$ip_rand
declare -a minutes=$ip_rand
count=0
while [ $x -lt 60 ]
do
next=$(expr “${minutes[$count]}” + $frequency)
if [ $next -lt 60 ] ; then
minutes=(“${minutes[@]}” “$next”)
fi
(( count++ ))
x=$next
done
echo -n ${minutes[@]} | tr " " ,
So running this:
cron_scheduler.sh -i 10.10.5.160 -f 15
results in this output:
5,20,35,50
(every 15 minutes)
So just decide how frequently you want to schedule the task, and pass in the IP address. voila.
-
name: pick a minute to run example
script: bin/cron_scheduler.sh -i {{ ansible_default_ipv4.address }} -f 10
register: cron_minutes
-
name: configure example
template: src=example/example.cron dest=/etc/cron.d/example.cron owner=root group=root mode=0644
and the template would have something like this:
{{cron_minutes.stdout}} * * * * root /usr/local/bin/example