#jinja2: lstrip_blocks: True
{{ ansible_managed | comment }}
{% for tunnel in vpn_connections %}
{%   if item in tunnel.hosts %}
{%     set otherhost = tunnel.hosts[item].hostname | d((hostvars[item] | d({})).ansible_host | d(item)) %}
{%     set rightid = tunnel.hosts[item].rightid | d(otherhost) %}
{%     for host in tunnel.hosts %}
{%       if host == inventory_hostname or host == ansible_host %}
{%         set thishost = host %}
{%         set host = tunnel.hosts[host].hostname | d((hostvars[host] | d({})).ansible_host | d(host)) %}
{%         set leftid = tunnel.hosts[thishost].leftid | d(host) %}
conn {{ tunnel.name ~ '-' if 'name' in tunnel and tunnel.name else '' }}{{ host }}-to-{{ otherhost }}
  left={{ host }}
  leftid={{ host | vpn_ipaddr | ternary('','@') }}{{ leftid }}
{%         if tunnel.hosts[host] is mapping and 'subnets' in tunnel.hosts[host] %}
  leftsubnets={
{%-          for subnet in tunnel.hosts[host].subnets -%}
{{ subnet }}
{%- if not loop.last -%},{%- endif -%}
{%-          endfor -%}
}
{%         endif %}
{%       endif %}
{%     endfor %}
  right={{ otherhost }}
{%     if tunnel.auth_method == 'psk' %}
  rightid={{ otherhost | vpn_ipaddr | ternary('','@') }}{{ rightid }}
{%     endif %}
{%     if tunnel.hosts[item] is mapping and 'subnets' in tunnel.hosts[item] %}
  rightsubnets={
{%-      for subnet in tunnel.hosts[item].subnets -%}
{{ subnet  }}
{%- if not loop.last -%},{%- endif -%}
{%-      endfor -%}
}
{%     endif %}
  ikev2={{ __vpn_ikev2 }}
{# options key is name of tunnel parameter #}
{# options value is name to use in ipsec config #}
{%     set options = {'auto': 'auto', 'dpdaction': 'dpdaction', 'dpddelay': 'dpddelay',
                      'dpdtimeout': 'dpdtimeout', 'esp': 'esp', 'ike': 'ike',
                      'ikelifetime': 'ikelifetime', 'leftupdown': 'leftupdown',
                      'retransmit_timeout': 'retransmit-timeout',
                      'salifetime': 'salifetime', 'type': 'type'} %}
{%     set needs_quotes = {'leftupdown': 'leftupdown'} %}
{%     for key, ipsec_key in options.items() %}
{%       if key in tunnel %}
{%         set val = tunnel[key] %}
{%         if key in needs_quotes and val is not none %}
  {{ ipsec_key }}="{{ val }}"
{%         else %}
  {{ ipsec_key }}={{ val }}
{%         endif %}
{%       endif %}
{%     endfor %}
{%     if tunnel.auth_method == 'psk' %}
  authby=secret
{%     endif %}
{%     if tunnel.auth_method == 'cert' %}
  rightid=%fromcert
  leftrsasigkey=%cert
{%       for host in tunnel.hosts %}
{%         if host == inventory_hostname or host == ansible_host %}
  leftcert={{ tunnel.hosts[host].cert_name | d((hostvars[host] | d({})).cert_name) }}
{%         endif %}
{%       endfor %}
  rightrsasigkey=%cert
{%     endif %}
{%   endif %}
{% endfor %}
