If you are using the template module, you may want to create your own function and call it. jinja2 has a function called macro, which calls a file in which a unique function is written from another j2 file. It seems that it can be used, but I will actually try it if it can also be used with the template module.
(1)Playbook
template_sample.j2
---
- name: template TEST
hosts: localhost
gather_facts: no
vars:
ansible_python_interpreter: /usr/bin/python3
tasks:
- name: 'template'
template:
src: base.j2 #Playbook from which macro is called
dest: result.txt
___ (2) j2 file (base.j2: caller file) ___ Line 1: Load macro in macro.j2, which is in the same directory as this j2 file 2nd line: Pass the variable to a unique function called test1 in macro.j2 Line 3: Pass the variable to a unique function called test2 in macro.j2
base.j2
{% import "macro.j2" as macro %}
{{ macro.test1("Taro", "Tokyo") }}
{{ macro.test2("Hanako", "tennis") }}
___ (3) j2 file (macro.j2: file in which original functions are written) ___ Start writing the function as "macro function name (variable 1, variable 2, ...)" Finally, let's close it with "end macro"
macro.j2
{% macro test1(var1, var2)%}
My name is {{ var1 }}
I live in {{ var2 }}
{% endmacro %}
{% macro test2(var1, var2)%}
My name is {{ var1 }}
I like {{ var2 }}
{% endmacro %}
I was able to execute it as expected. Let's cut out a similar description into a macro file and create a smart template.
result.txt
My name is Taro
I live in Tokyo
My name is Hanako
I like tennis
[Ansible x NW automation] I want to create NW device settings with the template module
Recommended Posts