Ansible - 将远程脚本的输出读入变量以供另一个游戏处理

Ansible - Reading output of remote scripts into variable for processing by another play

我正在编写一个剧本,它将 运行 多个远程盒子上的脚本。 运行 需要将这些遥控器的 stdout_lines 整理成一个数组,该数组可以传递给本地 运行 书中的另一个剧本,然后将这个整理好的大数组传递给到一个模块。

我似乎找不到执行此操作的方法。下面是一些代码类的东西(不起作用):

---

- name: Gather information from hosts
  hosts: remote-hosts
  become: yes
  become_method: sudo

  vars:
    information: |
      {%- set o=[] %}
      {%- for i in play_hosts %}
        {%- for line in hostvars[i].info_script_output_lines %}
          {%- if o.append(hostvars[i].info_script_output_lines[line]) %}
          {%- endif %}
        {%- endfor %}
      {%- endfor %}
      {{ o }}

  tasks:
    - name: Run info retrieval script
      script: /script_folder/script_that_outputs_lines.sh
      register: info_script_output

    - set_fact:
        info_script_output_lines: "{{ info_script_output.stdout_lines }}"

    - set_fact:
        final_info: "{{ info_script_output_lines }}"
        run_once: true
        delegate_to: 127.0.0.1
        delegate_facts: true

- name: Output result
  hosts: localhost

  tasks:
    - debug:
        msg: Output = {{ hostvars['localhost']['final_info'] }}

hostvars['localhost']['final_info']在第二部中不存在。

任何人都可以解释一下我是否 (a) 使用每个遥控器的输出事实正确构建我的数组,以及 (b) 如何将最终的合并数组放入另一个游戏中以便我可以使用它?

给你:

---
- hosts: mygroup
  gather_facts: no
  tasks:
    - shell: echo begin; echo {{ inventory_hostname }}; echo end;
      register: cmd_output
    - set_fact:
        my_lines: "{{ cmd_output.stdout_lines }}"

- hosts: localhost
  gather_facts: no
  vars:
    combined_lines: "{{ groups['mygroup'] | map('extract',hostvars,'my_lines') | sum(start=[]) }}"
  tasks:
    - debug:
        msg: "{{ combined_lines }}"

使用 extract 过滤器,然后 sum(start=[]) 将列表展平为长行列表。