如何通过在localhost上运行playbook来获取inventory_hostanme和ansible_ssh_hosts信息

问题描述 投票:0回答:2

我想将一个特定组下的主机名和ssh_host从库存文件写入我的localhost中的文件。我试过这个:

我的角色

  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分别作为键和值。

ansible ansible-2.x ansible-inventory
2个回答
1
投票

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

0
投票

非常感谢你的回答@ Vladimir Botka

我想出了将属于某个组的主机写入文件的另一个要求,下面的代码可以帮助解决这个问题(添加到@ Vladimir的解决方案)。

- hosts: all
  become: no
  gather_facts: no
  tasks:
    - set_fact:
        my_inventory_hostname: "{{ ansible_host }}"
   - lineinfile:
        path: temp/hosts
        line: "inventory_hostname: {{ my_inventory_hostname }}"
      when: inventory_hostname in groups['my_group']
      delegate_to: localhost
    - debug:
        msg: "inventory_hostname: {{ ansible_host }}"
© www.soinside.com 2019 - 2024. All rights reserved.