我想在Jinja2的Ansible上下文中包含另一个Jinja2模板

sau*_*aga 8 jinja2 ansible ansible-template

我有一个Ansible手册,它设置了很多变量.一个剧本有这个任务:

- name: create config file 
  template:
    src: 'templates/main_config.j2'
    dest: "{{ tmp_dir }}/main_config.json"
Run Code Online (Sandbox Code Playgroud)

该模板main_config.j2在父Ansible playbooks和tasks中写入被定义为变量的字符串.

我想基于Ansible变量的值包含另一个Jinja2模板.

{% include "./templates/configurations.j2" %}, 
{% include "./templates/security.j2" %},
{% include './templates/' + {{ job }} + '_steps.j2' %}
Run Code Online (Sandbox Code Playgroud)

job 是在父级剧本中设置的Ansible变量.

这不起作用.可能是什么问题呢?

tec*_*raf 16

您不需要打开Jinja2表达式({{ ... }})来引用语句({% ... %})中的变量.您可以直接使用变量名称:

{% include './templates/' + job + '_steps.j2' %}
Run Code Online (Sandbox Code Playgroud)