Bostjan
Bostjan

Reputation: 1575

Ansible fetch host IP from another group based on defined variable

I would like to fetch IP of a host from another group in inventory file based on variable name.

Example inventory file:

[master]
master-0.example.io
master-1.example.io
master-2.example.io

[replica]
replica-0.example.io master_host=master-0.example.io
replica-1.example.io master_host=master-1.example.io
replica-2.example.io master_host=master-2.example.io

Later in playbook I want to run a command, but for that one I require IP of master (FQDN does not work). I have tried following, but this is not working:

- name: Test run
  shell: "echo {{ ansible_default_ipv4.address }}:{{ port }} {{ hostvars['master_host']['ansible_default_ipv4', 'address'] }}:{{ port }}"

Any idea if there is a way to get this covered? Or if there is any other way to do this - basically what I need is to match master-0 with replica-0 etc. and I do not want to put IPs into inventory file.

Upvotes: 1

Views: 279

Answers (1)

Zeitounator
Zeitounator

Reputation: 44760

hostvars is a hash. Each top entry in the hash is the name of your host in the inventory. To address that hash, your are using the string 'master_host' which does not exist. What you want, is to use the value of the variable master_host for the particular host your are executing the command on.

The 2 possible correct syntaxes are:

  • {{ hostvars[master_host].ansbible_default_ipv4.address }}
  • {{ hostvars[master_host]['ansbible_default_ipv4']['address'] }}

... or any mix between the dot or bracket syntax.

Upvotes: 2

Related Questions