'Creating crontab task in puppet using a cron expression

I'm trying to create a crontab task using Puppet. Problem is puppet is asking you to set parameters like "hour", "minute", "month", etc, to define at which moment the tasks have to be executed. I can't find a parameter using a cron expression, for example "*/5 * * * *" or "15 6 * * 1". Is there any way to do that?



Solution 1:[1]

Here is what I finally wrote:

#In my parameters, so I can pass the array using Foreman, for example
Array $cron_jobs = [['58 7 * * *', '/eloi/ksh/eloi-batch/scripts/purgeRepertoireLogTrace.ksh >/dev/null 2>&1', 'purgeRepertoireLogTrace'], ['*/5 * * * *',
  '/eloi/ksh/eloi-batch/scripts/replicationReferentielFichier.ksh >/dev/null 2>&1', 'replicationReferentielFichier']],

...

$cron_jobs.each |$cron_job| {
    $cron_expr = split($cron_job[0], ' ')

    cron{ "cron-${cron_job[2]}":
      command     => "${cron_job[1]}",
      minute      => "${cron_expr[0]}",
      hour        => "${cron_expr[1]}",
      monthday    => "${cron_expr[2]}",
      month       => "${cron_expr[3]}",
      weekday     => "${cron_expr[4]}",
      user        => "${appuser[0]}",
      environment => "PATH=/bin:/usr/bin:/usr/sbin",
    }
  }

Using the split function, I'm able to convert the cron expression from the table into a parameters for a Puppet cron resource.

I could put the whole cron string in a single dimension array, but some of my commands contain spaces, so it wouldn't work properly. It also gives me the opportunity to add another field to build the resource name.

Solution 2:[2]

For wildcards (*) you just need to leave the parameter blank, for example, I created;

class scratch::crontest {

  cron { 'logrotate1':
    command => '/usr/sbin/logrotate --version',
    user    => 'root',
    hour    => '*/5',
  }

  cron { 'logrotate2':
    command => '/usr/sbin/logrotate --version',
    user    => 'root',
    hour    => '15',
    minute  => '6',
  }
}

I applied that to a node and that created;

[root] # crontab -l
# HEADER: This file was autogenerated at 2022-04-20 16:53:05 +0000 by puppet.
# HEADER: While it can still be managed manually, it is definitely not recommended.
# HEADER: Note particularly that the comments starting with 'Puppet Name' should
# HEADER: not be deleted, as doing so could cause duplicate cron jobs.
# Puppet Name: logrotate1
* */5 * * * /usr/sbin/logrotate --version
# Puppet Name: logrotate2
6 15 * * * /usr/sbin/logrotate --version

The Puppet documentation on this seems to only exist for a Puppet 5.5 but if you're on a Puppet server or a node with an agent you can run puppet describe cron to see the documentation for your version.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 16c7x