首页 > 解决方案 > 使用条件渲染时出现Ansible模板奇怪错误

问题描述

我有这个可靠的角色

---

- name: render motd template
  template:
    src: motd.j2
    dest: /etc/motd
    owner: root
    group: root
    mode: 0644

这个模板在motd.j2

Welcome to {{inventory_hostname}}!
{{if ansible_distribution_major_version == 'NA'}}
There is {{ansible_distribution}}!
{{else}}
There is {{ansible_distribution}} {{ansible_distribution_major_version}}!
{{endif}}

当我尝试执行此角色时,出现此错误:

AnsibleError: template error while templating string: 
expected token 'end of print statement', got 'string'.

这里有什么问题?

如果我使用模板

Welcome to {{ inventory_hostname }}!
There is {{ansible_distribution}} {{ansible_distribution_major_version}}!

一切都按预期工作。我认为if有条件的错误

标签: ansiblejinja2

解决方案


看起来像是正确渲染模板的固定任务,jinja2 对变量输出({{ }})和条件渲染命令({% %})有不同寻常的不同分隔符:

Welcome to {{ inventory_hostname }}!
{% if ansible_distribution_major_version == 'NA' %}
There is {{ ansible_distribution }}!
{% else %}
There is {{ ansible_distribution }} {{ ansible_distribution_major_version }}!
{% endif %}

推荐阅读