【问题标题】:Check if strings are equals and ternary operator in Ansible检查 Ansible 中的字符串是否等于和三元运算符
【发布时间】:2016-05-11 11:01:50
【问题描述】:

在我的剧本中,我有这个:

#More things
- include: deploy_new.yml
  vars:
    service_type: "{{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }}"
    when: service_up|failed

expose_service 为真时,我希望将service_type 设置为NodePort,否则设置为ClusterIP

但是,service_type 在所有情况下都设置为False

我做错了什么?

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    解决了!

    service_type: "{{ 'NodePort' if expose_service == 'true' else 'ClusterIP' }}"
    

    【讨论】:

    • 在我看来,这个答案并没有回答关于三元的问题。这更像是一种解决方法
    【解决方案2】:

    在您的示例中,您将三元过滤器应用于'true' 字符串。实际上,您正在将 expose_service 的值与字符串 'NodePort' 进行比较,并始终在结果中得到 false

    您需要将相等运算符子句括在括号中:

     - include: deploy_new.yml
       vars:
         service_type: "{{ (expose_service == true) | ternary('NodePort', 'ClusterIP') }}"
       when: service_up|failed
    

    此答案中提到的其他两点:

    • 您使用字符串'true' 而不是布尔值
    • when 指令的缩进级别错误(您实际上传递了名为 when 的变量)

    【讨论】:

      【解决方案3】:

      我将在techraf 的回答中详细说明第一点。另外两点(when 标识和'true' 作为字符串而不是布尔值true)仍然有效。

      所以,问题是“我做错了什么?”。答案是:运算符优先级。

      {{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }} 中,过滤器首先应用于“真”。因此,Ansible 评估:

      • {{ expose_service == ('true' | ternary('NodePort', 'ClusterIP')) }}
      • 'true' | ternary('NodePort', 'ClusterIP') = 'NodePort' 因为引用的非空字符串仍然是布尔非假。

        {{ expose_service == 'NodePort' }}

        这显然是错误的。

      【讨论】:

        猜你喜欢
        • 2015-02-04
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 2020-07-20
        • 2017-05-24
        • 1970-01-01
        • 2021-10-06
        • 2018-05-23
        相关资源
        最近更新 更多