Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to manipulate list variable in Jinja2 template?

I’ve created a role which stores the unreachable hosts in a variable:

- block:
  - set_fact:
      unreachable_hosts: "{{ ansible_play_hosts_all|difference(ansible_play_hosts) }}"
  - debug:
      var: unreachable_hosts
  run_once: true

Depending on the amount of unreachable hosts this returns something like this:

"unreachable_hosts": [
    "server001",
    "server003"
]

In another role I’m creating an HTML file with Jinja2 template. In that HTML file I’d like to list all unreachable hosts per line (in a table row). I tried to make a for-loop in my HTML code like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  <tr>
    <td colspan="6">
        <b> Unreachable Servers: </b> <br>
          <ul>
          {% for items in unreachable_hosts %}
            <li font color="red">{{ unreachable_hosts }} </li>
            {% endfor %}
         </ul>
    </td>
  </tr>

But this creates an output like this:

Unreachable Servers:

- ['server001', 'server003']
- ['server001', 'server003']

I’d like to manipulate the output to look like this:

Unreachable Servers:

- server001
- server003

>Solution :

In your loop, items is an item in the unreachable_hosts list. To output one of the items being iterated over:

{% for items in unreachable_hosts %}
  <li font color="red">{{ items }} </li>
{% endfor %}

(I would also rename items to item (singular) since it contains a single item.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading