gpt4 book ai didi

Ansible 模板和神社 {%block%}

转载 作者:行者123 更新时间:2023-12-02 00:11:40 25 4
gpt4 key购买 nike

我需要在远程主机上使用多个模板文件和 Jinja 的 {% block block_name %} 在我的 Ansible 角色中生成一个文件

例如,

main.conf.j2:

value1 = 123
value2 = 456

{% block test %} {% endblock %}

value3 = 789

{% block example %} {% endblock %}

value4 = abcd

测试.conf.j2:

{% block test %}
more text here
{% endblock %}

示例.conf.j2

{% block example %}
....
example_param = 'example!'
....
{% endblock %}

下一步是什么?我必须在 test.conf.j2 和 example.conf.j2 中使用 {% extends 'nginx.conf.j2' %} 吗?如果是这样——我的 Ansible 任务会怎样?还是别的东西?

如果我尝试这样的事情:

- name: Copy config
template:
src: "{{ item }}"
dest: "{{ conf_file_path }}"
with_items:
- "main.conf.j2"
- "test.conf.j2"
- "example.conf.j2"
- "abcd.conf.j2"

它只适用于 main.conf.j2 和 test.conf.j2,但忽略 example.conf.j2 和其他模板

最佳答案

Q: "What's the next step? I must use {% extends 'nginx.conf.j2' %} ... ?"

答:是的。 extends是需要的。例如

    - template:
src: test.j2
dest: test

使用模板

    shell> cat main.j2
value1 = 123
{% block test %}
value = default value in main.j2
{% endblock %}
value3 = 789
    shell> cat test.j2 
{% extends 'main.j2' %}
{% block test %}
value = custom value in test.j2
{% endblock %}

给予

    shell> cat test 
value1 = 123
value = custom value in test.j2
value3 = 789

Q: "How will look my Ansible task?"

    - name: Copy config
template:
src: "{{ item }}"
dest: "{{ conf_file_path }}"
with_items:
- "main.conf.j2"
- "test.conf.j2"
- "example.conf.j2"
- "abcd.conf.j2"

A:循环将在每次迭代中重复覆盖dest 文件。参见 template .


FWIW。可以使用 blockinfile并循环 lookup的模板。例如

    - template:
src: main2.j2
dest: test
- blockinfile:
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item }}"
path: test
block: "{{ lookup('template', item) }}"
loop:
- test.conf.j2
- example.conf.j2

使用模板

    shell> cat main2.j2
value1 = 123

# BEGIN ANSIBLE MANAGED BLOCK test.conf.j2
value_test = default value in main2.j2
# END ANSIBLE MANAGED BLOCK test.conf.j2

# BEGIN ANSIBLE MANAGED BLOCK example.conf.j2
value_example = default value in main2.j2
# END ANSIBLE MANAGED BLOCK example.conf.j2

value3 = 789
    shell> cat test.conf.j2
value_test = custom value in test.conf.j2
    shell> cat example.conf.j2
value_example = custom value in example.conf.j2

给予

    shell> cat test 
value1 = 123

# BEGIN ANSIBLE MANAGED BLOCK test.conf.j2
value_test = custom value in test.conf.j2
# END ANSIBLE MANAGED BLOCK test.conf.j2

# BEGIN ANSIBLE MANAGED BLOCK example.conf.j2
value_example = custom value in example.conf.j2
# END ANSIBLE MANAGED BLOCK example.conf.j2

value3 = 789

关于Ansible 模板和神社 {%block%},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58793434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com