Let’s say you’re a systems engineer in charge of running log cleanups and your organization has ten remote servers. To run this task, you’d usually SSH into all ten servers and manually delete old logs or run a cleanup script.
This method is slow and prone to errors, and there’s always a chance you might miss a server or forget some critical steps. However, there’s a more automated approach: using the cron module in Ansible.
With this module, you’ll define the cleanup task once in your Ansible playbook and schedule it to delete logs older than, say, 30 days every week. Then, with a single command, you can apply it across all your servers, ensuring consistent and error-free execution.
This article introduces you to the Ansible cron module and guides you on how to create a cron job using this tool.
What we’ll cover:
To follow the examples in this article, you’ll need to:
- Ensure Ansible is installed on your local machine or control node.
- Have a foundational understanding of Ansible playbook structure to follow along effectively.
- Access a target server — either a local virtual machine (VM) or a remote server—that Ansible can connect to for executing commands.
The Ansible Cron module manages scheduled tasks, also known as cron jobs, on Linux and Unix-based systems. These tasks are automated processes that run at specific times or intervals, like cleaning up logs, backing up data, or checking system health. The module eliminates the need to manually edit a server’s crontab file, making it easy to create, modify, or remove cron jobs consistently and automatically.
Using the cron module simplifies server management, especially when you’re dealing with multiple servers. Instead of logging into each server and manually setting up the schedule, you define the job once in your Ansible playbook and apply it across all servers with one command. This approach not only saves time but also reduces the chances of errors or missed configurations.
The module is also particularly useful in infrastructure provisioning, where you want to set up routine tasks during server deployment. Whether you’re scheduling maintenance scripts or ensuring periodic updates, the cron module ensures tasks are consistent and repeatable across your environment.
The basic structure of the Ansible cron module
The basic structure of a cron module task in an Ansible playbook follows this format. Below is an example of a cron job that runs a log cleanup script every day at midnight:
- name: Example of a cron job
ansible.builtin.cron:
name: "Cleanup logs"
minute: "0"
hour: "0"
job: "/usr/bin/cleanup_logs.sh"
state: "present"
The above job is named “Cleanup logs” and schedules the execution of the /usr/bin/cleanup_logs.sh
script at exactly midnight every day.
Cron module parameters
The structure above is flexible and lets you specify a wide range of scheduling options and parameters. The following are some parameters commonly used with the cron module:
name
(required): A descriptive name for the cron job. This is essential to identify the job and avoid creating duplicates.backup
(optional): If set to yes, the module creates a backup of the crontab file before making any changes. This is useful for maintaining a history of previous configurations.cron_file
(optional): Specifies the file where the cron job will be written. By default, the job is added to the user’s crontab, but you can use this parameter to write to a custom cron file instead.job
(optional): The actual command or script the cron job should run. This can be anything from running a shell script to executing a command directly.minute
,hour
,day
,month
, andweekday
(optional): These parameters define when the cron job will run. You can specify exact times, use wildcards (*), or set ranges (e.g., 0-59 for minutes).state
(optional): This defines whether the job is added (present) or removed (absent). Use it to clean up old cron jobs that are no longer needed.special_time
(optional): A shortcut to define common scheduling intervals, such as reboot, daily, weekly, or monthly. It simplifies scheduling without needing to manually define the minute, hour, or day values.user
(optional): Specifies the user under which the cron job will run. If not specified, the job runs as the user executing the playbook (usually root).
You can find a complete list of the Ansible cron module parameters on the official Ansible documentation.
In this section, you’ll learn how to create a new cron job using the Ansible cron module. This cron job will run a shell command at a defined interval.
Step 1: Create an Ansible playbook
Start by creating a new Ansible playbook file. Save it as simple_cron_job_playbook.yaml
in your preferred directory, and open it in a text editor.
Add the following content to your playbook:
- hosts: localhost
tasks:
- name: Schedule a simple cron job
ansible.builtin.cron:
name: "Simple Cron Job"
minute: "*/10"
job: "/home/user/cleanup_logs.sh"
Below is a breakdown of the playbook above:
cron
: The Ansible module used to manage cron jobs on the target host.name
: The name of the cron job, which Ansible uses to identify and manage it.minute
: This parameter sets the scheduling interval. The value"*/10"
means the job will run every 10 minutes.job
: Specifies the command or script to be executed. In this case, it’s/home/user/cleanup_logs.sh
, a script located in the/home/user/ directory
.
Step 2: Create the script
Next, create a simple script that the cron job will execute. Save it as cleanup_logs.sh
in the /home/user/
directory.
Use the following content:
#!/bin/bash
echo "Log cleanup initiated at $(date)" >> /home/user/log_cleanup.log
Make sure the script is executable by running the following command:
chmod +x /home/user/cleanup_logs.sh
This script appends a timestamped message to a log file every time it runs, simulating a simple log cleanup operation.
Step 3: Run the playbook
To schedule the cron job, execute the playbook with the following command:
ansible-playbook simple_cron_job_playbook.yaml
When you run the playbook, you should see output similar to this:
This indicates that the cron job has been created successfully.
Step 4: Verify the cron Job
To confirm the cron job has been scheduled, check the crontab on the target system by running:
crontab -l
You should see an output similar to this:
#Ansible: Simple Cron Job
*/10 * * * * /home/user/cleanup_logs.sh
This confirms that the cron job is scheduled to run every ten minutes.
When setting up cron jobs using the Ansible cron module, you might need to specify environment variables to ensure the correct execution of tasks. These variables provide the necessary context, such as file paths, user-specific configurations, or application settings.
The Ansible cron module allows you to manage environment variables within cron jobs. Instead of manually editing the crontab file, you can define the required variables directly in your Ansible playbook.
Add environment variables to a cron job
To include environment variables in a cron job, use the env parameter in your task.
Below is an example playbook:
- hosts: localhost
tasks:
- name: Set PATH environment variable in the crontab
ansible.builtin.cron:
name: "PATH"
env: yes
job: "/usr/local/bin:/usr/bin:/bin"
- name: Set BACKUP_DIR environment variable in the crontab
ansible.builtin.cron:
name: "BACKUP_DIR"
env: yes
job: "/var/backups"
insertafter: "PATH"
- name: Set RETENTION_DAYS environment variable in the crontab
ansible.builtin.cron:
name: "RETENTION_DAYS"
env: yes
job: "30"
insertafter: "BACKUP_DIR"
- name: Set up a backup cron job
ansible.builtin.cron:
name: "Backup Task"
minute: "0"
hour: "2"
job: "/home/user/backup.sh"
The following is a breakdown of the playbook above:
- Each environment variable is added as a separate cron entry with
env: yes
. This sets variables in the crontab file above the actual cron jobs. insertafter
: Ensures that variables are inserted in the correct order by specifying after which entry they should appear.- Cron job: After setting the environment variables, the actual cron job is added to use these settings.
Run the playbook
Execute the playbook to create the cron job with the environment variables:
ansible-playbook backup_cron_with_env.yaml
Verify the cron job
Check the crontab to confirm that the environment variables have been set along with the cron job:
crontab -l
You should see output similar to this:
PATH="/usr/local/bin:/usr/bin:/bin"
BACKUP_DIR="/var/backups"
RETENTION_DAYS= "30"
#Ansible: Backup Task
0 2 * * * /home/user/backup.sh
Disabling a cron job means temporarily stopping it from running without permanently removing it from the crontab. This is useful when you want to pause a scheduled task for debugging, maintenance, or testing purposes but plan to re-enable it later.
The Ansible cron module makes this process straightforward by allowing you to change the job’s state to disabled.
Below is how you can disable a cron job using a playbook:
- hosts: localhost
tasks:
- name: Disable a scheduled backup job
ansible.builtin.cron:
name: "Backup Task"
job: "/home/user/backup.sh"
state: disabled
Below is a breakdown of this playbook:
name
: Identifies the specific cron job you want to disable. This matches the description of the job in the crontab.job
: Specifies the exact command or script associated with the cron job.state: disabled
: Temporarily disables the cron job by commenting it out in the crontab. The job remains listed, but it won’t run.
This job will still be visible after it’s run, but it won’t execute until it’s re-enabled.
If a cron job is no longer needed, you can remove it entirely using the cron module. This is particularly useful for cleaning up outdated jobs or tidying up your server configuration. Unlike disabling a job, removing it permanently deletes the entry from the crontab.
Below is an example playbook used to delete cron jobs:
- hosts: localhost
tasks:
- name: Remove a scheduled backup job
ansible.builtin.cron:
name: "Backup Task"
job: "/home/user/backup.sh"
state: absent
The playbook above does the following:
name
: Identifies the job you want to remove. This ensures only the specified cron job is targeted.job
: Matches the command or script of the job you want to delete.state: absent
: Permanently removes the job from the crontab, leaving no trace of it.
After running this playbook, the cron job will no longer exist in the crontab.
The special_time
parameter simplifies cron job scheduling by using predefined keywords like reboot
, hourly
, daily
, weekly
, monthly
, and yearly
. This is especially useful for tasks that follow standard intervals, like running maintenance scripts or syncing data periodically.
Let’s create a cron job that runs a script every day at a specific time using the special_time
option.
Create a new playbook file called special_time_cron.yaml
and open it in your text editor.
Add the following content:
- hosts: localhost
tasks:
- name: Schedule a daily log rotation task
ansible.builtin.cron:
name: "Daily Log Rotation"
special_time: daily
job: "/usr/bin/logrotate /etc/logrotate.conf"
state: present
This is a breakdown of the playbook above:
special_time: daily
: This sets the job to run daily at the system-defined time (usually midnight).job
: Specifies the command to execute, in this case, running the logrotate tool.state: present
: Ensures the job is created in the crontab.
Run the playbook using the following command:
ansible-playbook special_time_cron.yaml
Your output should look similar to this:
To confirm the cron job was added, check the crontab:
crontab -l
You should get the following output:
#Ansible: Daily Log Rotation
@daily /usr/bin/logrotate /etc/logrotate.conf
This confirms the job will run daily at the predefined system time.
You might need to create a cron job for a specific user, such as scheduling user-specific tasks or running custom scripts under a non-root account. The user
parameter in the cron module makes this easy.
Create a new playbook file called user_specific_cron.yaml
and open it in your text editor.
Add the following content:
- hosts: localhost
become: yes
tasks:
- name: Schedule a backup script for the "webadmin" user
ansible.builtin.cron:
name: "Webadmin Backup"
minute: "30"
hour: "3"
job: "/home/webadmin/scripts/backup.sh"
user: "webadmin"
state: present
The following is a breakdown of the playbook above:
user: webadmin
: Ensures the cron job is added to the webadmin user’s crontab.minute: 30
andhour: 3
: Schedules the job to run at 3:30 AM.job
: Specifies the script to execute, located in the webadmin user’s home directory.state: present
: Ensures the cron job is created.
Run the playbook with the following command:
ansible-playbook user_specific_cron.yaml
Your output should look similar to this:
To confirm the cron job was added for the webadmin user, switch to the user and list their crontab:
sudo crontab -u webadmin -l
You should get the following output:
#Ansible: Webadmin Backup
30 3 * * * /home/webadmin/scripts/backup.sh
This verifies the job is configured under the specified user and will execute as planned.
Spacelift’s vibrant ecosystem and excellent GitOps flow are helpful for managing and orchestrating Ansible. By introducing Spacelift on top of Ansible, you can easily create custom workflows based on pull requests and apply any necessary compliance checks for your organization.
Another advantage of using Spacelift is that you can manage infrastructure tools like Ansible, Terraform, Pulumi, AWS CloudFormation, and even Kubernetes from the same place and combine their stacks with building workflows across tools.
Our latest Ansible enhancements solve three of the biggest challenges engineers face when they are using Ansible:
- Having a centralized place in which you can run your playbooks
- Combining IaC with configuration management to create a single workflow
- Getting insights into what ran and where
Provisioning, configuring, governing, and even orchestrating your containers can be performed with a single workflow, separating the elements into smaller chunks to identify issues more easily.
Would you like to see this in action — or just get a tl;dr? Check out this video showing you Spacelift’s Ansible functionality:
If you want to learn more about using Spacelift with Ansible, check our documentation, read our Ansible guide, or book a demo with one of our engineers.
The Ansible cron module simplifies the management of scheduled tasks across your infrastructure, making it an invaluable tool for automation. In this article, we explored the essentials of using the cron module, from creating simple cron jobs to more advanced scenarios like managing environment variables, disabling or removing tasks, and even scheduling jobs for specific users.
We explained the structure and parameters of the cron module, emphasizing how it helps create consistent, repeatable configurations. From there, we walked through real-world examples — like using the special_time
option and setting up jobs for different users. Each example demonstrated how you can go from defining your playbook to running it and verifying the results.
The cron module should be your go-to solution the next time you need to perform backups, cleanups, or other repetitive tasks.
Manage Ansible Better with Spacelift
Managing large-scale playbook execution is hard. Spacelift enables you to automate Ansible playbook execution with visibility and control over resources, and seamlessly link provisioning and configuration workflows.