Jinja2 filter list using string contains test

后端 未结 4 1555
遥遥无期
遥遥无期 2021-02-20 06:01

I\'m trying to filter a list in ansible in Jinja2 when the elements contain a string, but the Jinja documentation doesn\'t seem clear enough for me to figure it out.

Thi

4条回答
  •  忘了有多久
    2021-02-20 06:13

    You can build a new list with set_fact and print the elements of a new list.

    - hosts: localhost
      gather_facts: false
      vars:
        script_stdout_lines:
          - apples
          - running script one
          - oranges
          - running script two
      tasks:
        - set_fact:
            new_list: "{{ new_list | default([]) + [item] }}"
          with_items: "{{ script_stdout_lines }}"
          when: '"running script" in item'
        - debug: var=new_list
    

    Result:

    TASK [set_fact] *********************************************************************************************************************
    skipping: [localhost] => (item=apples) 
    ok: [localhost] => (item=running script one)
    skipping: [localhost] => (item=oranges) 
    ok: [localhost] => (item=running script two)
    
    TASK [debug] ************************************************************************************************************************
    ok: [localhost] => {
        "new_list": [
            "running script one",
            "running script two"
        ]
    }
    

    It prints skipping during set_fact operation but at the end it provides a new list with the only matching items.

提交回复
热议问题