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_namenames,则脚本可以正常运行:据我所知,问题出自Ansible试图计算的| first过滤器。 / p>

这是正常现象吗?如果是的话,有人可以向我解释为什么会发生这种情况(为什么要尝试计算未使用的变量/过滤器?)。有没有变通的方法可以使它像我期望的那样工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...