使用Ansible控制Jinja2模板中的缩进



我有这个剧本:

(venv) bash-3.2$ cat playbooks/nginx_config_generate.yml
---
- name: Generate Nginx Config
hosts: all
gather_facts: False
roles:
- ../roles/nginx_config_generate

以下是组成角色的文件:

(venv) bash-3.2$ cat roles/nginx_config_generate/tasks/main.yml
---
- name: Generate Nginx Config
import_tasks: gen_config.yml
(venv) bash-3.2$ cat roles/nginx_config_generate/tasks/gen_config.yml
- name: Generate Nginx Config File From Template
ansible.builtin.template:
src: sp.conf.j2
dest: "/tmp/nginx.cfg"
(venv) bash-3.2$ cat roles/nginx_config_generate/templates/sp.conf.j2
something here
# Upstreams
{% for ups in my_vars.upstreams %}
{{ ups.entry }}
{% endfor %}
# HTTP Insecure
server {
blha blah blah
something here = that
this = that
{% for ups in my_vars.http_locations %}
{{ ups.entry }}
{% endfor %}
}

这是我的host_vars…

(venv) bash-3.2$ cat inventory/prod/sfo/host_vars/127.0.0.1
my_vars_str: "host,127.0.0.1,srv1,srv2"
my_vars:
upstreams:
- entry: |
upstream something {
foo: blah blah
}
- entry: |
upstream completely {
foo: blah blah
different: True
}
http_locations:
- entry: |
location / {
set something
}
- entry: |
location /foo {
set something
hover: craft
}

当我运行我的play时,它产生了这个文件:

(venv) bash-3.2$ cat /tmp/nginx.cfg
something here
# Upstreams
upstream something {
foo: blah blah
}
upstream completely {
foo: blah blah
different: True
}

# HTTP Insecure
server {
blha blah blah
something here = that
this = that
location / {
set something
}
location /foo {
set something
hover: craft
}

}

正如你所看到的,上面可能是一个有效的nginx配置,但我如何修复我的location行缩进,使其更可读?

更新:我尝试了Carlos的建议,所以我尝试了这个:

...
# HTTP Insecure
server {
blha blah blah
something here = that
this = that
{% for loc in my_vars.http_locations %}
{{ loc.entry }}
{% endfor %}
}

但是产生相同的输出:

# HTTP Insecure
server {
blha blah blah
something here = that
this = that
location / {
set something
}

location /foo {
set something
hover: craft
}

好的。我开始在我的模板中使用indent过滤器。下面是我用来生成所需输出的模板:

something here
# Upstreams
{% for ups in my_vars.upstreams %}
{{ ups.entry }}
{% endfor %}
# HTTP Insecure
server {
blha blah blah
something here = that
this = that
{% for loc in my_vars.http_locations %}
{{ loc.entry | indent(4)}}
{% endfor %}
}

现在我得到这样的输出:

something here
# Upstreams
upstream something {
foo: blah blah
}
upstream completely {
foo: blah blah
different: True
}

# HTTP Insecure
server {
blha blah blah
something here = that
this = that
location / {
set something
}
location /foo {
set something
hover: craft
}

}

你试过修改第二个循环中的缩进吗?

# HTTP Insecure
server {
blha blah blah
something here = that
this = that
{% for ups in my_vars.http_locations %}
{{ ups.entry }}
{% endfor %}
}

最新更新