简体   繁体   中英

How to call/include an ip address from inventory file to ansible playbook

---

- hosts: pupservers
  sudo: yes

  tasks:
  - command: bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 2  --partitions 1 --topic my-replicated-topic
    with_inventory_hostnames: zookservers

In the above code I need call an ip address of another variable declared as zookservers in inventory file instead of local host.

I tried different things but nothing worked for me , tried to call {{ ansible_ssh_host }} , {{ zookservers[ansible_ssh_host] }}

Thanks in advance.

{{ hostvars['zookservers']['ansible_eth0']['ipv4']['address'] }}

The problem is, your play is limited to the group pupservers . Ansible will only know facts about hosts it is supposed to run something on. zookservers is a different group not involved in your play, so Ansible will not connect to these hosts and not collect facts (including the ip)

To make Ansible gather facts on the hosts of the group zookservers you can simply add an empty play to your playbook. So your playbook would look like this:

- hosts: zookservers

- hosts: pupservers
  sudo: yes

  tasks:
  - ...

Fact caching would be another option but I guess this should suit your needs.

In your loop then you should be able to get the IP with

{{ hostvars[item].ansible_eth0.ipv4.address }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM