Create a Simple Cron Job
In this step, you will create a simple cron job using the Ansible Cron module. The cron job will execute a shell command at a specified interval.
First, create a new Ansible playbook file called /home/labex/project/cron_module_playbook.yaml
and open it in a text editor.
Add the following content to the playbook file:
- hosts: localhost
tasks:
- name: Create a simple cron job
cron:
name: my_cron_job
minute: "*/5"
job: /home/labex/project/script.sh
cron
: This is the Ansible module used to manage cron jobs on the target host.
minute
: This sets the scheduling interval for the cron job. In this example, it means "every 5 minutes". The */5
syntax means "every minute divisible by 5".
job
: This specifies the command or script to be executed by the cron job. In this case, it's /home/labex/project/script.sh
, indicating that the script script.sh
located in the /home/labex/project/
directory will be executed by the cron job.
The cron
module in Ansible is used to manage cron jobs on Unix-like systems. It provides a convenient way to automate tasks by scheduling them to run at specific times or intervals. In this configuration, it's used to create a cron job named "my_cron_job" that runs the script /home/labex/project/script.sh
every 5 minutes.
Next, create a simple script file called /home/labex/project/script.sh
with the following content:
#!/bin/bash
echo "This is a simple script."
Then, run the playbook with the following command:
ansible-playbook cron_module_playbook.yaml
Example output:
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'
PLAY [localhost] ***************************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Create a simple cron job] ************************************************
changed: [localhost]
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Finally, verify that the cron job is created by checking the crontab on the target system.
crontab -l
Example output:
#Ansible: my_cron_job
*/5 * * * * /home/labex/project/script.sh