DEV Community

Cover image for Automating Cron Job Setup with Ansible Like a Pro
Athreya aka Maneshwar
Athreya aka Maneshwar

Posted on

Automating Cron Job Setup with Ansible Like a Pro

Hi there! I'm Maneshwar. Right now, I’m building LiveAPI, a first-of-its-kind tool that helps you automatically index API endpoints across all your repositories. LiveAPI makes it easier to discover, understand, and interact with APIs in large infrastructures.


Keeping servers clean, logs trimmed, and disk space healthy?

Cron jobs do the grunt work — but managing them manually? Pain.

That’s where Ansible saves the day.

Here's how I automated system maintenance jobs with a reusable Ansible role called cron-master.

Project Structure

ansible-galaxy init roles/cron-master --offline
Enter fullscreen mode Exit fullscreen mode
ansible/
├─ README.md
├─ ansible.cfg
├─ cron-master.yml              # playbook to run cron-master role
├─ hosts.ini                    # inventory file
├─ install_ansible.sh           # bootstrap script
├─ requirements.yml
├─ roles/
│  └─ cron-master/
│     ├─ tasks/                 # main logic broken into files
│     │  ├─ main.yml
│     │  ├─ crons.yml
│     │  ├─ deps.yml
│     │  ├─ clean.yml
│     │  └─ space.yml
│     ├─ templates/             # cron scripts and job list
│     │  ├─ crons.j2
│     │  ├─ clean.sh.j2
│     │  └─ space.sh.j2
│     ├─ defaults/vars/meta/... usual role files
Enter fullscreen mode Exit fullscreen mode

Installing Dependencies

We need basic packages and a specific version of cronitor to monitor jobs.

roles/cron-master/tasks/deps.yml

- name: Ensure dependencies are installed
  apt:
    name:
      - bc
      - curl
    state: present

- name: Check cronitor version
  command: cronitor --version
  register: cronitor_version
  changed_when: false
  failed_when: false

- name: Install specific cronitor version
  when: "'30.3' not in cronitor_version.stdout"
  block:
    - name: Download cronitor 30.3
      get_url:
        url: https://github.com/cronitorio/cronitor-cli/releases/download/30.3/linux_amd64.tar.gz
        dest: /tmp/cronitor.tar.gz

    - name: Extract and move binary
      unarchive:
        src: /tmp/cronitor.tar.gz
        dest: /tmp
        remote_src: yes

    - name: Move cronitor binary
      command: mv /tmp/cronitor /usr/local/bin/cronitor
Enter fullscreen mode Exit fullscreen mode

Defining Cron Jobs

I put my cron jobs in a crons.j2 template, so I can maintain them like code:

roles/cron-master/templates/crons.j2

0 0 * * * sudo truncate -s 0 /var/log/nginx/access.log
0 0 * * * sudo truncate -s 0 /var/log/nginx/nginx_error.log
0 0 * * * rm /var/log/nginx/*.gz
Enter fullscreen mode Exit fullscreen mode

Then loaded it in crons.yml:

- name: Add custom cron jobs to root crontab
  vars:
    lines: "{{ lookup('template', 'crons.j2').splitlines() }}"
  cron:
    name: "{{ (idx > 0 and lines[idx-1].strip().startswith('#')) | ternary(lines[idx-1] | trim | regex_replace('^#\\s*', ''), ' '.join(item.split()[5:])) }}"
    minute: "{{ item.split()[0] }}"
    hour: "{{ item.split()[1] }}"
    day: "{{ item.split()[2] }}"
    month: "{{ item.split()[3] }}"
    weekday: "{{ item.split()[4] }}"
    job: "{{ ' '.join(item.split()[5:]) }}"
    user: root
  loop: "{{ lines }}"
  loop_control:
    index_var: idx
  when: item | trim | length > 0 and not item.strip().startswith('#')
Enter fullscreen mode Exit fullscreen mode

Custom Scripts for Cleaning & Space Checks

I used templates like clean.sh.j2 and space.sh.j2, then scheduled them via clean.yml and space.yml.

Master Task File

main.yml ties it all together:

- name: Install dependencies
  include_tasks: deps.yml

- name: Deploy clean script
  include_tasks: clean.yml

- name: Deploy space check cron
  include_tasks: space.yml

- name: Add custom cron jobs
  include_tasks: crons.yml
Enter fullscreen mode Exit fullscreen mode

Running the Role

Use a playbook like this:

cron-master.yml

- name: Set up cron jobs on servers
  hosts: all
  become: true
  roles:
    - cron-master
Enter fullscreen mode Exit fullscreen mode

Then run it:

ansible-playbook -i hosts.ini cron-master.yml
Enter fullscreen mode Exit fullscreen mode

Why This Rocks

  • 🔁 Idempotent cron management
  • 📋 All cron jobs version-controlled
  • 🔎 Easy to test in isolation with ansible-playbook --tags
  • 🔐 Secure and predictable

Bonus Tip: Test with Vagrant or Docker

You can easily test this role in a local VM or container to be safe before pushing to prod.


LiveAPI helps you get all your backend APIs documented in a few minutes.

With LiveAPI, you can generate interactive API docs that allow users to search and execute endpoints directly from the browser.

LiveAPI Demo

If you're tired of updating Swagger manually or syncing Postman collections, give it a shot.

Top comments (0)