Ansible vars_prompt输入字符串转bool始终返回false问题求助
问题原因
- Ansible通过
vars_prompt获取的用户输入默认是原始字符串类型,内置bool过滤器仅会对字面值为True(首字母大写)、1的字符串返回真值,你输入的小写y、yes、全大写Y/YES都不符合bool过滤器的真值匹配规则,所以转换结果始终为false。
修复方案
方案1:直接声明变量类型为布尔值
在vars_prompt配置中添加type: bool参数,Ansible会自动识别常用的布尔类输入(包括y/Y/yes/YES/true/True/1等)并转换为对应的布尔值,修改后的playbook如下:
- hosts: localhost vars_prompt: - name: is_sudoer prompt: Is the new user a sudoer (Y/N)? private: no type: bool # 新增此行声明变量类型 tasks: - name: debugTruth debug: msg: "Statement True" when: is_sudoer|default(false) - name: debugFalse debug: msg: "Statement False" when: not is_sudoer|default(false)
方案2:自定义真值匹配逻辑
如果需要更灵活的匹配规则,可以手动写判断逻辑,兼容各类自定义输入:
- hosts: localhost vars_prompt: - name: is_sudoer prompt: Is the new user a sudoer (Y/N)? private: no tasks: - name: debugTruth debug: msg: "Statement True" when: is_sudoer|default('n')|lower in ['y','yes','true','1'] - name: debugFalse debug: msg: "Statement False" when: is_sudoer|default('n')|lower not in ['y','yes','true','1']
内容的提问来源于stack exchange,提问作者Ruth Edges
相关产品推荐
相关产品推荐

