Ansible – Conditionally Append to a List in Ansible

ansible

I'm quite new to Ansible, so please be patient. I'm trying to come up with an elegant way to populate a list. Some of the items should be in the list unconditionally, for example, item1. Some of them would be added to the list if "when" conditions are met. So far I got this and it is not working, I assume it just overrides item1 with item2 and 3. Also, it starts looking ugly the more items you add. Has anyone had experience with populating ansible lists conditionally?

 - name: Add items to list
      set_fact:
        items_list: ["item1"]
      with_items: 
        - item2
          when:
           - condition1 is defined
           - condition3 is defined
        - item3
          when:
          - condition 4 is defined

Best Answer

    - set_fact:
        items_list: "{{ items_list | default(['item1']) + [item] }}"
      loop:
        - "{{ (True and True) | ternary('item2', None) }}"
        - "{{ (True) | ternary('item3', None) }}"
      when: item
    - debug: var=items_list

or

     - set_fact:
         items_list: "{{ items_list | default(['item1']) + [item] }}"
       loop:
         - "item2"
         - "item3"
       when: >-
         (item == "item2" and True and True) or
         (item == "item3" and True)
     - debug: var=items_list