How would you approach this problem? Host1 needs to dynamically know the IP address of Host2

Here's the basic structure of my playbook:

  • Play1 applies to both hosts
  • Play2 applies to Host1

In Play2, I have a task that needs to know the IP address of Host2.

How would you typically handle this? It doesn't seem as though I can register a variable in Play1, as the variable isn't accessible to Host1 in Play2.

Thank you in advance!

Posted Mar 17, 2017, 6:29 PM UTC

88
tastycidr•
{{ hostvars['host2.contoso.com']['ansible_eth0']['ipv4']['address'] }}

As long as you gather facts and know the name of those you want a var from, you can use that method.

2
thomas_stringerOP•

Ah that looks like a good approach. What about in the case of a group? I.e. multiple hosts.

Thanks!

1
tastycidr•

I would need more context on what you mean by that to answer

1
cryonine•
for host in group['group2']

Then perform your logic using group variable instead of a hardcoded host name.

1
stmarier•

I'm a little confused I guess.

If I have a play targeting both hosts, that play is using an inventory file which has a hostname for both hosts. Since I know the hostname, I can just use it directly or query an IP address from DNS, right? (regardless of which play I'm in)

But, I've never run into this problem. My first question would be: why does play2 apply only to host 1? Can I just have play1, and have a task delegated_to host1? (so I still have access to group_vars)?

If I'm just templating a config file for example, I also don't really need to split up plays like this, since I have full jinja inside the file. Like, if you're configuring a kubernetes cluster, and the kubelet config file needs the hostnames of every host in this cluster except iteslf, that's pretty easy with play_hosts.

If I must -- I would suspect that you can just run the setup module on host1 as the first task in play2 and register it as a variable, and then access things about it as needed. I probably wouldn't be very happy with this solution though.

e: You may want to take a look at the delegation section of the docs: http://docs.ansible.com/ansible/playbooks_delegation.html and you'll probably find something that works for you. But as a rule of thumb, groups are really powerful, and if you need to do something gross, there's probably something in the ansible magic variables list that can help.

1
thomas_stringerOP•

Play2 has multiple tasks that only apply to a single host or single group, and not the other hosts in the other group.

1
kkirsche•

Any reason not to use just one play with run once and delegate to to control which host gets a task and if it's ran once or multiple times either in a group or groups

1
tetroxid•

Have the DHCP update the DNS

1