Code Snippet

Just another Code Snippet site

[Ansible] Loop

Loop with index & length to debug variables :

- name: "Debug"
  debug: msg="[{{item.0 +1}}/{{var_2_debug | length}}] {{item.1}} is {{ vars[item.1] | default('undefined') }}"
  with_indexed_items: "{{var_2_debug}}"

with :

var_2_debug:
    - "var_1"
    - "var_2"
    - "var_3"

{{item.0}} is the index of the item
{{item.1}} is the value of the item
vars[item.1] is an “eval” version of the item

Loop over files :

var_files_2_load:
    - "file1.yml"
    - "file2.yml"

- name: "Load variables from files"
  include_vars: "{{item}}"
  with_items: "{{var_files_2_load}}"


3 thoughts on “[Ansible] Loop

  • Olivier says:
    - name: "Test"
      debug: msg="[{{ item.0 +1 }}/{{ app_modules | length }}] {{item.1.installer_name}}"
      with_indexed_items: '{{ app_modules }}'
    

    with ;

    app_modules : [
        {
            installer_name: 'AA1',
            version: '1.0.0.0'
        },
        {
            installer_name: 'AA2',
            version: '1.0.0.0'
        },
        {
            installer_name: 'AA3',
            version: '1.0.0.0'
        }
    ]
    
  • Olivier says:

    Loop “for” basic

    - debug: msg="Loop index = {{item}}"
      with_sequence: count=5
    

    from 1 to 5

    - debug: msg="Loop index = {{item}}"
      with_sequence: start=0 end=5
    

    from 0 to 5

Leave a Reply to Olivier Cancel reply

Your email address will not be published. Required fields are marked *