Simply  Seth
Simply Seth

Reputation: 3506

ansible jinja2 concatenate IP addresses

I would like to cocatenate a group of ips into a string.

example ip1:2181,ip2:2181,ip3:2181,etc

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

I have the above code, but can't seem to quite figure out how to concatenate into a string.

searching for "Jinja2 concatenate" doesn't give me the info I need.

Upvotes: 12

Views: 10867

Answers (3)

Def_Os
Def_Os

Reputation: 5467

You can use the 'extract' filter for this (provided you use ansible>=2.1):

{{ groups['zookeeper'] | map('extract', hostvars, ['ansible_eth0', 'ipv4', 'address']) | join(',') }}

More info: http://docs.ansible.com/ansible/playbooks_filters.html#extracting-values-from-containers

Upvotes: 11

saranicole
saranicole

Reputation: 2483

Found a similar solution at https://adamj.eu/tech/2014/10/02/merging-groups-and-hostvars-in-ansible-variables/ .

I did a set_fact using a groups variable as suggested in the post:

- hosts: all
  connection: local
  tasks:
    - set_fact:
        fqdn_list: |
          {% set comma = joiner(",") %}
          {% for item in play_hosts -%}
              {{ comma() }}{{ hostvars[item].ansible_default_ipv4.address }}
          {%- endfor %}

This relies on joiner, which has the advantage of not having to worry about the last loop conditional. Then with set_fact I can make use of the new string in later tasks.

Upvotes: 6

udondan
udondan

Reputation: 60079

Updated this answer, because I think I misunderstood your question.

If you want to concatenate the IP's of each host with some string, you can work with the loop controls, to check if you're in the last iteration:

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

Old answer:

The word you're looking for is join:

{{ hostvars[host]['ansible_eth0']['ipv4']['address'] | join(", ") }}

Upvotes: 15

Related Questions