Junior — Middle
Can you explain what templates are in Ansible and how they are used?
sobes.tech AI
Answer from AI
In Ansible, templates are files, usually with the .j2 extension (Jinja2), which contain text with dynamic variables and expressions. They allow creating configuration files or scripts by substituting variable values during the playbook execution.
Templates are used to generate configurations that depend on host parameters or environment. For example, you can create an nginx configuration template where the server address and port are substituted from variables.
Example of using a template in an Ansible task:
- name: Copy nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
In the nginx.conf.j2 template, variables can be used:
server {
listen {{ nginx_port }};
server_name {{ server_name }};
}
Thus, templates make playbooks flexible and allow adapting configurations to different conditions without code duplication.