Ansible can be used to remotely configure cron entries or even create a crontab files in managed nodes.
The below example creates a crontab file named “/etc/cron.d/the-date-time” in the managed nodes.
First let us verify if the file already exists in the managed node.
[root@centosMYOBvm ~]# cat /etc/cron.d/the-date-time
cat: /etc/cron.d/the-date-time: No such file or directory
[root@centos9vm ~]# cat create_crontab_file.yml
= ======
– – –
– name: Playbook to create a cron file with a job
hosts: testONE
become: true
tasks:
– name: Task to create a crontab file with entry
ansible.builtin.cron:
name: Add a crontab file
cron_file: the-date-time
minute: “*/1”
hour: “9-16”
weekday: “mon,tue,wed,thu,fri”
job: “ls /var >> /home/user1/the_date_time_cron_job”
user: user1
state: present
==== ==
[root@centos9vm ~]# ansible-navigator run -m stdout create_crontab_file.yml
==== ==
PLAY [Playbook to create a cron file with a job] *******************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.48.129]
TASK [Task to create a crontab file with entry] ********************************
changed: [192.168.48.129]
PLAY RECAP *********************************************************************
192.168.48.129 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
==== ==
Now let us verify the crontab file that got created
[root@centosMYOBvm ~]# cat /etc/cron.d/the-date-time
#Ansible: Add a crontab file
*/1 9-16 * * mon,tue,wed,thu,fri user1 ls /var >> /home/user1/the_date_time_cron_job
==== ==
[root@centosMYOBvm ~]# tail -f /home/user1/the_date_time_cron_job
adm
cache
crash
==== ====
In order to remove a crontab file a task similar to above needs to be written, but with the property status as absent.
name: Add date and time to a file
user: user1
cron_file: the-date-time
state: absent