Home > Net >  How to append a string to each item in a list to display it in a template?
How to append a string to each item in a list to display it in a template?

Time:08-24

I'm trying to set a template that pulls in a comma separated list of hosts, and appends a port to each host.

The list, an ansible fact: {{ nodes }}) looks like this:

node1,node2,node3,...,nodeX

And I want the final templated file to look like this:

        node1:1234
        node2:1234
        node3:1234
        ...
        nodeX:1234

My jinja template currently looks like:

"{{ nodes.split(',') | to_nice_json | indent(8) }}"

Which gets me:

        node1,
        node2,
        node3,
        ...,
        nodeX

But, how can I append the port to each node?

I've tried various combinations of

  • {{ nodes.split(',') | join(':1234) | to_nice_json | indent(8) }}
    
  • {{ nodes.split(',') |   (':1234) | to_nice_json | indent(8) }}
    
  • {% for n in {{ nodes.split(,) }} | zip(':1234') %}
                 {{ n[0]n[1] }}
    {% endfor %}
    
  • etc

CodePudding user response:

You will need to use a product in order to repeat the port for each element of the split nodes list.
Then, join back the list of lists with a join in a map.
And finally, join everything together, and indent it.

Here would be your template expression:

{{ nodes.split(',')
   | product([':1234'])
   | map('join')
   | join('\n')
   | indent(8, True)
}}

PS: the second argument to the indent filter instruct it to also indent the first line

first – Don’t skip indenting the first line

Source: https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.indent

CodePudding user response:

Q: "Set a template that pulls in a comma-separated list of hosts, and appends a port to each host."

The final templated file should look like this:

        node1:1234
        node2:1234
        node3:1234
        ...
        nodeX:1234

A: The template is very simple

shell> cat nodes.txt.j2
{% for n in nodes.split(',') %}
  {{ n }}:1234
{% endfor %}

For example, the play

- hosts: localhost
  vars:
    nodes: "node1,node2,node3,nodeX"
  tasks:
    - template:
        src: nodes.txt.j2
        dest: /tmp/nodes.txt

will create the file

shell> cat /tmp/nodes.txt 
  node1:1234
  node2:1234
  node3:1234
  nodeX:1234
  • Related