2

How could I omit parameter in lookup when it isn't defined?

I have tried with something like default(omit), but it doesn't work:

- set_fact:
    myvar: >-
      {{ query(
          'awx.awx.schedule_rrule',
          'minute',
          start_date=item.start_date | default(omit) 
      ) }}

This errors with:

fatal: [localhost]: FAILED! =>
msg: 'An unhandled exception occurred while running the lookup plugin ''awx.awx.schedule_rrule''. Error was a <class ''ansible.errors.AnsibleError''>, original message: Parameter start_date must be in the format YYYY-MM-DD [HH:MM:SS]. Parameter start_date must be in the format YYYY-MM-DD [HH:MM:SS]'

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Kucharsky
  • 201
  • 3
  • 16

1 Answers1

2

This one is indeed a tricky one, it seems like the omit happens too late even if you use the trick to pass a dictionary in the named parameters of the lookup.

So, to cover it, you could trim down the item dictionary to the start_date only or an empty dictionary, with the selectattr filter:

- debug:
    msg: >-
      {{ query(
          'awx.awx.schedule_rrule',
          'minute',
          **_param
      ) }}
  loop: "{{ rrules }}"
  loop_control:
    label: "{{ item.name }}"
  vars:
    _param: >-
      {{
        item
        | dict2items
        | selectattr('key', 'eq', 'start_date')
        | items2dict
      }}
    rrules:
      - name: r1
        start_date: '2022-01-01 13:00:00'
      - name: r2

Or, if you want a more verbose version — that would probably also be more readable for neophytes, with an inline-if expression:

- debug:
    msg: >-
      {{ query(
          'awx.awx.schedule_rrule',
          'minute',
          **(
            {'start_date': item.start_date}
            if item.start_date is defined
            else {}
          )
      ) }}
  loop: "{{ rrules }}"
  loop_control:
    label: "{{ item.name }}"
  vars:
    rrules:
      - name: r1
        start_date: '2022-01-01 13:00:00'
      - name: r2

Both would yield:

ok: [localhost] => (item=r1) => 
  msg: DTSTART;TZID=Europe/Paris:20220101T130000 RRULE:FREQ=MINUTELY;INTERVAL=1
ok: [localhost] => (item=r2) => 
  msg: DTSTART;TZID=Europe/Paris:20220705T192634 RRULE:FREQ=MINUTELY;INTERVAL=1
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83