且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果Ansibe中的变量为空,如何省略?

更新时间:2023-09-18 13:29:52

您应该使用 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"