当Ansible遇到一个if块,并且if条件涉及groups变量时,似乎在评估if条件之前先扩展了块的内容。这将导致未定义的变量错误,if否则该条件将防止该错误。
为什么会发生错误?是预期的行为还是错误?
我已将行为减少到最小的测试用例。
库存.yml
group1:
group2:
hosts:
localhost:
vars:
foo: "{{ groups.group1[0] }}"
Run Code Online (Sandbox Code Playgroud)
一个空字符串,因为在两种情况下if条件均为false
$ ansible -i inventory.yml group2 -mdebug -amsg="{% if false %}{{ foo }}{% endif %}"
localhost | SUCCESS => {
"msg": ""
}
$ ansible -i inventory.yml group2 -mdebug -amsg="{% if groups.group1 %}{{ foo }}{% endif %}"
localhost | SUCCESS => {
"msg": ""
}
Run Code Online (Sandbox Code Playgroud)
当if条件涉及groups变量时,foo将对其求值,从而产生未定义的变量消息
$ ansible -i inventory.yml group2 -mdebug -amsg="{% if false %}{{ foo }}{% endif %}"
localhost | SUCCESS => {
"msg": ""
}
$ ansible -i inventory.yml group2 -mdebug -amsg="{% if groups.group1 %}{{ foo }}{% endif %}"
localhost | FAILED! => {
"msg": "The task includes an option with an undefined variable. The error was: list object has no element 0"
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Ansible 2.7.9。