Possible approaches to iteration

15 views
Skip to first unread message

tom.r...@gmail.com

unread,
Apr 9, 2018, 9:45:59 AM4/9/18
to Ansible Project
I would like to understand semantics of `with_items` in ansible and compare this approach to `map` for example. 

For example, let consider:  

`{{ ["1","2", "3"]  | map('regex_replace', '^(.*)$', \1'some tail')  tail }}`

How to reach the same effect using `with_items` ? 
And in general how does it work ? Where is the body of this loop ?
For example (got from some stack overflow thread):

    ---
    - hosts: localhost
      tasks:
      - name: set fact 1
        set_fact: foo="[ 'zero' ]"
    
      - name: set fact 2
        set_fact: foo="{{ foo }} + [ 'one' ]"
    
      - name: set fact 3
        set_fact: foo="{{ foo }} + [ 'two', 'three' ]"
    
      - name: set fact 4
        set_fact: foo="{{ foo }} + [ '{{ item }}' ]"
        with_items:
          - four
          - five
          - six
    
      - debug: var=foo

To sum up, the question is about which approach is better (`map` vs `with_items`) and possible details of working (e.g. where  is body of this loop) 
Each detail of working ansible is welcome!

Brian Coca

unread,
Apr 10, 2018, 11:01:11 PM4/10/18
to Ansible Project
In the case of 'set_fact' you should not see much difference, but in
most other cases map will always be faster, with_<lookup> executes the
task once per item, except when squashing, but that is magic reserved
to only a few plugins.

FYI the 'item's part is equivalent of loop: '{{ [ "four", "five",
"six"] | flatten(depth=1) }}', a closer representation to map would be
with_list.



--
----------
Brian Coca
Reply all
Reply to author
Forward
0 new messages