ansible角色中使用的一些数据:
list1:
- foo
- bar
list2: # sometimes this is empty
此 ansible 任务失败:
- name: hello
somemodule:
dosomething: "{{ list1 + list2 }}"
错误:
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{list1 + list2}}): can only concatenate list (not \"NoneType\") to list"}
是否有办法仅在 list2
不为空时有条件连接?
最佳答案
您可以使用none
bulitin 测试结合 inline if expression为此:
- debug:
msg: "{{ list1 + (list2 if list2 is not none else []) }}"
鉴于剧本
- hosts: local
gather_facts: no
vars:
list1:
- foo
- bar
list2:
tasks:
- debug:
msg: "{{ list1 + (list2 if list2 is not none else []) }}"
一场比赛将导致以下回顾:
PLAY [local] **************************************************************************************
TASK [debug] **************************************************************************************
ok: [local] => {
"msg": [
"foo",
"bar"
]
}
PLAY RECAP ****************************************************************************************
local : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
关于ansible - 有条件地连接 jinja2 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61962370/