问题
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