本文介绍了如何在Ansibe中忽略变量是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究可移植的示例

我需要像示例中一样发布一个端口,但是要使用if语句 if port else else .像这样:

And I need to publish a port just like in the example but with an if statement if port else omit. Like this:

docker_container:
name: myapplication
...
ports:
 - "{{ if port else omit }}" # the {{ port }} variable is set from the default task.
...

但是每次运行此命令时,Docker守护进程都会告诉我:

But each time I run this, the Docker daemon tells me:

template error while templating string: expected token 'end of print statement', got 'port'. String: {{ if port else omit }}"

如果变量 {{port}} 为空,如何省略端口设置?

How do I omit setting the port if the variable {{ port }} is empty?

非常感谢您的帮助.

推荐答案

您应使用 默认过滤器,并为此忽略变量.

You should use the default filter with the omit variable for that.

- docker_container:
    name: myapplication
    ports: "{{ port|default(omit) if port is not defined else [port] }}"

请记住您要使用这种确切的语法,而不是像这样的数组符号

Mind that you want to use this exact syntax and not the array notation like

- docker_container:
    name: myapplication
    ports:
      - "{{ port|default(omit) }}"

否则,您将最终在属性 ports 中得到一个数组,但该数组仍将具有

Otherwise you will end up with an array in the attribute ports, still, that would have some odd value like

"__omit_place_holder__ad3616ee8afa39aa187d7fc6ac7ad36f3e7691c0"

这篇关于如何在Ansibe中忽略变量是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:04