Ansible条件语句中整数比较不生效的问题排查
问题原因分析
你遇到的核心问题是错误地将debug模块的任务结果对象当作纯版本值来使用:
- 当你用
debug模块并register: w时,w并不是你看到的那个"55"字符串,而是一个完整的Ansible任务结果对象,结构类似:w: changed: false stdout: "55" stdout_lines: ["55"] ... - 直接对这个对象用
| int过滤器时,Ansible无法将复杂对象转为有效整数,会默认返回0,所以0 < 55永远为true,导致Test result任务始终执行。 - 去掉
| int后,是把整个对象和整数55比较,类型不匹配且值不相等,所以任务会被跳过。
解决方法
有两种简洁的修复方式:
方式一:用set_fact直接计算并存储版本值(推荐)
放弃用debug模块中转,直接用set_fact生成纯整数版本变量,避免多余的对象结构:
- name: Check the version of the current sql database on both dispatchers and save that value. command: /usr/bin/mysql -V changed_when: false register: sqlversion - name: Calculate MySQL main version as integer (e.g. 5.5 → 55) set_fact: mysql_main_version: "{{ sqlversion.stdout.split()[4] | regex_search('[0-9]+\\.[0-9]+') | replace('.','') | int }}" - name: Show the value of the variable. debug: var: mysql_main_version - name: Test result command: w when: mysql_main_version < 55
方式二:如果保留debug注册,需引用stdout字段
如果一定要用debug模块输出并注册,在条件判断时必须取w.stdout(debug模块输出的内容存在stdout字段中)来转成整数:
- name: Check the version of the current sql database on both dispatchers and save that value. command: /usr/bin/mysql -V changed_when: false register: sqlversion - name: Print to the screen the current sql database version. debug: var: "{{ sqlversion.stdout.split()[4] | regex_search('[0-9]+\\.[0-9]+') | replace(\".\",'') }}" register: w - name: Show the value of the variable. debug: var: w - name: Test result command: w when: (w.stdout | int) < 55
验证说明
两种方式都能正确获取到版本整数(比如5.5对应55),此时当版本为55时,55 <55为false,Test result任务会被正确跳过;当版本低于5.5(比如5.4转成54)时,条件成立,任务执行。
内容的提问来源于stack exchange,提问作者Viscosity
相关产品推荐
相关产品推荐

