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.
regex_replace
can do this. It is available in ansible and saltstack:
magic() | map('regex_replace', '$', ':'~port) | list
regex_replace
filter to each list element (like listElement | regex_replace('$', ':'~port)
):
and port (so append it)Using a regexp is overkill, but my other tries were even more so. Unfortunately regex_replace
does not exist in normal jinja.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With