我有本手册,可以在我们服务器上的docker容器中部署领事。我基本上看起来像这样:
- name: run consul
hosts: all
tasks:
- name: consul | run consul servers and agents
docker_container:
name: consul
network_mode: bridge
published_ports:
- "{{ docker_host_ip }}:8301:8301"
- "{% if consul_server is defined %}{{ docker_host_ip }}:8300:8300{% endif %}"
...
...,除了最后一行无效。我只想公开consul作为服务器的8300端口,该服务器存储在每个主机的consul_server
变量中。
如何有条件地将元素添加到YAML列表/数组?
答案 0 :(得分:1)
您可以使用数组concat:
- name: consul | run consul servers and agents
docker_container:
name: consul
network_mode: bridge
published_ports: "{{ [ docker_host_ip ~ ':8301:8301' ] + ([ docker_host_ip ~ ':8300:8300' ] if consul_server is defined else [])}}"
在示例代码中,如果定义了{{ docker_host_ip }}:8300:8300
,则consul_server
将被添加到列表中。
答案 1 :(得分:1)
Filters是你的朋友。
- set_fact:
myTrue : true
myFalse : false
myList :
- first
myAdd :
- second
- debug:
msg: "When TRUE: {{ myTrue |
ternary( myList | union( myAdd ), myList ) }}"
- debug:
msg: "When FALSE: {{ myFalse |
ternary( myList | union( myAdd ), myList ) }}"
输出(经过微调以消除不相识之处):
TASK [test : debug]
"msg": "When TRUE: [u'first', u'second']"
TASK [test : debug]
"msg": "When FALSE: [u'first']"