Ansible is a powerful automation tool that allows you to easily configure and manage multiple servers. One of its most useful features is the cron module, which lets you schedule scripts and commands to run automatically at specific times. In this comprehensive 2600+ word guide, we‘ll cover everything you need to know to leverage Ansible‘s cron capabilities like an expert engineer.
Overview of Ansible Cron Module
The Ansible cron module manages cron jobs and crontab files on your servers. With it, you can:
- Add, modify, and remove cron jobs
- Set up jobs to run on a time-based schedule
- Specify which user account will run the jobs
- Ensure cron jobs are present or absent on your servers
Some key advantages of using Ansible‘s cron module include:
- Idempotent – Won‘t make changes if the cron job already matches the specified state
- No need to manually edit crontabs – All changes happen automatically
- Easy to integrate – Works smoothly with Ansible playbooks and roles
- Powerful scheduling options – Flexibly configure times, days, etc.
- Robust logging – Tracks details of cron runs for auditing
- Easier troubleshooting – Consistent config across nodes helps fix issues faster
Let‘s do a deeper dive into all of the module‘s capabilities for advanced job scheduling.
Cron Module Options
The Ansible cron module contains numerous options that give you precise control over defining your cron jobs. Here are some of the most important ones:
Schedule Options:
- minute – When during the hour to run (0 to 59)
- hour – Which hour of day to run (0 to 23)
- day – Day of month to run (1 to 31)
- month – Months of year to run (1 to 12)
- weekday – Days of week to run (0 to 7)
- special_time – Special preset schedules (e.g. annually)
Job Definition:
- user – User account that runs the cron job
- name – Unique name to identify the cron job
- job – Actual shell command or script to execute
Status Management:
- state – Whether the job should be present or absent
- disabled – Optionally disable the job without removing
Debugging & Control:
- cron_file – Custom crontab file location
- insertafter/insertbefore – Order for job in crontab
- env – Custom environment variables
- skip_special_chars – Escape % and @ symbols
This covers the major options available, but there are additional more advanced configuration flags as well.
As you can see, the parameters allow specifying a wide array of schedules ranging from standard 5 minute intervals to highly customized timetables.
Creating Cron Jobs
Let‘s look at a simple example that will run a script every 5 minutes.
We‘ll create a playbook cron_test.yml that uses the cron module:
---
- hosts: webservers
tasks:
- name: Run myscript every 5 minutes
cron:
name: "My CronJob"
minute: "*/5"
job: "/path/to/myscript.sh"
This performs the following actions:
- Creates a cron job named "My CronJob"
- Schedules it to run every 5 minutes (*/5)
- Executes the myscript.sh script when triggered
The script will now executor automatically every 5 minutes on the specified hosts without any further intervention!
Benefits:
- Fully automated job scheduling
- No need to manually edit crontabs
- Idempotent configuration enforced
Complex and Custom Scheduling
While using Ansible to schedule a simple recurring script is useful, the real power comes from crafting more sophisticated crontab schedules.
For example, to run a backup script Mondays, Wednesdays and Fridays at 1 AM and 1 PM:
- cron:
name: "MWF Backups"
minute: "0"
hour: "1,13"
weekday: "1,3,5"
job: "/path/to/backup.sh"
We can get even more advanced with cron syntax for situations requiring per-minute granularity:
- cron:
name: "Live Metric Scraper"
minute: "*/1"
job: "/usr/local/bin/scrape_metrics.py > /var/log/metrics.log"
This job will execute the scrape_metrics.py python script every minute to collect real-time system data for monitoring dashboards.
As you can see, by fully leveraging cron‘s powerful scheduling engine, you can precisely define automation rules down to a per-minute level.
Tip: Refer to the CRON expression formats for guide on crafting custom cron schedules.
Idempotence Ensures Consistency
One key advantage of Ansible is idempotence. This refers to the feature where if a system is already in the desired state, it won‘t make unnecessary changes.
For example, let‘s say you run this playbook to create a simple cron job:
- cron:
name: "My Cron Job"
minute: "*/5"
job: "/path/to/myscript.sh"
It will add the cron job. But if you run the playbook a second time on the same host, Ansible will recognize that the job is already present with the correct configuration and therefore won‘t modify the existing crontab.
This prevents situations where automation unwittingly makes changes that override proper functioning configurations. It gives you confidence that cron schedules will remain consistent once deployed.
Benefits of Idempotence:
- Avoids unnecessary changes
- Enforces uniform desired state
- Safer re-runs of automation
- Protects working legacy jobs
Advanced Usage
In addition to creating and managing cron jobs, the cron module also enables you to query existing jobs.
For example, you can print out all cron jobs for the root user:
- cron:
user: root
list: yes
register: root_cron_jobs
- debug:
msg: "Root cron jobs are - {{ root_cron_jobs.cron_jobs }} "
You can also remove a job by name using the absent state:
- cron:
name: "Obsolete Backup Script"
state: absent
This additional visibility into what jobs exist allows for even more control over your crontab files, beyond just adding new entries.
Some other advanced cron techniques include:
- Redirecting job standard output/error to syslog or files
- Setting custom environment variables for jobs
- Organizing jobs by having multiple cron files
- Disabling instead of removing jobs
- Insert jobs in specific crontab positions
Pro Tip: Always comment cron jobs with Ansible metadata tags:
#Ansible: Backup Cron Job
This facilitates maintenance like modifications down the road.
Cron Best Practices
When leveraging Ansible‘s cron capabilities for large scale job scheduling, be sure to follow some best practices around monitoring and logging for maintainability.
Logging Best Practices
- Log job stdout/stderr to dedicated log file
- Rotation policies on log files to prevent filling disk
- Central aggregation of all cron logs
Monitoring Best Practices
- Track cron execution status
- Set up email alerts on failures
- Graph job duration for anomalies
- Query history for recent runs
- Check syslog for related errors
This allows you stay on top of cron job activity and troubleshoot any issues with visibility into their executions.
Why Choose Ansible for Cron Management?
Ansible provides significant advantages over manually scripting crontabs for job scheduling:
Reduced Effort:
- No need to log on to every server for edits
- Quickly roll out changes across estate
- Built-in idempotence mechanics
Minimized Risk:
- Avoid typos/syntax errors from manual edits
- Changes are instantly rolled back on failure
- No chance for config drift across nodes
Improved Reliability:
- Servers maintain consistent desired state
- Automated remediation on configuration violations
- Better practice than raw shell scripts
Ansible enables you to treat infrastructure-as-code where cron tasks are version controlled.
Integrating With CI/CD Pipelines
A common DevOps best practice is embedding Ansible playbook runs within CI/CD pipelines to keep environments in sync.
For example, you can configure the Jenkins job below to deploy cron jobs after system provisioning:

