如何在Ansible中使用条件设置变量值? [英] How can I use a condition to set a variable value in Ansible?
问题描述
我有两个变量:a
,b
.
我想为变量c
赋值,其依据是:a
或b
包含更大的数值.
I want to assign a value to a variable c
based on which: a
or b
contains greater numerical value.
这是我尝试过的:
- set_fact:
c: "test1"
when: a <= b
- set_fact:
c: "test2"
when: b <= a
看起来它总是将c
设置为test1
而不是test2
.
Look like it always sets c
to test1
not test2
.
推荐答案
-
使用
if-else
表达式:- set_fact: c: "{{ 'test1' if (a >= b) else 'test2' }}"
-
使用三元运算符:
Using ternary operator:
- set_fact: c: "{{ (a >= b) | ternary ('test1', 'test2') }}"
-
使用正确的自己的代码(请参见下面的通知)
Using your own code which is correct (see the notice below)
以上任何一种方法都要求比较中使用的两个变量都具有相同的类型,才能得出合理的结果.并且为了进行数值比较,它们要求两个值都为整数.
Either of the above methods requires both variables used in comparison to be of the same type to give sensible results. And for a numerical comparison, they require both values to be integers.
问题中的代码:
- set_fact: c: "test1" when: a <= b - set_fact: c: "test2" when: b <= a
在两种情况下可以正常工作:
works properly in two cases:
- 两者:
a
和b
是整数 - 两者:
a
和b
是包含数字位数相同的数字的字符串
- both:
a
andb
are integers - both:
a
andb
are strings containing numerical value with the same number of digits
但是它产生意外结果的时间是:
However it produces unexpected result is when:
- 其中一个值是字符串,另一个是整数
- 字符串值包含具有不同位数的数字值
这篇关于如何在Ansible中使用条件设置变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 两者: