Template funtions for CCC

Fra PerMejdal
Spring til navigation Spring til søgning

Some usefull template funtions for Cisco Catalyst Center / DNAc / DNA Center.

{#
  Function to convert IP/(CIDR|MASK) or IP,(CIDR|MASK) to the network adress
  If IP/(CIDR1|MASK1),(CIDR2|MASK2) then (CIDR2|MASK2) is used.
  The MASK can contain holes, like 255.0.255.0
#}
{%- macro ip_to_net(ip__cidr_or_mask, cidr_or_mask) -%}
 {%- set ip = ip__cidr_or_mask.split('[/]')[0] -%}
 {%- set ip_parts = ip.split('[.]') -%}
 {%- if cidr_or_mask is not defined -%}
  {%- set cidr_or_mask = ip__cidr_or_mask.split('[/]')[1] -%}
 {%- endif -%}
 {%- set subnet_masks = [
[0,0,0,0],
[128,0,0,0],
[192,0,0,0],
[224,0,0,0],
[240,0,0,0],
[248,0,0,0],
[252,0,0,0],
[254,0,0,0],
[255,0,0,0],
[255,128,0,0],
[255,192,0,0],
[255,224,0,0],
[255,240,0,0],
[255,248,0,0],
[255,252,0,0],
[255,254,0,0],
[255,255,0,0],
[255,255,128,0],
[255,255,192,0],
[255,255,224,0],
[255,255,240,0],
[255,255,248,0],
[255,255,252,0],
[255,255,254,0],
[255,255,255,0],
[255,255,255,128],
[255,255,255,192],
[255,255,255,224],
[255,255,255,240],
[255,255,255,248],
[255,255,255,252],
[255,255,255,254],
[255,255,255,255]
 ] -%}
 {%- if cidr_or_mask | int(-1) != -1 -%}
  {%- set mask_parts = subnet_masks[cidr_or_mask] -%}
 {%- else -%}
  {%- set mask_parts = cidr_or_mask.split('[.]') -%}
 {%- endif -%}
 {%- set result = [] -%}
 {%- for i in range(0, 4) -%}
    {%- set result_parts = ip_parts[i] | int // ( 256 - mask_parts[i] | int ) * ( 256 - mask_parts[i] | int ) -%}
    {%- do result.append(result_parts) -%}
  {%- endfor -%}
{{result | join('.')}}
{%- endmacro -%}

{#
  Function to check if IP is ( NET/(CIDR|MASK) or NET,(CIDR|MASK) )
  If NET/(CIDR1|MASK1),(CIDR2|MASK2) then (CIDR2|MASK2) is used.
  The MASK can contain holes, like 255.0.255.0
#}
{%- macro ip_in_net(ip, net, cidr_or_mask) -%}
 {%- set ip = ip.split('[/]')[0] -%}
 {%- if cidr_or_mask is not defined -%}
  {%- set cidr_or_mask = net.split('[/]')[1] -%}
 {%- endif -%}
 {%- set net = net.split('[/]')[0] -%}
 {%- if ip_to_net(ip,cidr_or_mask) == ip_to_net(net,cidr_or_mask) -%}
True
 {%- endif -%}
{%- endmacro -%}