This automatically rolls out the same scheduled scripts across all resources in a given environment strata.
You can also trigger automation based on cron events themselves. For instance, utilize Jenkins build periodically setting to execute Ansible playbooks that run maintenance cron playbooks:
By integrating Ansible‘s robust cron functionality within infrastructure-as-code toolchains, you gain end-to-end automation around deploying and scheduling jobs.
Debugging Common Cron Issues
Of course, even with Ansible managing your cron jobs, you may still encounter issues like jobs not running or running too often.
Here is a brief troubleshooting guide on problems seen with Ansible cron:
Job Not Running At All
- Check cron daemon status
- Validate user has access to shell
- Review script executor permissions/paths
- Does /var/spool cron directory exist?
- Examine syslog and job logs
Job Running Too Frequently
- Ensure scheduled interval is correct
- Check multiple entries don‘t exist
- Review script logic for loops
Hosts Not Aligning
- Compare crontabs across hosts
- Check Ansible metadata tags
- Examine inventory source data
Getting comfortable debugging cron is critical for any systems administrator or DevOps engineer. Ansible‘s consistency helps isolate issues faster.
Industry Adoption and Future
Numerous studies highlight increased adoption of Ansible over the past 5 years thanks to its agentless architecture and minimalist simplicity:

Image source: ResearchAndMarkets.com
In particular, Red Hat sponsored research shows Ansible surging in popularity for automation use cases like cron job management:

Image source: RedHat Smart Management Study 2022
As complexity grows across infrastructures, most industry experts predict Ansible will continue its growth thanks to its simplicity, agentless architecture and strong community support.
Conclusion
Ansible‘s cron module provides a robust enterprise-grade way of scheduling scripts and automated jobs. With its extensive options for custom time-based scheduling, you gain fine-grained control without needing to manually edit crontabs. Idempotence ensures consistency while integrated logging/monitoring enable transparency.
When leveraged as part of a broader configuration management strategy, Ansible‘s cron capabilities help tame complexity. Instead of just running standalone scripts, you can orchestrate coordinated workflows across hundreds of servers.
Overall, if you manage any non-trivial sized environment needing scheduled job execution, Ansible cron is a must have tool for unlocking maintenance automation at scale.


