首页 > 解决方案 > 如何通过在 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 分别作为键和值的字典的文件。

标签: ansibleansible-2.xansible-inventory

解决方案


一个选项是使用lineinfiledelegate_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

推荐阅读