Developer

last person joined: 3 days ago 

Expand all | Collapse all

Coding help with Jinja2 templates

  • 1.  Coding help with Jinja2 templates

    Posted Jul 07, 2020 12:52 PM

    Getting some good progress with building OS CX configs, 

     

    I wanted to see if anyone knows how I can test if a variable is present. 

     

    I have an if statement in a template to check if something is defined.

     

    #--interfaces.j2--#

    {% if item.lag is defined and item.lag|length >0 %}
    lag {{ item.lag }}
    {% endif %}

     

    #--host_vars--#

     

    physical_links:
    - { port: 1/1/1, enabled: 'yes', mtu: 9000, lag: , peer: CoreCX, udld: 'no', rg: 'no',}

     

    but the output either fails, or is considered to have something in it.

     

    I've tried a few items but no success

     

    {% if item.lag is defined and is not null %}

     

    Any ideas?

     



  • 2.  RE: Coding help with Jinja2 templates

    Posted Jul 07, 2020 03:15 PM

    Hi,

     

    I believe that you just need another condition to check if the object is none object.

     

    You seem to have defined a list in variable 'physical_links'. The following template will iterate through elements of the variable and will check the following

      1) if lag is defined

      2) if lag is defined will check if its not NoneType,

      3) if lag is defined and not none, checks if length > 0.

     

    Variable:

     

    physical_links:
    - {lag: 'abc'}
    - {lag: ''}
    - {}
    - {lag: }

     

     

    Jinja2 Template:

     

    {% for item in physical_links %}
    {% if item.lag is defined and item.lag is not none and item.lag|length %}
    lag {{ item.lag }}
    {% endif %}
    {% endfor %}

     

     

    Rendered Output:

     

    lag abc

     

     

    Thanks,

    Karthik