Ansible 将字符串转换为布尔值

Ansible casting string to bool

我正在尝试询问用户是否希望他们正在创建的新用户成为 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"
    }

如您所见,我总是收到错误的回复。

"Y/N" 在 Ansible 中不会自动转换为布尔值。 "Y""N" 都是简单的非空字符串,将被计算为 True。解决方法很简单。测试字符串,例如

    - debug:
        msg: User is sudoer
      when: is_sudoer|lower == 'y'

有关“truthie/falsie”的详细信息,请参见下文。给定列表

    list1:
      - true
      - yes
      - Y
      - y
      - x
    list2:
      - false
      - no
      - N
      - n
      - x

测试 truthy of list1

    - debug:
        msg: "{{ item }} is Truthy [{{ item is truthy }}]"
      loop: "{{ list1 }}"

给予

  msg: True is Truthy [True]
  msg: True is Truthy [True]
  msg: Y is Truthy [True]
  msg: y is Truthy [True]
  msg: x is Truthy [True]

list2

    - debug:
        msg: "{{ item }} is Truthy [{{ item is truthy }}]"
      loop: "{{ list2 }}"

给予

  msg: False is Truthy [False]
  msg: False is Truthy [False]
  msg: N is Truthy [True]
  msg: n is Truthy [True]
  msg: x is Truthy [True]

测试 falsy of list1

    - debug:
        msg: "{{ item }} is Falsy [{{ item is falsy }}]"
      loop: "{{ list1 }}"

给予

  msg: True is Falsy [False]
  msg: True is Falsy [False]
  msg: Y is Falsy [False]
  msg: y is Falsy [False]
  msg: x is Falsy [False]

list2

    - debug:
        msg: "{{ item }} is Falsy [{{ item is falsy }}]"
      loop: "{{ list2 }}"

给予

  msg: False is Falsy [True]
  msg: False is Falsy [True]
  msg: N is Falsy [False]
  msg: n is Falsy [False]
  msg: x is Falsy [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 过滤器解析为布尔值 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) 提示符下仅键入回车键)在 when 时将为 False。最后,避免 ==.