Ansible中bool过滤器对非空字符串返回false的问题排查
问题描述
执行以下Ansible任务时,通过redis-cli获取Redis集群信息,使用regex_search匹配cluster_known_nodes:[1-9]+并将结果赋值给cluster_created变量,期望当cluster_known_nodes值为非0数字时,该变量转布尔值为true,但实际debug显示为false。
任务代码
- name: Get cluster info from one of the nodes command: > redis-cli --user default -h {{ hostvars[groups['masters'][0]].ansible_host }} CLUSTER INFO register: cluster_info_output ignore_errors: true - name: Set fact indicating if the cluster is already created set_fact: cluster_created: "{{ cluster_info_output.stdout | regex_search('cluster_known_nodes:[1-9]+') }}"
Debug任务
- name: debug cluster_created debug: var: cluster_created | bool
执行结果
TASK [redis.cluster : Set fact indicating if the cluster is already created] **************************************************** ok: [server1 -> localhost] => { "ansible_facts": { "cluster_created": "cluster_known_nodes:3" }, "changed": false } TASK [redis.cluster : debug cluster_created] ************************************************************************************ ok: [server1 -> localhost] => { "cluster_created | bool": false }
原因分析
问题出在Ansible的bool过滤器转换规则上:
- 只有当字符串是
"true"(大小写不敏感)、"yes"、"1"这类明确表示真值的内容时,bool过滤器才会返回true。 - 当前
regex_search返回的是完整匹配字符串"cluster_known_nodes:3",这个字符串既不是纯数字,也不属于上述真值字符串范畴,所以bool过滤器会将其判定为false。
解决方案
需要修改regex_search的用法,只提取cluster_known_nodes:后面的数字部分,再进行布尔转换。可以通过正则分组捕获来实现:
修改后的set_fact任务:
- name: Set fact indicating if the cluster is already created set_fact: cluster_created: "{{ cluster_info_output.stdout | regex_search('cluster_known_nodes:([1-9]+)', '\\1') }}"
这里\\1表示引用正则表达式中第一个捕获组(也就是括号里匹配到的数字),最终cluster_created会被赋值为"3",再通过bool过滤器转换时,就会得到true。
也可以用regex_replace实现相同效果:
- name: Set fact indicating if the cluster is already created set_fact: cluster_created: "{{ cluster_info_output.stdout | regex_replace('.*cluster_known_nodes:([1-9]+).*', '\\1') }}"
修改后再执行debug任务,结果会显示"cluster_created | bool": true。
内容的提问来源于stack exchange,提问作者Behnia FB
相关产品推荐
相关产品推荐

