Setting Cron Jobs via Ansible CLI

From bib. source

Periodic tasks run via cron are managed by a system’s crontab. Normally, to change cron job settings on a server, you would log into the server, use crontab -e under the account where the cron jobs reside, and type in an entry with the interval and job.

To use Ansible for managing cron jobs, one can use the cron module (Geerling 2023, 41):

From bib. source

Ansible makes managing cron jobs easy with its cron module. […] add a cron job with:

ansible multi -b -m cron -a “name=’daily-cron-all-servers’ hour=4 job=’/path/to/daily-script.sh’”

Exemplified differently:

ansible $INVENTORY_FILE_GROUP -b -m cron -a "name=${CRON_JOB_NAME} hour=${CRON_JOB_HOUR_INTERVAL} job=${SCRIPT_FILEPATH}"

For all unspecified interval values, Ansible will assume a wildcard by default for that interval (represented by an asterisk, “*”) (Ibid). Special time values–such as event-based ones–available to the crontab can also be specified instead (Ibid).

Most importantly, one “can also set the user the job will run under via user=[user]” as well as “create a backup of the current crontab by passing backup=yes” (Ibid).

To remove a cron job, use state=absent in option a for this cron module while specifying an extant cron job name (Geerling 2023, 40-41):

ansible $INVENTORY_FILE_GROUP -b -m cron -a "name=${EXTANT_CRON_JOB_NAME} state=absent"

More on modules

For background on some of these options, see 20250322150219-Ansible_Modules_via_CLI.

crontab cron_job chronos chronos_table chronos_job configuration_management command_line command_lines command_line_interface command_line_interfaces ad-hoc_command ad-hoc_commands Bourne_Again_Shell bash bash_script bash_scripting Bourne_Again_Shell_script Bourne_Again_Shell_scripting modules


bibliography

  • “Ad-Hoc Commands.” In Ansible for DevOps: Server and Configuration Management for Humans, 2nd ed., 18–46. Leanpub, 2023.