How to get another host's IP/Hostname from the inventory as a variable?

Hi all,

I’ve had a hard time finding the answer to this question online. Hoping someone can help here pls:

What variable can I use to access the “mongodb” IP address from my inventory file?

ie: What variable can I use: {{ ?? }} that would == ?




Thanks so much!

Did you try groups['mongodb'][0] or groups.mongodb[0] ?

Using this task

    - name: mongodb host
        msg: "{{ groups['mongodb'][0] }}"

Gives this output:

TASK [mongodb host] *************************************
ok: [] => {
    "msg": ""


Another suggestion would be to use inventory_hostnames lookup plugin:

- name: test
  hosts: localhost
  connection: local
  gather_facts: false
    - ansible.builtin.debug:
        msg: "{{ item }}"
      with_inventory_hostnames: mongodb
$ ansible-playbook -i ./inv ./pbtest.yml
TASK [ansible.builtin.debug] ***********************************************************************************************************************************************************************************************************************************************************************************************
Friday 03 November 2023  11:40:57 +0100 (0:00:00.009)       0:00:00.009 ******* 
ok: [localhost] => (item= => {
    "msg": ""

Thank you, devnull, this works great!
…Your solution is perfect for my scenario – since I need to only use the first host entry.

…Others who are reading this may also be interested in ptn’s solution, in case they need to process for each host entry. Thank you also to ptn!


Hi @chatguy

good to hear it’s working fine for you :+1:t3: