Search code examples
if-statementansibleconditional-statementslogrotate

If conditions for parameters in Ansible


This is task to add cronjob to crontab:

    - name: Add job triggering logs rotation for clusters.
      cron:
        cron_file: '/etc/crontab'
        user: 'root'
        name: 'logrotate'
        minute: *
        hour: '*/4'
        job: '/etc/cron.daily/logrotate'
        state: present

What I want to accomplish is to add minute: */5 and hour: * if dev in inventory_hostname, else add minute: 0 and hour: */4.

Is there any way to do this adding conditions in minute and hour parameters? Can I deal with this using template, but just to add this two parameters in mentioned task?


Solution

  • This is one way to achieve this with the ternary filter:

        - name: Add job triggering logs rotation for clusters.
          vars:
            is_dev: "{{ 'dev' in inventory_hostname }}"
          cron:
            cron_file: '/etc/crontab'
            user: 'root'
            name: 'logrotate'
            minute: "{{ is_dev | ternary('*/5', '*') }}"
            hour: "{{ (is_dev | ternary('*', '*/4' }}"
            job: '/etc/cron.daily/logrotate'
            state: present