Search code examples
ansibleansible-inventoryansible-facts

How to get host IP and hostname using Ansible


I am trying to create a task that will get the host target IP address and host-name that are in the inventory then save it to a file in the local directory.

Would love to save the data like this:

hostname:ip-address

where to start?


Solution

  • I would suggest using"delegate_to", I tried that on my computer and it worked properly. I put the first step to delete the file if it exists so it can be executed multiple times. This is a very fast example, I suggest to use variables for the path, etc. But I think you can get the idea

    ---
    - 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