Jack
Jack

Reputation: 1372

ansible templating : if conditions

I'm creating a role and i'm running this playbook on two machines and I have a template that im using this variable

--cluster.peers {{ cluster_peers_addr }} 

when i run the playbook host A config should get host B ip address here and Host B should get host A ip address.

I can do if condition like this

{% if inventory_hostname == "hosta" %}
--cluster.peers 1.1.1.1
else
--cluster.peers 2.2.2.2
{% endif %}

but I don't like this solution, please suggest better approach

Upvotes: 0

Views: 66

Answers (1)

user2599522
user2599522

Reputation: 3215

If hostA and hostB are in a group, you could do something like

(groups["my-group"] | diff(inventory_hostname))[0].ansible_default_ipv4.address

This will be buggy when you have more than two hosts in the group, but you can either loop over that, or do something else thats clever. YMMV.

Upvotes: 1

Related Questions