I'm going to show you a live Playbook and some simple Ansible code.
I'm Luca Berton and welcome to today's episode of Ansible Pilot.
Ansible schedule a Cron Job task in Linux
- ansible.builtin.cron
- Manage cron.d and crontab entries
Today we're talking about Ansible module cron.
The full name is ansible.builtin.cron, which means that is part of the collection of modules "builtin" with ansible and shipped with it.
It's a module pretty stable and out for years and it works in a different variety of operating systems.
It manages cron.d and crontab entries.
For Windows targets, use the ansible.windows.win_scheduled_task module instead.
Parameters
- name string - crontab name
- state string - present/absent
- job string - command to execute
- user string - defaults to the current user
- minute, hour, day, month, weekday string - '\', '1–31', '\/2'
- special_time - annually/daily/hourly/monthly/reboot/weekly/yearly
- cron_file - NEVER use for /etc/crontab
This module has some parameters to perform any tasks.
The only required is "name", where you specify the description of a crontab entry.
The parameter "state" sets whether the cron job is present or not in the target host.
The parameter "job" sets the command to execute or, if env is set, the value of the environment variable.
The parameter "user" sets the specific user for the crontab, when unset, this parameter defaults to the current user.
The most important part is the moment to run the crontab, specifically: "minute", "hour", "day", "month", "weekday". In this field, you could use the star operator "\*" to specify all the minutes, hours, weekdays, days, and months. You could be more specific with a single number, range, or intervals.
There are also some special times already defined in the parameter "special_time". The options are: annually, daily, hourly, monthly, reboot, weekly, yearly.
Let me also highlight that we could also specify the "cron_file" if you want a specific name and not under the user.
Links
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/cron_module.html
- https://crontab.guru/
## Playbook
Ansible schedule a Cron Job task in Linux.
code
- cron.yml
``yaml
---
- name: cron module Playbook
hosts: all
tasks:
- name: "example cronjob"
ansible.builtin.cron:
name: "test"
state: present
minute: "*/2"
hour: "*"
day: "*"
month: "*"
weekday: "*"
job: 'logger "ansible-pilot"'
``
#