Usage of with nested to cat multiple files

I need to create users inputting from 2 list files as below:

cat user.yml
user1
user2
user3

cat group.yml
group1
group2
group3

cat playbook.yml
- name: Add the user
  user:
    name: "{{ item[0] }}"
    group: "{{ item[1] }}"
  with_nested:
    - cat user.yml
    - cat group.yml

The two files will get inputs dynamically from other tasks, so I will not be able to mention the list in ['user1', 'user2'] like that. Kindly suggest how to cat two lists using with_nested


Solution 1:

Q: "Cat two lists using with_nested."

A: For example

    - debug:
        msg: "{{ item.0 }} {{ item.1 }}"
      with_nested:
        - "{{ lookup('file', 'user.yml').splitlines() }}"
        - "{{ lookup('file', 'group.yml').splitlines() }}"

gives

  msg: user1 group1
  msg: user1 group2
  msg: user1 group3
  msg: user2 group1
  msg: user2 group2
  msg: user2 group3
  msg: user3 group1
  msg: user3 group2
  msg: user3 group3

The same result gives the pipe lookup plugin, .e.g.

    - debug:
        msg: "{{ item.0 }} {{ item.1 }}"
      with_nested:
        - "{{ lookup('pipe', 'cat user.yml').splitlines() }}"
        - "{{ lookup('pipe', 'cat group.yml').splitlines() }}"

Lookup plugins "... like all templating, lookups execute and are evaluated on the Ansible control machine."

If the files are stored on the remote host, e.g.

shell> ssh admin@test_11 cat user.yml
user1
user2
user3
shell> ssh admin@test_11 cat group.yml
group1
group2
group3

read the files from the remote host first, e.g.

- hosts: test_11
  tasks:
    - command: cat user.yml
      register: result_user
    - command: cat group.yml
      register: result_group
    - debug:
        msg: "{{ item.0 }} {{ item.1 }}"
      with_nested:
        - "{{ result_user.stdout_lines }}"
        - "{{ result_group.stdout_lines }}"

gives the same result

  msg: user1 group1
  msg: user1 group2
  msg: user1 group3
  msg: user2 group1
  msg: user2 group2
  msg: user2 group3
  msg: user3 group1
  msg: user3 group2
  msg: user3 group3