如何消除 Ansible Jinja2 模板中宏调用之间的多余空格?

How do I eliminate extra whitespace between macro calls in Ansible Jinja2 templates?

给定 Ansible Jinja2 模板:

{% macro directive(name, value) %}
{% if value is defined %}
{{ name }}={{ value }}
{% endif %}
{% endmacro -%}

# {{ ansible_managed }}

[Unit]
{{ directive('Description', service.description) }}
{{ directive('Documentation', service.documentation) }}
{{ directive('Requires', service.requires) }}

with service 变量定义:

service:
  description: Test Template
  requires: multi-user.target

如何更改模板以消除结果输出中的额外换行符:

# Ansible managed

[Unit]
Description=Test Template


Requires=multi-user.target

所以它看起来像:

# Ansible managed

[Unit]
Description=Test Template
Requires=multi-user.target

?

考虑以下几点:

{% macro directive(name, value) %}
{% if value is defined %}
{{ name }}={{ value }} # a newline hardcoded in macro follows
{% endif %}
{% endmacro -%}

# {{ ansible_managed }}

[Unit 1]
{{ directive('Description', service.description) }}# 1st hardcoded newline follows
{{ directive('Documentation', service.documentation) }}# 2nd hardcoded newline follows
{{ directive('Requires', service.requires) }}# 3rd hardcoded newline follows

它产生:

# Ansible managed

[Unit 1]
Description=Test Template # a newline hardcoded in macro follows
# 1st hardcoded newline follows
# 2nd hardcoded newline follows
Requires=multi-user.target # a newline hardcoded in macro follows
# 3rd hardcoded newline follows

尽管关于 whitespace control 的文档声明“如果存在单个尾随换行符”,它不适用于变量替换,因此即使结果宏末尾包含一个换行符,这个特定的换行符将不会被删除。

就像你定义了它没有被剥离一样:

variable_with_newline: "value\n"

和运行一个模板:

start-{{ variable_with_newline }}-end

它产生:

start-value
-end

要修复模板,请删除硬编码的换行符:

[Unit]
{{ directive('Description', service.description) }}{{ directive('Documentation', service.documentation) }}{{ directive('Requires', service.requires) }}

或添加明确的空白剥离:

[Unit]
{{ directive('Description', service.description) }}
{{- directive('Documentation', service.documentation) }}
{{- directive('Requires', service.requires) }}

[Unit]
{{ directive('Description', service.description) -}}
{{ directive('Documentation', service.documentation) -}}
{{ directive('Requires', service.requires) }}