Make a CSV file of all the cronjobs on all the systems managed by ansible

March 31, 2017 - Reading time: 3 minutes

To get a monthly overview of all the cronjobs on all the systems I wrote a wrapper (in bash) to create the CSV lines which with the help of an ansible playbook to generate a csv file.

This is the wrapper (

#this script will return a CSV file containing the server,user,cronjob
#this is set to be able to use filters on wildcards
shopt -s extglob
#here we store the hostname since we only need to declare this once
HOST=$(hostname|cut -d"." -f1)
#here we start looping through all the cron files exept the ones filtered by the pipe seperated list
for f in $(ls /var/spool/cron/*;ls /etc/cron.d/!(*@(sysstat|0hourly)) 2>>/dev/null )
        #here we store the content of the current cron file
        COMMAND=$(cat $f)
        #here we loop over the individual jobs in the file while filtering out comments and empty lines
        echo "$COMMAND" | sed /^#/d | sed /^\s*$/d | while read line;
                #here we start printing a line for our CSV file
                #starting with the host
                printf $HOST","
                #here we check if it is a user or a system cron and we print accordingly
                if [[ $f == /var/spool/cron/* ]];
                        printf $USER","
                        printf "system,"
                #and finally here we print the actual command and since we desire a new line echo is used here instead of printf
                echo "$line"

 And the matching playbook (made by a colleague):

- hosts: all
  #gather_facts: no
#  - name: create folder
#    local_action: file dest=/tmp/cron_collect state=directory owner=root group=root mode=0700
  - block:
    - name: "collect crons on system"
      script: "{{ playbook_dir}}/../../scripts/"
      register: crons
      ignore_errors: yes
    - name: move to csv file
      local_action: copy content={{ crons.stdout }} dest=/opt/systems/cron_collect/{{ansible_fqdn}}.csv
- hosts: localhost:ansibleserver01
  gather_facts: no
  - name: combine into one file
      src: /opt/systems/cron_collect/
      dest: /tmp/croncollection.csv
      owner: bescorli
      group: sysauto
      mode: 0640
  - name: remove blanks
      dest: /tmp/croncollection.csv
      regexp: '^\s$'
      state: absent



Koen Diels

I'm a freelance system and network engineer from Mechelen (BE) and I'm available for ad-hoc and long term projects.

>>my resume<<