【问题标题】:How to omit if variable is empty in Ansibe?如果变量在 Ansible 中为空,如何省略?
【发布时间】:2020-06-02 05:19:12
【问题描述】:

我正在为 Docker 处理 ansible example

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

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

但每次我运行它时,Docker 守护进程都会告诉我:

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

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

提前感谢您的帮助。

【问题讨论】:

  • 你应该接受一个答案,如果它解决了你的问题,我认为 β.εηοιτ.βε 答案可以解决

标签: docker ansible


【解决方案1】:

您应该为此使用default filter with the omit variable

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

请注意,您要使用这种精确的语法,而不是像这样的数组表示法

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

否则你最终会在属性ports 中得到一个数组,但仍然会有一些奇怪的值,比如

"__omit_place_holder__ad3616ee8afa39aa187d7fc6ac7ad36f3e7691c0"

【讨论】:

    【解决方案2】:

    您可以使用when 进行有条件播放。首先定义你的容器:

    docker_container:
      name: myapplication
      ...
    

    如果定义了端口,则公开它:

    docker_container:
      name: myapplication
      ports:
       - "{{ port }}"
      when: port is defined
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 2015-04-30
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多