我试图询问用户是否希望他们创建的新用户成为 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 中总是评估为 true。
这是我得到的输出:
ansible-playbook manageUsers.yml
Is the new user a sudoer (Y/N)?: y
...
TASK [debugTruth] **********************************************
skipping: [localhost]
TASK [debugFalse] **********************************************
ok: [localhost] => {
"msg": "Statement False"
}
如你所见,我总是得到错误的回复。
最佳答案
I thought "y","Y","yes" etc always evaluated to true in the ansible.
该说法不正确,您可以在此处看到:https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/filter/core.py#L76通过过滤器解析为 boolean true 的值是字符串“1”、“on”、“yes”和“true”(不区分大小写)或数字 1(因此,NOT“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 键)在 when 中将为 False。最后,避免使用 ==
。
关于linux - Ansible 将字符串转换为 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68893629/