How to omit if variable is empty in Ansibe?

删除回忆录丶 提交于 2021-02-11 06:21:52

问题


I'm going through ansible example for Docker.

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.
...

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

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

Thanks kindly for your help in advance.


回答1:


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

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

"__omit_place_holder__ad3616ee8afa39aa187d7fc6ac7ad36f3e7691c0"



回答2:


You can use when for conditional plays. Define your container first:

docker_container:
  name: myapplication
  ...

If port is defined expose it:

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


来源:https://stackoverflow.com/questions/62140639/how-to-omit-if-variable-is-empty-in-ansibe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!