{% import "routeros7.bgp-macro.j2" as bgpcfg %}

{% for vname,vdata in vrfs.items() %}
{#
    First of all, need to add the vrf to the default instance (for VPNv4)
#}
/routing/bgp/vpn add label-allocation-policy=per-vrf vrf={{ vname }} route-distinguisher={{ vdata.rd }} import-route-targets={{ vdata.import|join(',') }} export-route-targets={{ vdata.export|join(',') }}

{#
    Create BGP template/instance
#}
/routing/bgp/template add name=vrf_{{ vname }} as={{ bgp.as }} output.network=bgp-networks-{{ vname }} vrf={{ vname }} routing-table={{ vname }} output.redistribute=connected,bgp,copy

{% if bgp.router_id|ipv4 %}
/routing/bgp/template set vrf_{{ vname }} router-id={{ bgp.router_id }}
{% endif %}

{% if 'ospf' in vdata %}
/routing/bgp/template set vrf_{{ vname }} output.redistribute=([get vrf_{{ vname }} output.redistribute],"ospf")
{% endif %}

{#
    And now the peers...
#}
{%   for n in vdata.bgp.neighbors|default([]) %}
{%     for af in ['ipv4'] if n[af] is defined %}
{{       bgpcfg.neighbor(n,n[af],vdata.bgp,'vrf_'+vname) }}
{%     endfor %}
{%   endfor %}

{% endfor %}
