161

How do you get the current host's IP address in a role?

I know you can get the list of groups the host is a member of and the hostname of the host but I am unable to find a solution to getting the IP address.

You can get the hostname by using {{inventory_hostname}} and the group by using {{group_names}}

I have tried things like {{ hostvars[{{ inventory_hostname }}]['ansible_ssh_host'] }} and ip="{{ hostvars.{{ inventory_hostname }}.ansible_ssh_host }}"

techraf
  • 64,883
  • 27
  • 193
  • 198
SJC
  • 2,767
  • 4
  • 20
  • 31

12 Answers12

175

A list of all addresses is stored in a fact ansible_all_ipv4_addresses, a default address in ansible_default_ipv4.address.

---
- hosts: localhost
  connection: local
  tasks:
    - debug: var=ansible_all_ipv4_addresses
    - debug: var=ansible_default_ipv4.address

Then there are addresses assigned to each network interface... In such cases you can display all the facts and find the one that has the value you want to use.

techraf
  • 64,883
  • 27
  • 193
  • 198
  • How do you display all flags? – SJC Oct 03 '16 at 06:30
  • `ansible -m setup`, or `all` instead of hostname for all hosts in the inventory file – techraf Oct 03 '16 at 06:31
  • 1
    Can you list all flags from within a task? – SJC Oct 03 '16 at 06:32
  • 2
    @SJC Flags? You mean facts, right? Yes, run `setup:` module with `register: allfacts` and display with `- debug: var=allfacts` – techraf Oct 03 '16 at 06:39
  • 9
    the value of `gather_facts` must be`true` for this to work. it is true by default but one may turn it to false if the info about the hosts is not required. – shshnk Sep 27 '17 at 12:06
  • 3
    Incorrect answer. Default IP address isn't necessarily the address ansible is using during the play – poige Apr 20 '18 at 15:28
  • 3
    @poige It might be incorrect if you ask a new question, as you do. – techraf Apr 20 '18 at 22:40
  • this is not the address ansible connects to. It might match, but it does not have to. – LogicDaemon Oct 11 '21 at 10:35
  • Yes, `ansible_default_ipv4` is not always the required IPv4 of a specific NIC. It's just the address of the NIC that is in the `default` route (e.g. check output of `ip route` or read more here https://medium.com/opsops/ansible-default-ipv4-is-not-what-you-think-edb8ab154b10 ) – DanOPT Mar 06 '23 at 03:42
95

You can get the IP address from hostvars, dict ansible_default_ipv4 and key address

hostvars[inventory_hostname]['ansible_default_ipv4']['address']

and IPv6 address respectively

hostvars[inventory_hostname]['ansible_default_ipv6']['address']

An example playbook:

---
- hosts: localhost
  tasks:
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv6']['address']
Pasi H
  • 2,490
  • 19
  • 18
  • 2
    This might fail in some cases, see this: https://medium.com/opsops/ansible-default-ipv4-is-not-what-you-think-edb8ab154b10 – RafalS Dec 16 '19 at 07:18
  • this is not the address ansible connects to. It might match, but it does not have to – LogicDaemon Oct 11 '21 at 10:36
32

Just use ansible_ssh_host variable

playbook_example.yml

- hosts: host1
  tasks:
  - name: Show host's ip
    debug:
      msg: "{{ ansible_ssh_host }}"

hosts.yml

[hosts]
host1   ansible_host=1.2.3.4

Result

