Ser*_*erg 2 ansible ansible-template ansible-2.x
我需要在远程主机上使用多个模板文件和 Jinja{% block block_name %}
在我的 Ansible 角色中生成一个文件
例如,
main.conf.j2:
value1 = 123
value2 = 456
{% block test %} {% endblock %}
value3 = 789
{% block example %} {% endblock %}
value4 = abcd
Run Code Online (Sandbox Code Playgroud)
测试.conf.j2:
{% block test %}
more text here
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
例子.conf.j2
{% block example %}
....
example_param = 'example!'
....
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
下一步是什么?我必须{% extends 'nginx.conf.j2' %}
在 test.conf.j2 和 example.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"
Run Code Online (Sandbox Code Playgroud)
它仅适用于 main.conf.j2 和 test.conf.j2,但忽略 example.conf.j2 和其他模板
问:“下一步是什么?我必须使用 {% extends 'nginx.conf.j2' %} ... ?
答:是的。需要扩展。例如
- template:
src: test.j2
dest: test
Run Code Online (Sandbox Code Playgroud)
与模板
shell> cat main.j2
value1 = 123
{% block test %}
value = default value in main.j2
{% endblock %}
value3 = 789
Run Code Online (Sandbox Code Playgroud)
shell> cat test.j2
{% extends 'main.j2' %}
{% block test %}
value = custom value in test.j2
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
给
shell> cat test
value1 = 123
value = custom value in test.j2
value3 = 789
Run Code Online (Sandbox Code Playgroud)
问:“我的 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"
Run Code Online (Sandbox Code Playgroud)
A:循环会在每次迭代中反复覆盖dest文件。请参阅模板。
FWIW。可以使用blockinfile并循环查找模板。例如
- 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
Run Code Online (Sandbox Code Playgroud)
与模板
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
Run Code Online (Sandbox Code Playgroud)
shell> cat test.conf.j2
value_test = custom value in test.conf.j2
Run Code Online (Sandbox Code Playgroud)
shell> cat example.conf.j2
value_example = custom value in example.conf.j2
Run Code Online (Sandbox Code Playgroud)
给
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1478 次 |
最近记录: |