Adding a Prefix and Suffix to a each element of a list via Jinja2 templates


Example of a list of IP addresses which need to be have a protocol e.g. https: as prefix and a port number e.g. 5000 as suffix in order to configure a file or use the list to query the endpoint.

- hosts: localhost
  gather_facts: false
    endpoints: [,,]
    - name: 'endpoints with protocol https and port 5000'
        var: updated_endpoints
         protocol: https://
         port: :5000
         updated_endpoints: |
               [protocol] | product(endpoints) | map('join') |
               product([port]) | map('join') | list


Initial Reference which provides the idea of using product. I combined the logic to make the prefix and suffix logic work together.

Thought it might be helpful for people playing with lists and adding things to each element.

1 Like

There are lots of ways to do things with Ansible :slight_smile:

Iā€™d have probably done this using the regex_replace filter, for example:

- name: Endpoints with protocol https and port 5000
    var: updated_endpoints
    updated_endpoints: >-
      endpoints |
      map('ansible.builtin.regex_replace', '^', 'https://') |
      map('ansible.builtin.regex_replace', '$', ':5000')
1 Like