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

Scenario

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
  vars:
    endpoints: [192.168.1.10, 192.168.2.10, 192.168.3.10]
  tasks:
    - name: 'endpoints with protocol https and port 5000'
      ansible.builtin.debug:
        var: updated_endpoints
      vars:
         protocol: https://
         port: :5000
         updated_endpoints: |
           {{ 
               [protocol] | product(endpoints) | map('join') |
               product([port]) | map('join') | list
           }}

Reference

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
  ansible.builtin.debug:
    var: updated_endpoints
  vars:
    updated_endpoints: >-
      endpoints |
      map('ansible.builtin.regex_replace', '^', 'https://') |
      map('ansible.builtin.regex_replace', '$', ':5000')
1 Like