DEV Community

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

Posted on • Edited on

Automating Cron Job Setup with Ansible Like a Pro

Hello, I'm Maneshwar. I'm building git-lrc, an AI code reviewer that runs on every commit. It is free, unlimited, and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

Hello, I'm Maneshwar. I'm working on FreeDevTools online currently building **one place for all dev tools, cheat codes, and TLDRs* — a free, open-source hub where developers can quickly find and use tools without any hassle of searching all over the internet.

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


Keeping servers clean, logs trimmed, and disk spac
e 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.

Any feedback or contributors are welcome!

It’s online, open-source, and ready for anyone to use.

👉 Check it out: ⭐ Star it on GitHub:

Let’s make it even better together.

git-lrc
*AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.*

Any feedback or contributors are welcome! It's online, source-available, and ready for anyone to use.

⭐ Star it on GitHub:

GitHub logo HexmosTech / git-lrc

Free, Unlimited AI Code Reviews That Run on Commit

git-lrc logo

git-lrc

Free, Unlimited AI Code Reviews That Run on Commit


git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

See It In Action

See git-lrc catch serious security issues such as leaked credentials, expensive cloud operations, and sensitive material in log statements

git-lrc-intro-60s.mp4

Why

  • 🤖 AI agents silently break things. Code removed. Logic changed. Edge cases gone. You won't notice until production.
  • 🔍 Catch it before it ships. AI-powered inline comments show you exactly what changed and what looks wrong.
  • 🔁 Build a habit, ship better code. Regular review → fewer bugs → more robust code → better results in your team.
  • 🔗 Why git? Git is universal. Every editor, every IDE, every AI…




Top comments (0)