如果变量为空,我想设置一个默认数组。在默认过滤器中设置一个空数组的工作原理如下所述这里. 设置存储在变量中的数组则不会。
在示例中run_targets
为undefined
,targets
应改用 。
- name: Set vars
vars:
targets: [target1, target2, target3]
- name: Include run sql task
include: tasks/sql.yml
with_items: "{{ run_targets | defult(targets) }}"
有什么办法可以做到这一点?
答案1
您的剧本无效。vars
不是您可以在任务中运行的模块。您可以在游戏级别使用set_fact
或声明vars
。以下完整示例表明它可以正常工作:
---
- name: Demo of default from var
hosts: localhost
gather_facts: false
vars:
default_targets:
- target1
- target2
- target3
tasks:
- name: Show run targets else defaults
debug:
msg: "{{ run_targets | default(default_targets) }}"
这使:
$ ansible-playbook playbook.yml
PLAY [Demo of default from var] ************************************************
TASK [Show run targets else defaults] ******************************************
ok: [localhost] => {
"msg": [
"target1",
"target2",
"target3"
]
}
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
$ ansible-playbook playbook.yml -e "{run_targets: [a,b,c]}"
PLAY [Demo of default from var] ************************************************
TASK [Show run targets else defaults] ******************************************
ok: [localhost] => {
"msg": [
"a",
"b",
"c"
]
}
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0