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

**URL:** <https://forum.ansible.com/t/adding-a-prefix-and-suffix-to-a-each-element-of-a-list-via-jinja2-templates/5260>\
**Category:** Guides, FAQs & Howtos\
**Tags:** howto\
**Created:** [May 2, 2024, 1:27pm UTC](https://forum.ansible.com/t/adding-a-prefix-and-suffix-to-a-each-element-of-a-list-via-jinja2-templates/5260 "2024-05-02T13:27:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ShanDesai](https://avatars.discourse-cdn.com/v4/letter/s/838e76/32.png) [@ShanDesai](https://forum.ansible.com/u/ShanDesai)\
**Post date:** [May 2, 2024, 1:27pm UTC](https://forum.ansible.com/t/adding-a-prefix-and-suffix-to-a-each-element-of-a-list-via-jinja2-templates/5260/1 "2024-05-02T13:27:39Z")

</div>

## 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.

```auto
---
- 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.

> **[Ansible: Add a prefix or suffix to all items of a list](https://www.itix.fr/blog/ansible-add-prefix-suffix-to-list/)**
>
> Recently, in one of my Ansible playbooks I had to prefix all items of a list with a chosen string.

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

---

<div class="post-metadata">

**Author:** ![chris](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/chris/32/293_2.png) [@chris](https://forum.ansible.com/u/chris)\
**Post date:** [May 2, 2024, 2:00pm UTC](https://forum.ansible.com/t/adding-a-prefix-and-suffix-to-a-each-element-of-a-list-via-jinja2-templates/5260/2 "2024-05-02T14:00:49Z")

</div>

There are lots of ways to do things with Ansible 🙂

I’d have probably done this using [the regex\_replace filter](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/regex_replace_filter.html), for example:

```yaml
- 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')
```
