检查字符串是否等于 Ansible 中的三元运算符
Check if strings are equals and ternary operator in Ansible
在我的剧本中,我有这个:
#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
。
我做错了什么?
已解决!
service_type: "{{ 'NodePort' if expose_service == 'true' else 'ClusterIP' }}"
在您的示例中,您将三元过滤器应用于 '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
的变量)
我将在 的回答中详细说明第一点。另外两点(when
identation 和 'true'
as string instead of boolean true
)仍然成立。
所以,问题是 "What am I doing wrong?"。答案是:运算符优先级。
在{{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }}
中,过滤器首先应用于'true'。因此,Ansible 评估:
{{ expose_service == ('true' | ternary('NodePort', 'ClusterIP')) }}
'true' | ternary('NodePort', 'ClusterIP') = 'NodePort'
因为引用的非空字符串仍然是布尔非假。
→ {{ expose_service == 'NodePort' }}
这显然是错误的。
在我的剧本中,我有这个:
#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
。
我做错了什么?
已解决!
service_type: "{{ 'NodePort' if expose_service == 'true' else 'ClusterIP' }}"
在您的示例中,您将三元过滤器应用于 '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
的变量)
我将在 when
identation 和 'true'
as string instead of boolean true
)仍然成立。
所以,问题是 "What am I doing wrong?"。答案是:运算符优先级。
在{{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }}
中,过滤器首先应用于'true'。因此,Ansible 评估:
{{ expose_service == ('true' | ternary('NodePort', 'ClusterIP')) }}
'true' | ternary('NodePort', 'ClusterIP') = 'NodePort'
因为引用的非空字符串仍然是布尔非假。→
{{ expose_service == 'NodePort' }}
这显然是错误的。