Search code examples
ansibleansible-2.xansible-inventoryansible-factsansible-template

Pass/loop 2 register output lines (has list of values each) to next task in Ansible


I'm trying to pass 2 register list values to a task. but when I pass both the list , it is not looping to the register values but its just passing the complete array of list.

data (ls -ld)

drwxr-xr-x  2 root           root                 4096 Jun  4  2019 dir_1
drwxr-xr-x  2 root           root                 4096 Jun  4  2019 dir_2
drwxr-xr-x  2 ram            ram                  4096 Jun  4  2019 dir_3
drwxr-xr-x  2 mike           mike                 4096 Jun  4  2019 dir_4

Code

- name: Get Owners
  become: false
  shell: ls -ld  | awk '{print $3}'
  args:
    chdir: /data
  register: owner

- name: Get foldernames
  become: false
  shell: ls -ld | awk '{print  $9}'
  args:
    chdir: /data
  register: foldername

- name: check if its able to loop.
  debug:
    msg: "{{item.a}}:{{item.b}}"
  loop:
    - { a: "{{ owner.stdout_lines }}", b: "{{ foldername.stdout_lines }}" }

output

Instead of having the output looped its copying the whole (stdout_lines) list in array 

"msg": "[u'root', u'root', u'ram', u'mike']:[u'dir_1', u'dir_2', u'dir_3', u'dir_4']

How can I get the data (owner and foldername) looped and passed to the msg one by one in a sequence (and right owner to folername).


Solution

  • Q: "How can I get the data (owner and foldername) looped and passed to the msg one by one in a sequence (and right owner to folername)."

    A: There are more options.

    1) Use zip. For example

    - name: debug:
        msg: "{{ item.0 }} - {{ item.1 }}"
      loop: "{{ owner.stdout_lines|zip(foldername.stdout_lines)|list }}"
    

    2) It's possible to find the directories and json_query registered result in the loop. For example

        - find:
            path: data
            file_type: directory
          register: result
    
        - debug:
            msg: "{{ item.0 }} - {{ item.1 }}"
          loop: "{{ result.files|json_query('[].[pw_name, path]') }}"