ansible cron job - ghdrako/doc_snipets GitHub Wiki

A cron job entry consists of six fields:

  • Minute (0 - 59)
  • Hour (0 - 23)
  • Day of the month (1 - 31)
  • Month (1 - 12)
  • Day of the week (0 - 7; 0 and 7 represent Sunday)
  • Command to execute

Environment Variables: Be aware that cron jobs run with a minimal environment, so specify all necessary paths and variables.

Creating Cron Jobs

---
- hosts: webserver
  become: yes
  tasks:
    - name: Daily backup of web content
    cron:
      minute: "0"
      hour: "3"
      user: webuser
      job: "/usr/local/bin/backup-web-content.sh"

Modifying Cron Jobs

For example, to change the backup time to 4:00 AM:

- name: Update backup time to 4:00 AM
  cron:
    minute: "0"
    hour: "4"
    user: webuser
    job: "/usr/local/bin/backup-web-content.sh"

Removing Cron Jobs

- name: Remove backup job
  cron:
    user: webuser
    job: "/usr/local/bin/backup-web-content.sh"
    state: absent

Complex Scheduling

un a script every 15 minutes during business hours on weekdays:

- name: Run script during business hours
  cron:
    minute: "*/15"
    hour: "9-17"
    weekday: "1-5"
    user: webuser
   job: "/usr/local/bin/business-hours-task.sh"