如果Ansibe中的变量为空,如何省略? [英] How to omit if variable is empty in Ansibe?
问题描述
我正在研究 Docker 的 ansible 示例.
I'm going through ansible example for Docker.
我需要像示例中一样发布一个端口,但使用 if 语句 if port else omit
.像这样:
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?
提前感谢您的帮助.
推荐答案
您应该使用 default
过滤器,带有 omit
变量.
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中的变量为空,如何省略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!