如何解决Ansible模板尝试在未使用的条件分支中计算变量:这是正常行为吗?
我正在使用Ansible 2.8.6,并且在使用条件时遇到模板错误。即使这些变量仅在模板的“未使用的分支”中使用,它也会尝试计算变量的某些部分。就我而言,计算这些变量没有任何意义,并且会引发错误,因此我不希望Ansible计算这些变量。我希望如果不满足使用条件,Ansible / Jinja2不会计算它们。
我要解释的简单示例:
-
pb_test.yml
(剧本)- name: "Testing template" hosts: localhost tasks: - name: "Generate a file from a template" template: src: templates/test.txt.j2 dest: /tmp/test.txt
-
templates/test.txt.j2
(模板)Hello,please call me: {% if use_last_name %} "{{ last_name }}". This is how my colleagues call me. {% else %} "{{ first_name }}". This is how my friends call me. {% endif %}
-
inventory/hosts
localhost
-
inventory/group_vars/all.yml
use_last_name: True names: [] ## I don't have any names in the list but it does not matter,I use last names. first_name: "{{ names | first }}" last_name: "Doe"
除了这本剧本,我希望一切正常。变量first_name
无法定义,但是没关系,因为我没有使用它。但是我得到以下结果:
$ ansible-playbook -i inventory/host -kK -u admin pb_test.yml
SSH password:
BECOME password[defaults to SSH password]:
PLAY [Testing template] ************************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************************
ok: [localhost]
TASK [Generate a file from a template] ******************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false,"msg": "AnsibleUndefinedVariable: No first item,sequence was empty."}
PLAY RECAP ****************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
从该错误中,我了解到Ansible正在尝试计算first_name
,即使它不会被使用。请注意,如果根本没有定义first_name
和names
,则脚本可以正常运行:据我所知,问题出自Ansible试图计算的| first
过滤器。 / p>
这是正常现象吗?如果是的话,有人可以向我解释为什么会发生这种情况(为什么要尝试计算未使用的变量/过滤器?)。有没有变通的方法可以使它像我期望的那样工作?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。