首页 > 解决方案 > 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"
    }

如您所见,我总是得到错误的回应。

标签: linuxansibleboolean

解决方案


我认为“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 。最后,避免==.


推荐阅读