Ansible Automation: Manage CRON Jobs via Ansible (Step By Step)
In many UNIX/LINUX type operating systems, the Cron is one of the very valuable and productive utility. It is used to run commands and scripts at pre-defined time.
These pre-scheduled jobs are called ‘cron jobs’.
Run the follwoing command at linux shell prompt:
Following is the syntax of cron job entry in the crontab file:
10 0 * * * /path/command
30 15 5 * * /path/myscript.sh
0 18 * * 1-3 /path/myscript.sh
The Ansible cron module is used to manage the crontab entries via play books. Consider, If you have many servers and you want to configure some common cron jobs on all servers, then configuring the same job manually on all servers will be tedious and error-prone task. Ansible can do this job via a simple playbook to configure the said cron jobs on all servers automatically (in one go).
1- One Ansible Control Node
2- Two Ansible managed hosts (You may use as many as you want)
3- Network access between control node and managed nodes
4- Host names of all three nodes should be registered with DNS server or appropriate entries should be present in the /etc/hosts files (on all three nodes).
5- User SSH keys should have already been generated at control node and shared with managed nodes (see this article to configure SSH Keys: http://tiny.cc/ro75fz
Note: In this article, we have used one user “fakhar” on all three nodes. Its SSH keys have been generated at control node and shared on both managed hosts.
Step-1: Create an inventory file at control node (i.e. CentOS-Ctrl-Node), containing the host names of both managed servers, as shown in below image:
Step-2: Create an ansible playbook, to schedule cron jobs as shown below:
Step-3 (Optional): Run the ‘tree’ command at control node, where your playbook is placed (this is just to show you as how the files are placed/organized). See image below:
Step-4: Run the ‘crontab -l’ and ‘ls -l /home/fakhar/temp.txt’ on both managed hosts to confirm the status before the execution of playbook. See image below:
Step-5: Run the playbook using command ‘ansible-playbook -i inventory cronPlayBook.yml’ at control node. See image below. The playbook has been executed successfully.
Step-6: Check the result on the target managed hosts after the cron job scheduled time. For this purpose, run the ‘crontab -l’ and ‘ls -l /home/fakhar/temp/txt’ commands on both managed hosts. See image below, the cron job entries have been created and executed at specified time. The cron jobs have collected the system information and placed it in the target file (i.e. /home/fakhar/temp.txt) successfully.