Add an item to a list dependent on a conditional in ansible

前端 未结 4 604
情书的邮戳
情书的邮戳 2021-01-17 16:04

I would like to add an item to a list in ansible dependent on some condition being met.

This doesn\'t work:

  some_dictionary:
    app:
       - some         


        
4条回答
  •  灰色年华
    2021-01-17 16:51

    You can filter out all falsey values with select(), but remember to apply the list() filter afterwards. This seems an easier and more readable approach for me:

    - name: Test
      hosts: localhost
      gather_facts: no
      vars:
          mylist:
            - "{{ (true)  | ternary('a','') }}"
            - "{{ (false) | ternary('b','') }}"
            - "{{ (true)  | ternary('c','') }}"
     
      tasks:
      - debug:
          var: mylist|select|list
    

    Result:

    TASK [debug] *****************************************************************************************************************************************************************************************************************
    ok: [localhost] => {
        "mylist|select()|list": [
            "a", 
            "c"
        ]
    }
    

    Replace (true) and (false) with whatever test you want.

提交回复
热议问题