Search code examples
puppet

How to remove Cron job through puppet


I was wondering if there is any way that i can remove my cron which got created through puppet. It works fine when i add "ensure => absent" to my manifest. But the challenge for me is, I have to wait an hour to run my puppet agent on my clients since agent is configured to run on every hour. Also i have to manually edit each job to add "ensure => absent".

Is there any other way that i can remove the cron than adding `"ensure => absent"` to each cron jobs

for example, how can we remove "job1" from all applied servers without adding "ensure => absent"

    class cron::my_cron
    ( 
    )
    {
      cron::hourly { 'Job1':
        minute      => '0',
        user        => 'root',
        command     => 'cmd',
        environment => [ 'MAILTO=root', 'PATH="/usr/bin:/bin"', ],
      }

      cron::hourly { 'job2':
        minute      => '0,5,10,15,20,25,30,35,40,45,50,55',
        user        => 'root',
        command     => 'cmd',
        environment => [ 'MAILTO=root', 'PATH="/usr/bin:/bin"', ],
      }
    }

Solution

  • Here is the work around I found. On my puppet class I have created an array with all my active crons. Then I will pass those list to my bash script. My bash script will install and execute once puppet agent run on my clients.

    On my bash script i will grep for all my crons which installed via puppet then i loop through each cron job and compare with my active cron array, If it does not match with my active cron list, will execute the rm command to remove the cron entry.

     class cron ( 
            $active_cron=['cron1', 'cron2', 'cron3', 'cron4')
         )
      {
    
           file {
            '/usr/sbin/remove_cron.sh':
              ensure => present,
              mode   => 755,
              owner  => 'root',
              group  => 'root',
              content => template('cron/remove_cron.erb'),
              notify => Exec['remove_cron'],
           }
    
           exec { 'remove_cron':
              command => "/usr/sbin/remove_cron.sh >> /var/log/remove_cron.log",
              path    => '/usr/local/bin/:/bin/:/usr/bin/',
              require => File['/usr/sbin/remove_cron.sh'],
              refreshonly => true,
           }
        }
    

    My Bash script template

        #!/bin/bash
        LIST='<%= @active %>'
        grep -il puppet* /etc/cron.d/* | grep -il puppet* /etc/cron.d/* | awk -F"/" '{print $NF}' |while read CRON
        do
                FOUNDIT=$(echo $LIST |grep "\"$CRON\"" |wc -l)
                if [ $FOUNDIT -eq 0 ]
                then
                        echo "$(date) : Cron $CRON Removed"
                        rm -r /etc/cron.d/$CRON
                fi
        done