问题描述
如果我这样做:
- set_fact:
NEW_VARIABLE: "{{ VARIABLE | default('default') }}"
和VARIABLE
是空字符串(""
),默认情况下不会触发.
and VARIABLE
is the empty string (""
), than the default not triggering.
我可以这样做:
- set_fact:
NEW_VARIABLE: "{{ VARIABLE | default('default') }}"
- set_fact:
NEW_VARIABLE: "default"
when: VARIABLE == ""
但是我实际上想循环执行此操作.因此,如果我可以使用ansible过滤器而不是有条件的过滤器,那么操作会容易得多.
But I actually want to do this in a loop. So it would be much easier if I could do this using ansible filters and not conditionals.
这可能吗?是否有像default
一样工作但将""
视为未定义的ansible过滤器?
Is this possible? Are there ansible filters that work like default
but treats ""
as not defined?
推荐答案
是的,有可能.
不知道您是否想要这样的东西,但是根据您的描述,这对您有用...
Dont know if its something like that you want but, for your description, this will work for you...
- hosts: localhost
vars:
VARIABLE: ""
tasks:
- set_fact:
NEW_VARIABLE: '{{ (VARIABLE |length > 0) | ternary(VARIABLE, "default") }}'
- debug: msg="{{ NEW_VARIABLE }}"
PLAY [localhost] ********************************************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************************************************
ok: [localhost]
TASK [set_fact] *********************************************************************************************************************************************************************************
ok: [localhost]
TASK [debug] ************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "default"
}
我假设您的变量将始终定义为""
.通过假设,可以检查其长度,然后使用三元滤波器.如果其大于0,则使用变量值;否则,将NEW_VARIABLE
设置为"default"
.如果您不知道是否定义了VARIABLE
,请在set_fact
任务上放一个when: VARIABLE is defined
,应该是它.
Im assuming that your variable will always be defined as ""
. By assuming that, its possible check its length and then use the ternary filter. If its bigger than 0, it use the variable value and if not, it will set NEW_VARIABLE
to "default"
. If you dont know if VARIABLE
will be defined or not, put a when: VARIABLE is defined
on your set_fact
task and this should be it.
来源:可用的过滤器
这篇关于ansible:“默认"过滤器,将空字符串视为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!