Automate Cron Jobs with Ansible: Step-by-Step Playbook Guide
Learn how to install Ansible, then create, modify, and delete crontab entries across multiple hosts using Ansible playbooks, with detailed examples of YAML configurations and command-line instructions that illustrate Infrastructure as Code for reliable scheduled task management.
Ansible is a Python‑based automation tool that can configure, deploy software, and orchestrate advanced tasks such as continuous deployment or zero‑downtime rolling upgrades. It can also manage crontab, the Unix utility for scheduling periodic commands.
Why Use Ansible to Manage Crontab
Before Ansible, cron jobs were edited manually with crontab -e, which becomes unmanageable as the number of hosts and scripts grows. Using Ansible embraces the Infrastructure as Code approach, allowing configuration files to define all changes, eliminating manual backups and enabling consistent initialization across systems.
Install Ansible
Ensure Ansible is installed on your control machine. On Ubuntu, run:
sudo apt update
sudo apt install ansibleCreate a Crontab Entry
Write an Ansible playbook that defines the desired cron job. Example crontab.yml:
---
- name: Manage crontab
hosts: your_target_hosts
tasks:
- name: Add crontab entry
cron:
name: "rsync backup"
minute: "0"
hour: "2"
job: "/path/to/your/backup_script.sh"Run the playbook with: ansible-playbook crontab.yml This creates the specified cron entry on the target hosts.
Modify and Delete Crontab Entries
Use the cron module with the state parameter to modify or remove entries. Example playbook:
---
- name: Manage crontab
hosts: your_target_hosts
tasks:
- name: Modify crontab entry
cron:
name: "My cron job"
minute: "30"
hour: "3"
job: "/path/to/your/updated_script.sh"
state: present
- name: Remove crontab entry
cron:
name: "My cron job"
state: absentExecute with ansible-playbook to apply the changes.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
