Ansible Jinja2, formatting

so currently I run a for loop to produce a list of addresses, here is the loop:

sg_nodes_dn: "
  {%- set nodes = [] %}
  {%- for host in groups['elastic_nodes'] %}
  {{- nodes.append('CN=%s,OU=Systems/DevOps,O=x x x,L=x,C=x' % hostvars[host]['elk_node_name']) }}
  {%- endfor %}
  {{- nodes -}}"

This works great, however the problem I have is when I format it into a j2 template.

Here is the var inside my template:

searchguard.nodes_dn:
    {{ sg_nodes_dn | to_nice_yaml }}

The problem with this is, it will print the first line fine, however the second line is not formatted in yaml and the service will fail to load, the outcome of this is.

searchguard.nodes_dn:
    - CN=x.x-x.x,OU=Systems/DevOps,O=x x x,L=x,C=x
- CN=x.x-x.x,OU=Systems/DevOps,O=x x x,L=x,C=x

How can I ensure that the second line is properly formatted? I did some brief reading and added:

#jinja2:trim_blocks: False

To the top of the file, but it didn't resolve the issue, can anyone other any input here?

Upvotes: 1

Views: 4043

Answers (1)

Eric Citaire
Eric Citaire

Reputation: 4513

You could use Jinja2 indent filter :

searchguard.nodes_dn:
    {{ sg_nodes_dn | to_nice_yaml | indent(4, false) }}

Or simply use default parameters (width=4 and indentfirst=False), which are exactly what you need:

searchguard.nodes_dn:
    {{ sg_nodes_dn | to_nice_yaml | indent }}

Upvotes: 4

Related Questions