Score:1

Usage of with nested to cat multiple files

ar flag

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

Score:1
br flag

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
pugazhendhi avatar
ar flag
Thanks @Vladimir Botka, it is working for me
br flag
You're welcome. I've added an example of the files stored on the remote host.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.