简体   繁体   中英

Conditional text in jinja2 templates for ansible

I have playbook which may set lot of options for the daemon command line. I want to allow set them all from variables, but the same time I want to make them all optional.

Now I have template (j2) with all variables mandatory:

{% for router in flowtools.captures %}
-d {{router.debug_level}} -e {{router.expire_count}} -E {{router.expire_size}} -f {{router.fiter_name}} -F {{router.filter_definition}} -n {{router.rotations}} -N {{router.netsting_level}} -S {{router.start_interval}} -t {{router.tag_name}} -T {{router.active_def}} -V {{pdu_version}} -w {{router.workdir}} -x {{router.xlate_fname}} -z {{router.z_level}}
{% endfor %}

I want:

  • To allow undefined variables in 'router' (without failing a playbook).
  • Not to include option (-z, -b, etc) to the output if related variable is empty.

For example above, if flowtools.captures[0] contains only debug_level=2 and workdir=/tmp it should generate:

-d 2 -w /tmp.

I can add huge list of {% if %}'s but this would be very bulky. Is it possible to make it gracefully?

Well, after some struggle I made

vars.yml:

flowtools_capute_options:
 byte_order: ' -b '
 workdir: ' -w '
 ...etc...

template.j2:

{% for router in flowtools.captures %}
    {% for opt in router  %}
        {{flowtools_capute_options[opt]}} {{-router[opt]-}}
    {% endfor %}    
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM