本文介绍了ansible:将空字符串视为未定义的“默认"过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

- set_fact:NEW_VARIABLE: "{{ VARIABLE | default('default') }}"

VARIABLE是空字符串(""),比默认不触发.

我可以这样做:

- set_fact:NEW_VARIABLE: "{{ VARIABLE | default('default') }}"- 设置事实:NEW_VARIABLE:默认"什么时候:变量=="

但我实际上想循环执行此操作.所以如果我可以使用 ansible 过滤器而不是条件来做到这一点会容易得多.

这可能吗?是否有像 default 一样工作但将 "" 视为未定义的 ansible 过滤器?

解决方案

是的,有可能.

不知道它是否与您想要的类似,但根据您的描述,这对您有用...

- 主机:本地主机变量:多变的: ""任务:- 设置事实:NEW_VARIABLE: '{{ (VARIABLE |length > 0) |三元(变量,默认")}}'- 调试:msg="{{ NEW_VARIABLE }}"
PLAY [localhost] ********************************************************************************************************************************************************************************************任务 [收集事实] *****************************************************************************************************************************************************************************************好的:[本地主机]任务 [set_fact] ********************************************************************************************************************************************************************************************好的:[本地主机]任务 [调试] **************************************************************************************************************************************************************************************************好的:[本地主机] =>{"msg": "默认"}

我假设您的变量将始终定义为 "".通过假设,它可能检查其长度,然后使用三元滤波器.如果它大于 0,它使用变量值,如果不是,它会将 NEW_VARIABLE 设置为 "default".如果您不知道 VARIABLE 是否会被定义,请在您的 set_fact 任务上放置一个 when: VARIABLE is defined ,这应该是它.

来源:Ansible 过滤器

If I do this:

- set_fact:
    NEW_VARIABLE: "{{ VARIABLE | default('default') }}"

and VARIABLE is the empty string (""), than the default not triggering.

I could do this:

- set_fact:
    NEW_VARIABLE: "{{ VARIABLE | default('default') }}"
- set_fact:
    NEW_VARIABLE: "default"
   when: VARIABLE == ""

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.

Is this possible? Are there ansible filters that work like default but treats "" as not defined?

解决方案

Yes, its possible.

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 }}"

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.

Source: Ansible filters

这篇关于ansible:将空字符串视为未定义的“默认"过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 15:30