linux - Ansible 将字符串转换为 bool

标签 linux ansible boolean

我试图询问用户是否希望他们创建的新用户成为 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/

相关文章:

php - 使用PHP脚本执行linux shell命令并在浏览器中显示?

linux - 在 ubuntu 中从 Chroot 内部运行服务器

linux - 在 Postfix 中配置备份邮件中继

kubernetes - Ansible Galaxy 角色安装到特定目录?

Ansible 和库存特定变量

ansible - 当我使用ansible模块expect时,我得到这个消息: The pexpect python module is required

java - 如何在 Java 中将 String 转换为 Boolean,但将 null 与 false 区别对待?

swift 错误 : 'DYLD_BOOL' is not convertible to 'bool'

c - 使用 .sh 脚本测试 C 程序时显示输入

PowerShell boolean 值