looping over variables

hello everyone, need some help here.

i have this variable;

vars:
ufw_applications:

  • { name: sample_app, ports: [ { port: 8081, protocol: tcp }, { port: 8082, protocol: udp } ] }

and i want to have a resulting config as;

[app2]
title=“sample_app”
ports=8081/tcp|8082/udp

my template looks like this but is not working. any help is appreciated.

[{{ item.name }}]
title=“{{ item.name }}”
{% if item.port is defined and item.protocol is defined %}
ports={{ item.port }}/{{ item.protocol }}
{% endif %}
{% if item.port is defined and item.protocol is not defined %}
ports={{ item.port }}/tcp|{{ item.port }}/udp
{% endif %}
{% if item.ports is defined %}
ports={{ {{ item.ports.port }}/{{ item.ports.protocol }}|join(‘|’) }}
{% endif %}