如何使用 Ansible 获取主机 IP 和主机名

How to get host IP and hostname using Ansible

我正在尝试创建一个任务,以获取清单中的主机目标 IP 地址和主机名,然后将其保存到本地目录中的文件中。

喜欢这样保存数据:

hostname:ip-address

从哪里开始?

我建议使用“delegate_to”,我在我的电脑上试过了,它工作正常。我把第一步删除文件(如果存在)以便可以多次执行。这是一个非常快的例子,我建议使用变量作为路径等。但我想你可以理解

---
- hosts: your_inventory

  tasks:
    - name: delete the file if exists
      file:
        path: /home/yourpath/host_ip.txt
          state: absent
      delegate_to: localhost
    - name: get data to a file
      lineinfile:
        dest: /home/yourpath/host_ip.txt
        create: yes
        line: "{{hostvars[inventory_hostname].ansible_hostname}}:{{hostvars[inventory_hostname].ansible_default_ipv4.address}}"
      delegate_to: localhost