2

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
1
  • Only variables can be tested as defined. Is this really what you want? Testing the existence of variables? Mar 19, 2021 at 3:44

2 Answers 2

1
    - 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
0

The use-case is adding an item to a list if some variables are defined. The best structure is a dictionary, e.g.

    d1:
      item1:
        l: []
      item2:
        l: [condition1, condition3]
      item3:
        l: [condition4]

If the variable condition4 is defined but others are not the task below

    - set_fact:
        items_list: "{{ items_list|default([]) + [item.key] }}"
      loop: "{{ d1|dict2items }}"
      when: _vals|from_yaml is all
      vars:
        _vals: |
          [
          {% for i in  item.value.l %}
          {{ vars[i] is defined }},
          {% endfor %}
          ]

gives

  items_list:
  - item1
  - item3
1
  • What is is all?
    – Jiri B
    Mar 19, 2021 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.