简体   繁体   中英

Compare version numbers using jinja2

I am using jinja2 template to install/upgrade packages.

The logic was setting a variable for current installed version and compare it with the available version. It was working fine but once we passed in to 10.x, comparison quit working.

Is it possible to cast the variable so it can correctly identify 10.9.8 is greater than 9.8.7?

Thanks

current_version=['9.8.7']

{% if current_version < '10.9.8' %}

There's a special test version_compare :

{% if current_version | version_compare('10.9.8', '<') %}

current_version should be string (it is a list in your example).

With Jinja2

Using split and because of how sequence comparison work, the following should do just fine:

{% if current_version.split('.') | map('int') < '10.9.8'.split('.') | map('int') %}

Test:

Split: {{ current_version.split('.') }}
Split + cast: {{ current_version.split('.') | map('int') }}
---
Is {{ current_version.split('.') | map('int') }} < {{ '10.9.8'.split('.') | map('int') }}?
{% if current_version.split('.') | map('int') < '10.9.8'.split('.') | map('int') %}
Yes
{% endif %}

Which, with current_version: "9.8.7" gives:

Split: ['9', '8', '7']
Split + cast: [9, 8, 7]
---
Is [9, 8, 7] < [10, 9, 8]?
Yes

Using plain jinja2, without ansible or other extensions:

{% if my_version.split('.') | map('int') | list >= [10, 9, 8]  %}

By converting each element to int , you ensure it won't compare lexicographically.

In saltstack you can use pkg.version_cmp

See my reply here: How to compare version strings in salt sls files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM