Search code examples
ansiblecron

Ansible Cron special time "You must specify time and date fields or special time." error


I am trying to add a cron job to an ansible playbook. This job takes a long time and I need to run it during normal server off time. The script is as follows:

- name: Set scheduled run
  cron:
    name: "cron run"
    special_time: reboot
    minute: "0"
    hour: "20"
    user: root
    job: "/path/to/script"

This works okay without the special_time: reboot but when that is added i get the following error:

"You must specify time and date fields or special time."

Solution

  • In order to achieve what you are looking for, you need two cron jobs:

    1. The first one will reboot the server at a given time
    2. The second one will be executed at reboot — with the @reboot mechanism of the crontab

    Mind that the side effect of this is that your script will be executed at each reboot of that node, might it be during night, when the first cron reboots the node, or whenever the node reboots.

    This will give this playbook:

    - name: Scheduled reboot
      cron:
        name: "Reboot to launch /path/to/script"
        minute: "0"
        hour: "20"
        user: root
        job: "/sbin/reboot"
    
    - name: Launch script after reboot
      cron:
        name: "Launch /path/to/script after reboot"
        special_time: reboot
        user: root
        job: "/path/to/script"
    

    What you could do to be extra sure that the script is not executed in the middle of the day, though, is to verify the hour at the beginning of it, something like:

    #!/usr/bin/env sh
    
    if [ "$(date +%H)" -lt 20 ]; then
        exit 0
    fi