How do I append to each item in a list of strings?

Andrew picture Andrew · Nov 9, 2015 · Viewed 16k times · Source

I have a list of strings containing IP addresses. I want to append a port number to each of them. In python I would do it something like this:

ip_list = [(ip + ":" + port) for ip in ip_list]

...but Jinja doesn't support list comprehensions. At the moment I'm kludging the problem by building a new list one item at a time:

{%- set ip_list = magic() %}
{%- set new_ip_list = [] %}
{%- for ip in ip_list %}
  {%- do new_ip_list.append(ip + ":" + port) %}
{%- endfor %}

This is ugly and irritating in the middle of a template, and it feels like there should really be a better way to get the job done. Preferably a one-liner.

While I know this can be done with custom filters, I'm supplying a template to software I did not write (saltstack), so they are (as far as I know) unavailable to me.

Answer

simohe picture simohe · Sep 4, 2020

my suggestion for ansible:

magic() | map('regex_replace', '$', ':'~port) | list

map: apply the filter regex_replace to each list element (like listElement | replace('$', ':'~port))
replace: replace end of string by : and port (so append it)
list: convert generator to list

Using a regexp is a overkill, but my other tries were even more. Unfortunately regex_replace does not exist in normal jinja.