ansible - 如何通过在 localhost 上运行 playbook 来获取 inventory_hostanme 和 ansible_ssh_hosts 信息
问题描述
我想将特定组下的主机名和 ssh_host 从清单文件写入本地主机中的文件。我试过这个:
我的角色
set_fact:
hosts: "{{ hosts_list|default({}) | combine( {inventory_hostname: ansible_ssh_host} ) }}"
when: "'my_group' in group_names"
剧本
become: no
gather_facts: no
roles:
- my_role
但是现在,如果我尝试将其写入另一个任务中的文件,它将为清单文件中的主机创建一个文件。
您能否建议是否有更好的方法通过在 localhost 上运行 playbook 来创建一个包含以 inventory_hostname 和 ansible_ssh_host 分别作为键和值的字典的文件。
解决方案
一个选项是使用lineinfile和delegate_to localhost。
- hosts: test_01
tasks:
- set_fact:
my_inventory_hostname: "{{ ansible_host }}"
- tempfile:
delegate_to: localhost
register: result
- lineinfile:
path: "{{ result.path }}"
line: "inventory_hostname: {{ my_inventory_hostname }}"
delegate_to: localhost
- debug:
msg: "inventory_hostname: {{ ansible_host }}
stored in {{ result.path }}"
注:无需引用条件。默认情况下扩展条件。
when: my_group in group_names
推荐阅读
- php - 如何动态地将方法添加到类中?
- entity-framework-core - EF Core - 从原始 SQL 填充未映射的列?
- angular - 角度自动刷新数据
- javascript - 如何在 JavaScript 中转换以下形式的对象数组?
- keras - 当我开始训练数据集时弹出输入用完数据错误
- javascript - addEventListener 仍然多次触发(即使使用同名回调)
- webrtc - 如何使用 [agora.io] 接收远程流
- r - 在 xtabs 中包含缺失的因子水平
- c++ - 在多线程应用程序中将数组作为函数的返回值传递
- swig - SWIG:如何在不包含标题的情况下将枚举映射到整数?