将with_项的输出存储到ansible中的单个变量中

将with_项的输出存储到ansible中的单个变量中,ansible,Ansible,是否有任何方法将with_项的所有输出存储到单个变量中。我问这个问题的原因是,我需要在采取一些措施之前和之后检查一些服务器的正常运行时间。列表存储在/etc/hosts中/ - hosts: hosts gather_facts: no tasks: - name: Genrate the node list shell: "for node in $(awk '{print $1}' /etc/hosts" register: node_li

是否有任何方法将with_项的所有输出存储到单个变量中。我问这个问题的原因是,我需要在采取一些措施之前和之后检查一些服务器的正常运行时间。列表存储在/etc/hosts中/

- hosts: hosts
  gather_facts: no
  tasks:
      - name: Genrate the node list
        shell: "for node in $(awk '{print $1}' /etc/hosts"
        register: node_list
        become: true


      - name: get the uptime of all nodes
        shell:  "ssh {{ item }} \"awk '{print $1}' /proc/uptime\""
        with_items:
          - "{{ node_list.stdout_lines }}"
        become: true
问题是如何将“name:get the uptime of all nodes”的所有输出存储到单个变量中,以便在采取操作之前和之后进行比较


作为临时解决方案,我将awk命令的输出重定向到一个NFS目录中,该目录在本地和远程_服务器之间共享,然后使用另一个awk在本地进行比较。这很好,但我必须循环两次并存储需要清理的文件

一种常见模式是将循环任务移动到包含文件中,该文件还包含一个任务,用于使用命令的输出更新由列表或字典组成的事实,然后将循环附加到包含任务:

include_file.yml:

---
- name: get the uptime of a node
    shell:  "ssh {{ item }} \"awk '{print $1}' /proc/uptime\""
  register: host_uptime
  become: true
- set_fact:
    hosts_uptime: "{{ hosts_uptime | default({}) | combine({ item: host_uptime.stdout}) }}
在你的剧本中:

- name: get hosts uptime
  include: include_file.yml
  loop: "{{ node_list.stdout_lines }}"
- debug:
    var: hosts_uptime

另外,如果您希望获得正常运行时间的所有主机都是您的Ansible清单的一部分,只要您首先从它们那里收集了事实,您就可以使用
hostvars['some_hostname']['Ansible_uptime_seconds']访问正常运行时间数据
而不必使用临时SSH命令。

请分享您已经尝试过的内容?