Advanced join for an Ansible use case

Viewed 49

I have the following pool configuration in Ansible:

_pool_config: "{{ (environment_hosts | default(['localhost'])) | join(':2100,') }}:2100{% if ssl_enabled | bool %},sslSettings=TLS{% endif %}"

Which on the server resolves to that:

server1:2100,server2:2100

I am now adding an additional process on server1 and server2 listening on port 2200 so would like to change the above to resolve to this instead:

server1:2100,server1:2200,server2:2100,server2:2200

And need some help amending the join please

I'm using Ansible 2.3

1 Answers

There are more options:

    env_hosts: [server1, server2]
    env_ports: [2100, 2200]
    _pool_config: "{{ env_hosts|default(['localhost'])|
                      product(env_ports)|
                      map('join', ':')|
                      join(',') }}"

gives the expected result

_pool_config: server1:2100,server1:2200,server2:2100,server2:2200

  • The Jinja template below gives the same result
    env_hosts: [server1, server2]
    env_ports: [2100, 2200]
    _pool_config: |-
      {% for server in  env_hosts|default(['localhost']) %}
      {% for port in  env_ports %}
      {{ server }}:{{ port }}{% if not loop.last %},{% endif %}
      {%- endfor %}
      {% endfor %}

  • You can write a filter on your own. For example,
shell> cat filter_plugins/my_product.py
from itertools import product


def my_product(x, y):
    return product(x, y)


class FilterModule(object):

    def filters(self):
        return {
            'my_product': my_product,
        }

Then, use the filter my_product

    env_hosts: [server1, server2]
    env_ports: [2100, 2200]
    _pool_config: "{{ env_hosts|default(['localhost'])|
                      my_product(env_ports)|
                      map('join', ':')|
                      join(',') }}"
Related