Thursday, 30 July 2020

Create, Modify, Delete a cron job using Ansible

There are two ways we can create a cron on a linux machine.

  1. Login to specific user and execute 'crontab -e'
  2. create a cron job file under /etc/cron.d

Now we will write a playbook with 3 tasks:
  • Create a cron job for a user(similar to crontab -e)
  • Delete  a cron job
  • Create a cron job file under /etc/cron.d
Cron-Job.yml

- hosts: all
  become: yes
  become_method: sudo
  tasks:

   - name: create cron job
     cron:
      name: "check dir space"
      user: jsmith
      minute: "5"
      job: "/home/jsmith/df.sh"

   - name: delete cron job
     cron:
      name: "check directory"
      user: jsmith
      state: absent

   - name: Creates a cron file under /etc/cron.d
     cron:
      name: check dir from cron.d file
      minute: "5"
      user: jsmith
      job: "/home/jsmith/df-cron.sh"
      cron_file: checkdir_cron


This playbook will create a cron job with will run every 5 min

It created the cron job file under /etc/cron.d



Also we created the cron job in user's profile


There are many parameters available for 'cron' module, you can refer to ansible official document:


No comments:

Post a Comment