TASK [Show host's ip] *********************************************************************************************************************************************************************************************
ok: [host1] => {
     "msg": "1.2.3.4"
}
29

You can use in your template.j2 {{ ansible_eth0.ipv4.address }} the same way you use {{inventory_hostname}}.

ps: Please refer to the following blogpost to have more information about HOW TO COLLECT INFORMATION ABOUT REMOTE HOSTS WITH ANSIBLE GATHERS FACTS .

'hoping it’ll help someone one day ッ

Orsius
  • 830
  • 1
  • 11
  • 18
  • 17
    Be extra careful. Nowadays the default network interface is not always 'eth0'. It sometimes called `ens3` or `enp2s0` and such things. You have just better bets if you use `ansible_default_ipv4` and if it's not working, then switch back looking for some sane defaults. – Gabor Garami Sep 08 '17 at 14:23
  • 7
    This probably used to work in the past but with Ansible 2.7 this variable is undefined. – Dirk Oct 26 '18 at 15:32
  • this is not the address ansible connects to. It might match, but it does not have to – LogicDaemon Oct 11 '21 at 10:36
13

Simple debug command:

ansible -i inventory/hosts.yaml -m debug -a "var=hostvars[inventory_hostname]" all

output:

"hostvars[inventory_hostname]": {
    "ansible_check_mode": false, 
    "ansible_diff_mode": false, 
    "ansible_facts": {}, 
    "ansible_forks": 5, 
    "ansible_host": "192.168.10.125", 
    "ansible_inventory_sources": [
        "/root/workspace/ansible-minicros/inventory/hosts.yaml"
    ], 
    "ansible_playbook_python": "/usr/bin/python2", 
    "ansible_port": 65532, 
    "ansible_verbosity": 0, 
    "ansible_version": {
        "full": "2.8.5", 
        "major": 2, 
        "minor": 8, 
        "revision": 5, 
        "string": "2.8.5"
    }, 

get host ip address:

ansible -i inventory/hosts.yaml -m debug -a "var=hostvars[inventory_hostname].ansible_host" all

zk01 | SUCCESS => {
    "hostvars[inventory_hostname].ansible_host": "192.168.10.125"
}
NOZUONOHIGH
  • 1,892
  • 1
  • 20
  • 20
10

Plain ansible_default_ipv4.address might not be what you think in some cases, use:

ansible_default_ipv4.address|default(ansible_all_ipv4_addresses[0])
RafalS
  • 5,834
  • 1
  • 20
  • 25
  • 1
    This should be the accepted answer here, per the [documentation](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html#ansible-facts) – Arcsector Nov 23 '22 at 20:28
7

Another way to find public IP would be to use uri module:

    - name: Find my public ip
      uri: 
        url: http://ifconfig.me/ip
        return_content: yes
      register: ip_response

Your IP will be in ip_response.content

chava
  • 379
  • 4
  • 7
  • Another service url that returns the same is: `https://ipecho.net/plain` – Paul Parker Apr 09 '19 at 10:42
  • @PaulParker https://ipecho.net/plain seems KO or ask api token ... ifconfig.me better and stable service since years :+1 – bastien May 23 '19 at 09:10
  • Never been asked for an API token. I cannot speak to the consistency of the service, I haven't monitored it, but it has never failed me. – Paul Parker May 23 '19 at 14:19
5

If you want the external public IP and you're in a cloud environment like AWS or Azure, you can use the ipify_facts module:

# TODO: SECURITY: This requires that we trust ipify to provide the correct public IP. We could run our own ipify server.
- name: Get my public IP from ipify.org
  ipify_facts:

This will place the public IP into the variable ipify_public_ip.

Simon Woodside
  • 7,175
  • 5
  • 50
  • 66
  • This does not always work. For me `ipify_public_ip` variable is empty – Davide Sep 28 '17 at 18:35
  • 2
    For AWS, inventory_hostname will be the ip address. – Berend de Boer Jan 15 '18 at 07:36
  • This plugin can work within a certain set of circumstances, if you're accessing the internet from behind a NAT, it won't work. Basically this works when the servers are accessible to the internet and can hit the ipify.org website to resolve their external IP when accessing the site. – slm Feb 03 '18 at 23:18
  • 1
    @BerenddeBoer Wrong. `inventory_hostname` is whatever is set in the inventory. It could be a host name as set in `.ssh/config`. – admirabilis May 18 '19 at 18:13
  • @slm as I said, if you're looking for the external public IP. If you're behind a NAT, then you won't have an external publicly accessible IP so you wouldn't use this method. – Simon Woodside May 28 '19 at 19:50
5

http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html

so in template, for e. g.:

{{ lookup('dig', ansible_host) }}

Notes:

  • Since not only DNS name could be used in inventory a check if it's not IP already better be added
  • Obviously enough this receipt wouldn't work as intended for indirect host specifications (like using jump hosts, for e. g.)

But still it serves 99 % (figuratively speaking) of use cases.

poige
  • 1,562
  • 15
  • 12
  • 1
    And what if DNS is not used in the environment? – techraf Apr 20 '18 at 22:40
  • (Or, I feel your pain. Otherwise you won't ask naive questions like that.) — If DNS isn't used in inventory one just use ansible_host directly as indicated in my answer. – poige Apr 21 '18 at 01:13
  • 1
    Abs what if `ansible_host` is not the IP address of the host in question? – techraf Apr 21 '18 at 02:01
  • this is not "and what". It's just "what" cause your previously asked question isn't counted, don't forget. – poige Apr 21 '18 at 02:06
  • "get current target host's IP address" — current target host is specified by inventory; it can be either given by DNS name or by IP-address. Both are explained. Don't suffer much – poige Apr 21 '18 at 02:07
  • I have no clue what you are saying; certainly you haven’t answered my clarifying question. So you assume all hosts are accessed either through a DNS address or their real IP address, right? – techraf Apr 21 '18 at 02:13
  • 1
    I have no clue what you are calling as "real IP address". Do you know some unreal ones? – poige Apr 21 '18 at 02:14
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169475/discussion-between-poige-and-techraf). – poige Apr 21 '18 at 02:15
  • Real IP address is the one set on the target itself. Unlike the one you might be accessing server with. – techraf Apr 21 '18 at 03:37
  • Why didn't you use term real DNS address then? O_o "Please avoid extended discussions in comments. Would you like to automatically move this discussion to chat?" — I've answered there hours ago – poige Apr 21 '18 at 04:02
  • Because I did not find it appropriate to formulate my thought using words you suggested. Sorry, I am using StackOverflow app, it neither suggests anything nor supports chat. Does it bother you? – techraf Apr 21 '18 at 04:09
  • Your inconsistency your mean? – poige Apr 21 '18 at 04:34
1

The following snippet will return the public ip of the remote machine and also default ip(i.e: LAN)

This will print ip's in quotes also to avoid confusion in using config files.

>> main.yml

---
- hosts: localhost
  tasks:
    - name: ipify
      ipify_facts:
    - debug: var=hostvars[inventory_hostname]['ipify_public_ip']
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']
    - name: template
      template:
        src: debug.j2
        dest: /tmp/debug.ansible

>> templates/debug.j2

public_ip={{ hostvars[inventory_hostname]['ipify_public_ip'] }}
public_ip_in_quotes="{{ hostvars[inventory_hostname]['ipify_public_ip'] }}"

default_ipv4={{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}
default_ipv4_in_quotes="{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
Akhil
  • 912
  • 12
  • 23
  • 2
    Some comments by you would improve this answer – Marged Jan 09 '19 at 22:10
  • 1
    `ipify:` is a community module. You'll soon need to use `community.genereal.ipify:` to access it. Answers consisting of only code are discouraged on SO. Explain how this works. – Jeter-work Mar 07 '22 at 17:26
0

In my case, I had needed to keep the IP and then run a command using delegate_to, so I wrote something as follows in variables:

leader_ip: '{{ansible_ssh_host}}'

and then I used the leader_ip.

the other solution is to use hostvar:

hostvars[INVENTORY_HOSTNAME]['ansible_host']
Daniel
  • 61
  • 10
0

This way worked for me:

this_node_ip: '{{ hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2] }}'
Aupr
  • 715
  • 9
  • 14