Ansible - 将远程脚本的输出读取到变量中,以便由另一个播放处理



我正在编写一个剧本,它将在许多远程设备上运行脚本。运行这些远程数据库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=[])将列表平展为长行列表。

最新更新