与"default"过滤器结合使用的 Ansible 列表串联



all

在我的库存中,我使用了三个不同级别的变量:

 all/vars: 
 common_configs:
   - src: cfg.a
     dest: dest_a
 group_vars/vars:
 group_configs:
   - src: cfg.b
     dest: dest_b
 host_vars/vars: 
 host_configs:
   - src: cfg.c
     dest: dest_c

最后,我需要将所有 CFG 部署到目标主机。我使用下一个代码:

 - copy:
     src: '{{ item.src }}'
     dest: '{{ item.dest }}'
   with_items:
      - '{{ common_configs + group_configs + host_configs }}'

所有工作,但就我而言,只有common_configs是强制性的,所以当group_configs或/和host_configs未定义时 - 我收到错误。我尝试使用默认(省略(过滤器:

   with_items:
      - '{{ common_configs + group_configs + host_configs|default(omit) }}'

但是我还有另一个错误:

FAILED! => {"msg": "Unexpected templating type error occurred on ({{ common_configs + group_configs + host_configs|default(omit) }}): can only concatenate list (not "str") to list"}

在这种情况下省略未定义的变量的真正方法是什么?

您希望使用 default 过滤器将表达式中的未定义变量替换为空列表:

with_items:
   - '{{ common_configs + group_configs|default([]) + host_configs|default([]) }}'

最新更新