linux - Ansible 将字符串转换为布尔值
问题描述
我试图询问用户是否希望他们创建的新用户成为 sudor。
- 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(false)|bool == true
- name: debugFalse
debug:
msg: "Statement False"
when: is_sudoer|default(false)|bool == false
但是,无论我输入什么,脚本始终默认为 false。我认为“y”、“Y”、“yes”等在ansible中总是被评估为真。
这是我得到的输出:
ansible-playbook manageUsers.yml
Is the new user a sudoer (Y/N)?: y
...
TASK [debugTruth] **********************************************
skipping: [localhost]
TASK [debugFalse] **********************************************
ok: [localhost] => {
"msg": "Statement False"
}
如您所见,我总是得到错误的回应。
解决方案
我认为“y”,“Y”,“yes”等总是在ansible中评估为真。
该声明不正确,您可以在此处看到:https ://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/filter/core.py#L76过滤器解析为布尔值 true 的值是字符串“1”、“on”、“yes”和“true”(不区分大小写)或数字 1(因此,不是“y”):
if isinstance(a, string_types):
a = a.lower()
if a in ('yes', 'on', '1', 'true', 1):
return True
return False
此外,按照@P 的评论建议,实现条件的更正确方法是
- name: debugTruth
debug:
msg: "Statement True"
when: is_sudoer | bool
- name: debugFalse
debug:
msg: "Statement False"
when: not is_sudoer | bool
default(false)
不需要,因为空字符串(即用户在 (Y/N) 提示符下仅键入 enter 键)将在 time 中为 False 。最后,避免==
.
推荐阅读
- mysql - MySQL 'IS NULL' 在 JOIN 查询中将值设置为 NULL
- scala - 如何通过在火花中使用 IN 子句传递另一个列值来检索列值
- c# - 我怎样才能重构它,以便具有 CardStack 脚本的多个游戏对象独立递增
- c# - C# 如何将 unHex 转换为字符串
- sharepoint - Azure 数据工厂和个人或组 SharePoint 数据类型
- javafx - JavaFX CSS 选择框和组合框
- wordpress - 在父类别上显示 Woocommerce 子类别的描述
- javascript - 谷歌表格电子邮件发送功能不起作用
- vue.js - vue-cli:为什么在 npm run build 后我在 Devtools 中看到非缩小的 javascript 代码?
- python - 在 Folium 中具有时间控制的 WMS 层