Ansible: get current target host's IP address
Asked Answered
G

14

165

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

Graphite answered 2/10, 2016 at 16:54 Comment(0)
C
178

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.

Cologne answered 2/10, 2016 at 23:1 Comment(9)
How do you display all flags?Graphite
ansible <host> -m setup, or all instead of hostname for all hosts in the inventory fileCologne
Can you list all flags from within a task?Graphite
@Graphite Flags? You mean facts, right? Yes, run setup: module with register: allfacts and display with - debug: var=allfactsCologne
the value of gather_facts must betrue 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.Bavardage
Incorrect answer. Default IP address isn't necessarily the address ansible is using during the playBuckler
@Buckler It might be incorrect if you ask a new question, as you do.Cologne
this is not the address ansible connects to. It might match, but it does not have to.Flytrap
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 medium.com/opsops/… )Kamal
E
101

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']
Endue answered 2/10, 2016 at 17:48 Comment(2)
This might fail in some cases, see this: medium.com/opsops/…Contrastive
this is not the address ansible connects to. It might match, but it does not have toFlytrap
H
35

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"
}
Horrific answered 9/6, 2020 at 8:28 Comment(2)
Ansible 2.0 has deprecated the “ssh” from ansible_ssh_host. And if ansible_host contains hostname instead of IP, ansible_ssh_host will also do.Flytrap
I'm currently using version 2.10 of ansible and this code works as charm in my case.Horrific
L
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 ッ

Lettielettish answered 25/1, 2017 at 13:50 Comment(3)
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.Tactics
This probably used to work in the past but with Ansible 2.7 this variable is undefined.Coburg
this is not the address ansible connects to. It might match, but it does not have toFlytrap
P
14

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"
}
Propertius answered 16/1, 2020 at 9:52 Comment(2)
ansible_host might contain hostnameFlytrap
Like @Flytrap said, ansible_host is whatever you defined in your inventory, so this does not always print the IP address.Kurtz
C
13

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])
Contrastive answered 16/12, 2019 at 7:22 Comment(1)
This should be the accepted answer here, per the documentationKurtz
F
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

Florencio answered 11/1, 2019 at 7:30 Comment(3)
Another service url that returns the same is: https://ipecho.net/plainBosch
@PaulParker ipecho.net/plain seems KO or ask api token ... ifconfig.me better and stable service since years :+1Fruitless
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.Bosch
B
6

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.

Buckler answered 20/4, 2018 at 16:16 Comment(12)
And what if DNS is not used in the environment?Cologne
(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.Buckler
Abs what if ansible_host is not the IP address of the host in question?Cologne
this is not "and what". It's just "what" cause your previously asked question isn't counted, don't forget.Buckler
"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 muchBuckler
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?Cologne
I have no clue what you are calling as "real IP address". Do you know some unreal ones?Buckler
Let us continue this discussion in chat.Buckler
Real IP address is the one set on the target itself. Unlike the one you might be accessing server with.Cologne
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 agoBuckler
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?Cologne
Your inconsistency your mean?Buckler
M
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.

Meson answered 22/4, 2017 at 6:3 Comment(5)
This does not always work. For me ipify_public_ip variable is emptyMarcus
For AWS, inventory_hostname will be the ip address.Alee
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.Neanderthal
@BerenddeBoer Wrong. inventory_hostname is whatever is set in the inventory. It could be a host name as set in .ssh/config.Aaronson
@Neanderthal 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.Meson
A
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'] }}"
Albertoalberts answered 22/11, 2018 at 7:9 Comment(2)
Some comments by you would improve this answerMarguerite
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.Umbilicate
A
1

This way worked for me:

this_node_ip: '{{ hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2] }}'
Ames answered 3/10, 2022 at 10:59 Comment(0)
B
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']
Bonus answered 24/5, 2022 at 6:53 Comment(0)
T
0

I cannot get ansible_default_ipv4. Actually it would be empty when default route cannot be set.

I use

   - name: IPv4
     ansible.builtin.debug:
       msg:
         ipv4: "{{ ansible_facts['env'].SSH_CONNECTION.split(' ')[2] }}"
Trejo answered 17/12, 2023 at 12:47 Comment(0)
M
0

You can use the below expression.

eg in a task:

  • name: IPv4 ansible.builtin.debug: msg: ipv4: "{{ ansible_facts['default_ipv4']['address'] }}"

In a jinja template just put the below expression where your ip needs to be present

{{ ansible_facts['default_ipv4']['address'] }}

Maynard answered 1/2 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.