Additional spaces appearing in Ansible templates

I am creating configuration files, and I want them to be indented that way. I started with a Jinja2 template that displayed correctly when called from a simple python program. When I call it due to impossibility, I will get 2 extra spaces on all but the first line of the loop. Creating things like YAML and python was a real pain. I took to put the comment line as the first line for the block to fix this ...

Here is a really simple example of a YAML generator:

call in playback mode:

  - name: generate bgp vars file, put in includes directory
    local_action: template src={{ role_dir }}/templates/bgp_vars.j2 dest={{ incvar_dir }}/bgp_vars.yaml
    run_once: true

template section:

dc_route_reflectors:
{% for dc in SH_dcs %}
# dc is "{{ dc }}"
  {{ dc }}:
  {% for host in groups[bgpgroupname] if dc == hostvars[host].MYDC %}
    - "{{ hostvars[host].MAIN_MYADDR }}"
  {% endfor %}
{% endfor %}

displayed output:

dc_route_reflectors:

# dc is "pnp"
  pnp:
      - "10.100.16.3"
      - "10.100.32.3"
  # dc is "sgs"
  sgs:
      - "10.8.0.3"
      - "10.8.16.3"
  # dc is "cst"
  cst:
      - "10.4.0.3"
      - "10.4.16.3"
  # dc is "dse"
  dse:
      - "10.200.0.3"
      - "10.200.16.3"

, dc "pnp" , , sgs, cst dse 2 . ip- . "-" "%", Jinja2, .

, , . 2.2.1.0 CentOS7.

+4
1

, , :

dc_route_reflectors:
{% for dc in SH_dcs %}
# dc is "{{ dc }}"
  {{ dc }}:
{% for host in groups[bgpgroupname] if dc == hostvars[host].MYDC %}
    - "{{ hostvars[host].MAIN_MYADDR }}"
{% endfor %}
{% endfor %}

, lstrip_blocks True ( : ):

#jinja2:lstrip_blocks: True
dc_route_reflectors:
{% for dc in SH_dcs %}
# dc is "{{ dc }}"
  {{ dc }}:
  {% for host in groups[bgpgroupname] if dc == hostvars[host].MYDC %}
    - "{{ hostvars[host].MAIN_MYADDR }}"
  {% endfor %}
{% endfor %}

Jinja2.


Jinja2 trim_blocks lstrip_blocks .

, ( ), . .

, dc "pnp" , , sgs, cst dse 2 .

7- ( {% endfor %}).

ip- .

5- ( {% for host).

+7

Source: https://habr.com/ru/post/1672761/


All Articles