Ansible’s Cron Module for Managing Scheduled Tasks

Ansible's Cron Module for Managing Scheduled Tasks

The Ansible `cron` module is used to manage scheduled tasks (cron jobs) on remote hosts, allowing you to create, modify, and delete scheduled tasks to ensure specified tasks are executed automatically at designated times.

1. Features of Ansible’s `cron` Module

Manage crontab and environment variable entries: You can create environment variables and named crontab entries, as well as update or delete them.

Support for special time specifications: Such as `@reboot`, `@daily`, etc.

Backup functionality: You can create backups before modifying or deleting crontab entries.

2. Parameters

`name` | The name of the task, used for identification and management. `minute`, `hour`, `day`, `month`, `weekday` | Set the execution time of the task. `job` | The command or script to be executed. `state` | Controls the state of the task, `present` indicates the task exists, `absent` indicates the task should be deleted. `user` | Specifies the user under which the task runs. `cron_file` | Specifies the file where the task is stored. `backup` | Whether to create a backup before modifying or deleting the task. `disabled` | Whether to disable the task (comment out the task).

3. Examples

1. Create a task: Execute `/usr/sbin/logrotate` every 15 minutes.

#bash ansible all -m cron -a "name='log rotate' minute='*/15' job='/usr/sbin/logrotate'"

2. Delete a task: Remove the task named “backup script”.

#bash ansible all -m cron -a "name='backup script' state=absent"

3. Create a task to run at 3 AM every Monday.

#bash ansible all -m cron -a "name='weekly cleanup' minute=0 hour=3 day_of_week=1 job='/usr/local/bin/cleanup.sh'"

4. Create a task and specify the user: Create the task as the `root` user.

#bash ansible all -m cron -a "name='check disk' minute=0 hour=1 user=root job='/usr/local/bin/check_disk.sh'"

Leave a Comment