I am checking to see if a cron job exists and if it doesn’t, add it. Because we use random times (for both hours and minutes) I cannot search for the entire line. Here is what I have:
lineinfile wants to add the line if it is not “present”. You can collapse these two tasks into a single task using just linieinfile.
Remember that each task is describing an “desired state”. In a single task you can look for and add the line if missing. If it is present the task will make no change. if it is missing the task will add it.
Putting cron jobs in individual lines of a shared cron file has
always been an iffy sort of task. Errors in ansible scripting can lead
to putting in duplicate lines, and failing to clear slightly older
formats of the same line. It's why I encourage using "/etc/cron.daily"
files and similar hoptions. Those can also help prevent running your
cron job in the midst of another interfering cron jobs, such as
database backups and filesystem backups.