puppet: Cron 1小时内多次随机执行

1320阅读 0评论2015-09-07 expert1
分类:系统运维

    某些BT的情况下,需要多个agent端1小时内多次执行某个cron(还得随机时刻), 此时puppet的cron这个resource type满足不了我们的需求了。此时解决办法呢?

   写个class, 里面用define, 大致如下:

class cron(arg1,arg2) {
define random_cron( $command) {
   cron { $name:
   command => $command,
   minute => inline_template("<%= (0..59).to_a.sample(4) %>"),  #执行4次, inline_template要用fqdn_rand的话是不对的,它是Puppet的函数,而inline_template里面是Ruby代码,显然不对。这<%= (0..59).to_a.sample(4) %>也没办法被puppet识别,具体原因不清楚,得分析cron这个resource的ruby代码了。

   hour     => $hour,
   ensure => "present",
  }
}

看下这里:

 (0..59).to_a.sample(4)
=> [2, 38, 1, 56]
不知道是否有重复,看下这个:
Array.new(4) { |e| e = rand(0..60)}
=> [4,14,30,4]   #明显有重复了,虽然用了rand函数。

最好自定义一个function, 检测是否重复,在class的define里面
minute  => random_points()

当然也可以在class里面调用generate()来用bash完成,这样对ruby不熟悉也可以轻松完成。

与fqdn_rand不同的是,这里的cron的minute每次都会变化。

要用python的话,

#!/usr/bin/env python
# generate cron job at different points based on $hostname

import sys, socket

if len(sys.argv) != 2 :
        print "not enough arguments ,exit "
        print "#"*40
        print "usage: python %s \"YOUR_CMD\"" % sys.argv[0]
        print "#"*40

        sys.exit()
else :
        cmd = sys.argv[1]

host = socket.gethostname()

time_range =  ",".join( [str((hash(host)%15)+i*15) for i in xrange(4)]) + " *"*4
cron =  "%s %s" %(time_range,cmd)

print cron
'''
try:
    with open("/tmp/%s" %host ,"wb") as f :
        f.writelines(cron)
        f.writelines("\n")   #write/writeline/writelines有区别的。
        f.close()
except Exception,e :

    print "ERROR" ,str(e)
'''


上一篇:Python的lambda函数和kwargs
下一篇:nagios+python检测report是否生成