sashaegorov
sashaegorov

Reputation: 1862

Ansible nodes IPs as the one string

I use Vagrant with Ansible. In my playbook I have the following variable:

seeds: '192.168.56.11,192.168.56.12'

192.168.56.11 and 192.168.56.12 here are IP addresses of multi-machine Vagrant configuration.

Can I do my configuration more flexible using Ansible i.e. can Ansible compose this string programmatically for me?

Upvotes: 1

Views: 182

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56987

You can use Jinja2 to template out your variable from other variables.

So if we have a list of things like this:

seeds:
 - 192.168.56.11
 - 192.168.56.12

We can turn that into a comma delimited string by looping through it with something like this:

seeds_string: '{% for seed in seeds %} {{ seed }}{% if not loop.last %},{% endif %}{% endfor %}'

As for getting the IP addresses of hosts in your inventory we can access facts about other hosts than the one being configured by using the groups and hostvars magic variables.

So to get the IP addresses of all hosts in the inventory we could use something like:

{% for host in groups['all'] %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}

Combining this together we can then do something like this:

seeds: '{% for host in groups['all'] %} {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}{% if not loop.last %},{% endif %}{% endfor %}'

Upvotes: 1

Related Questions