【问题标题】:Jinja template as variable valueJinja 模板作为变量值
【发布时间】:2021-05-05 16:06:42
【问题描述】:

我正在尝试在角色任务中使用 模板作为ansible.builtin.lineinfile module 的值。

named
├── tasks
│   ├── config.yml
│   ├── main.yml
├── templates
│   ├── option.ji2
│   ├── view.ji2
  ansible.builtin.lineinfile:
    path: "{{ test_dir }}{{ named_config_file['path'] }}"
    regex: "{{ item['key'] }}"
    line: "{% set option = item %}{% include 'option.ji2' %}"
    validate: named-checkconf %s
  loop: "{{ named_options | dict2items }}"

不幸的是 ansible 抛出 TemplateNotFound 错误:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: jinja2.exceptions.TemplateNotFound: option.ji2

使用模板的相对或绝对路径没有帮助。

view.ji2 中包含的相同模板有效:

{% for option in item['options'] | dict2items %}
{% if option is mapping %}
{% include 'option.ji2' %}
{% endif %}
{% endfor %}

在其他角色剧本中,有一个简单的 Jinja 模板(不包括包含)也可以:

  ansible.posix.authorized_key:
    key:
      "{% if item[1]['key'] is match('ssh-.{256}') %}\
      {{ item[1]['key'] }}\
      {% else %}\
      {{ lookup('file', item[1]['key'], errors='ignore') }}\
      {% endif %}"
    user: "{{ item[0]['name'] }}"
    state: "{{ item[1]['state'] | default(omit, true) }}"
  loop: "{{ user_accounts | subelements('authorized_keys', skip_missing=True) }}"

知道为什么 找不到/使用模板option.ji2

【问题讨论】:

  • 尝试添加文件路径。
  • 已经尝试了一些组合,包括下面列出的组合,但仍然没有成功。 templates/option.ji2../templates/option.ji2/home/ansible/.ansible/roles/named/templates/option.ji2

标签: jinja ansible templates ansible jinja2


【解决方案1】:

解决方法/解决方案是使用 template 查找。

ansible.builtin.lineinfile:
  path: "{{ test_dir }}{{ named_config_file['path'] }}"
  regex: "{{ item['key'] }}"
  line: "{{ lookup('template','option.ji2') }}"
  validate: named-checkconf %s
loop: "{{ named_options | dict2items }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多