是否可以将with_items的所有输出的输出存储到单个变量中。我问的原因是,在采取某些措施之前和之后,我需要检查少数服务器的正常运行时间。列表存储在/ 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
问题是如何将“名称:获取所有节点的正常运行时间”的所有输出存储到单个变量中,以便我可以在采取行动之前和之后进行比较。
作为临时解决方案,我将awk命令的输出重定向到NFS目录中,该目录在本地和remote_server之间共享,并且稍后使用另一个awk在本地进行了比较。这工作正常,但我必须循环两次并存储需要清理的文件。
答案 0 :(得分:0)
一种常见的模式是将循环的任务移到一个include文件中,该文件还包含一个使用命令的输出来更新由列表或字典组成的事实的任务,然后将循环附加到include任务:
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清单的一部分,只要您首先从它们中收集了事实,就可以使用{{1 }},而不必使用该即席SSH命令。</ p>