Ansible YAML中的条件列表元素

Ansible YAML中的条件列表元素,ansible,yaml,Ansible,Yaml,我有一个在我们的服务器上部署docker容器中的Consor的剧本。我基本上是这样的: - name: run consul hosts: all tasks: - name: consul | run consul servers and agents docker_container: name: consul network_mode: bridge published_ports: - "{{

我有一个在我们的服务器上部署docker容器中的Consor的剧本。我基本上是这样的:

- 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 %}"
...
。。。除了最后一行不行。我只想在concur部署为服务器时公开端口8300,该服务器存储在每个主机的
concur_服务器
变量中


如何有条件地将元素附加到YAML列表/数组?

您可以使用数组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 [])}}"
在示例代码中,如果定义了
concur\u server
,则将
{{docker\u host\u ip}}:8300:8300
添加到列表中。

是您的朋友


输出(稍微修改以删除不相关项):

- 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']"