使用jinja2比较版本号

问题描述 投票:0回答:5

我正在使用 jinja2 模板来安装/升级软件包。

逻辑是为当前安装的版本设置一个变量并将其与可用版本进行比较。它工作得很好,但是一旦我们进入 10.x,比较就停止工作了。

是否可以对变量进行强制转换,使其能够正确识别 10.9.8 大于 9.8.7?

谢谢

current_version=['9.8.7']

{% if current_version < '10.9.8' %}

ansible jinja2 salt-stack
5个回答
17
投票

使用Ansible时,有一个特殊的测试版本(Ansible 2.5之前名为

version_compare
):

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

current_version
应该是字符串(它是您示例中的列表)。


2
投票

使用普通的jinja2,没有ansible或其他扩展:

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

通过将每个元素转换为

int
,您可以确保它不会按字典顺序进行比较。


1
投票

与 Jinja2

使用split并且由于序列比较的工作原理,以下应该可以很好地完成:

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

测试:

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 %}

current_version: "9.8.7"
一起给出:

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

1
投票

@cglacet 答案在 Ansible 中生成时很有用并且有效,但是在直接在 Python 中使用 Jinja2 库时它给了我一个错误:

Exception has occurred: TypeError
'>=' not supported between instances of 'generator' and 'generator'

它似乎打印内存位置而不是实际值。我不知道 Ansible 使用什么巫毒魔法来让它工作,但添加

| list
创建了一个实际的整数列表并解决了问题。

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

证明:

{% set sw_version = "7.5.2" %}
{{ sw_version.split('.') }}
{{ ['7', '5', '2'] | int }}
{{ sw_version.split('.') | map('int') }}

输出

['7', '5', '2']
0
<generator object sync_do_map at 0x1223b6270>

修复:

{% set sw_version = "7.5.2" %}

{% if sw_version.split('.') | map('int') | list < '10.9.8'.split('.') | map('int') | list %}
Smaller than to 10.9.8
{% endif %}
{% if sw_version.split('.') | map('int') | list >= '7.5.2'.split('.') | map('int') | list %}
Equal to 7.5.2
{% endif %}
{% if sw_version.split('.') | map('int') | list >= '6.7.5'.split('.') | map('int') | list %}
Bigger than 6.7.5
{% endif %}
{% if sw_version.split('.') | map('int') | list < '7.6.1'.split('.') | map('int') | list %}
Smaller than 7.6.1
{% endif %}
{% if sw_version.split('.') | map('int') | list < '7.5.10'.split('.') | map('int') | list %}
Smaller than 7.5.10
{% endif %}
Smaller than to 10.9.8


Equal to 7.5.2


Bigger than 6.7.5


Smaller than 7.6.1


Smaller than 7.5.10

0
投票

在 saltstack 中你可以使用

pkg.version_cmp

请参阅我的回复:如何比较 salt sls 文件中的版本字符串

© www.soinside.com 2019 - 2024. All rights reserved.