Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Created March 22, 2012 16:26
Show Gist options
  • Select an option

  • Save kwilczynski/2159360 to your computer and use it in GitHub Desktop.

Select an option

Save kwilczynski/2159360 to your computer and use it in GitHub Desktop.
Random cron job minutes
module Puppet::Parser::Functions
newfunction(:random_crontab_minutes, :type => :rvalue) do |*arguments|
#
# This is to ensure that whenever we call this function from within
# the Puppet manifest or alternatively form a template it will always
# do the right thing ...
#
arguments = arguments.shift if arguments.first.is_a?(Array)
raise Puppet::ParseError, "random_crontab_minutes(): Wrong number " +
"of arguments given (#{arguments.size} for 2)" if arguments.size < 2
job_name = arguments.shift
raise Puppet::ParseError, 'random_crontab_minutes(): First argument ' +
'requires a string type to work with' unless job_name.is_a?(String)
host = arguments.shift
raise Puppet::ParseError, 'random_crontab_minutes(): Second argument ' +
'requires a string type to work with' unless host.is_a?(String)
# This is probably impossible as Digest is part of the Ruby Core ...
begin
require 'digest/sha1'
rescue LoadError
raise Puppet::ParseError, 'random_crontab_minutes(): Unable to ' +
'load Digest::SHA1 library.'
end
#
# Pick a random number based on the job and host name. This will yield
# the same value for exactly the same combination of the job and host name.
#
sha1 = Digest::SHA1.new
value = sha1.hexdigest(job_name + host).hex % 60
# Minutes are from 0 to 59 inclusive ...
value < 60 ? value : 59
end
end
# vim: set ts=2 sw=2 et :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment