首页 > 解决方案 > 迭代库存时,Ansible如何将寄存器的输出存储在列表中

问题描述

我正在运行一个 shell 命令,该命令对我的清单文件中列出的所有主机运行。然后我使用寄存器来定义变量,当我检索调试消息的这些值时,我看到为我的清单中的所有 IP 打印的所有主机的寄存器变量,但我想将它们存储在一个列表中,以便我可以在模板中使用它们。我们怎样才能实现它?

- name: Command
    shell: hostname -f
    register: fqdn_name

标签: ansibleansible-2.xansible-inventoryansible-factsansible-template

解决方案


对于您的具体问题,您所做的工作超出了您的需要。每次 Ansible 运行主机时,它都会收集一系列关于主机的“事实”,并将它们存储在您播放期间可用的字典中。因此,将您现有的 Command 任务替换为以下内容,以了解我的意思:

- name: Display the Ansible FQDN fact
  debug:
    var: ansible_fqdn

运行ansible -m setup <hostname taken from inventory file>将显示所有收集到的变量。

您所有主机的变量都可以通过一个名为“hostvars”的特殊字典获得,因此在您的模板中您可以执行以下操作:

{% for host in groups.all %}
{{ hostvars[host]['ansible_fqdn'] }}
{% endfor %}

您可以替换groups.allgroups.<some inventory groupname>将匹配的主机限制为特定组。

这里一个可能的问题是,只有在 Ansible 已经针对主机时才会收集这些事实,因此更复杂的剧本的一种策略是:

# This play simply connects to all your hosts and gathers facts
- hosts: all
  gather_facts: yes

# Now all subsequent plays have access to facts for all hosts
- hosts: <all or some group>
  tasks: ...

推荐阅读