Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 550
Andrew Avatar asked Nov 09 '15 19:11

Andrew


1 Answers

regex_replace can do this. It is available in ansible and saltstack:

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

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

like image 73
simohe Avatar answered Oct 15 '22 01:10

simohe