在Ansible中检查字符串是否等于和三元运算符

时间:2016-05-11 11:01:50

标签: ansible jinja2

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

#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

我做错了什么?

3 个答案:

答案 0 :(得分:25)

解决!

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

答案 1 :(得分:15)

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

您需要将等于operator-clause括在括号中:

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

这个答案中提到的另外两点:

  • 您使用字符串'true'代替布尔
  • when指令处于错误的缩进级别(您有效地传递了名为when的变量)

答案 2 :(得分:0)

我将详细说明techraf的答案。还有两个要点(when标识和'true'作为字符串而不是布尔值true)。

因此,问题是“我在做什么错?”。答案是:运算符优先级。

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

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

    {{ expose_service == 'NodePort' }}

    这显然是错误的。