简体   繁体   English

jinja2模板中的条件文本

[英]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: 现在,我有了带有所有必需变量的模板(j2):

{% 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. 如果相关变量为空,则不将选项(-z,-b等)包括在输出中。

For example above, if flowtools.captures[0] contains only debug_level=2 and workdir=/tmp it should generate: 例如,在上面的示例中,如果flowtools.captures [0]仅包含debug_level = 2和workdir = / tmp,则应生成:

-d 2 -w /tmp. -d 2 -w / tmp。

I can add huge list of {% if %}'s but this would be very bulky. 我可以添加{%if%}的大量列表,但这将非常庞大。 Is it possible to make it gracefully? 是否可以使它优雅?

Well, after some struggle I made 好吧,经过一番挣扎,我做了

vars.yml: vars.yml:

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

template.j2: template.j2:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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