ansible - 迭代库存时,Ansible如何将寄存器的输出存储在列表中
问题描述
我正在运行一个 shell 命令,该命令对我的清单文件中列出的所有主机运行。然后我使用寄存器来定义变量,当我检索调试消息的这些值时,我看到为我的清单中的所有 IP 打印的所有主机的寄存器变量,但我想将它们存储在一个列表中,以便我可以在模板中使用它们。我们怎样才能实现它?
- name: Command
shell: hostname -f
register: fqdn_name
解决方案
对于您的具体问题,您所做的工作超出了您的需要。每次 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.all
为groups.<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: ...
推荐阅读
- android - 单击工具栏上的菜单项不适用于 Navigationview
- r - 在 R Shiny 中使用 sql 查询时如何指定引号
- sql - 尝试使用 with 语句提取唯一值
- python - 使用数字和非数字变量的 imputer 从 numpy 更改为 pandas 时保留列名
- c# - 在 C# 中使用 API 发布
- reactjs - 尝试导入错误:“useControlled”未从“@material-ui/core/utils”导出
- java - 如何使用 thymeleaf 以一种形式显示来自 2 个实体的值
- python - 如何根据用户回答在 Streamlit 中显示代码?
- python - 使用 python 3.6 在 mac 上安装 mysqlclient 时出错
- arrays - 为具有 JSON 数组值的 jsonb 列创建 Postgres 索引