大网数据广告活动
服务器运维问答

Usage of with nested to cat multiple files

· 52CE 我爱测

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: …

问题原文

原帖链接 · pugazhendhi · CC BY-SA 4.0

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

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

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

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-07-23)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。