ansible template - ghdrako/doc_snipets GitHub Wiki

In Ansible, templates use the Jinja2 templating engine

Example managing a fleet of web servers with different domains, ports, and document roots. Rather than creating a separate configuration file for each server, you can create a template containing variables for these settings.

server {
listen {{ web_server_port }};
server_name {{ domain }};
root {{ document_root }};
}

Then, using Ansible's capabilities, you can deploy this template to each server, substituting the appropriate values for each variable. This single template can serve an entire fleet of web servers, each with its unique configuration. By encapsulating configuration logic into templates and utilizing variables for customization, Ansible provides a scalable, maintainable, and consistent way to manage configurations.

---
- name: Configure Nginx
hosts: webservers
vars:
web_server_port: 80
domain: example.com
document_root: /var/www/html
tasks:
- name: Generate Nginx Configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/sites-available/default

This playbook utilizes the Jinja2 template to generate Nginx configuration file tailored to each web server. By leveraging variables, filters, loops, conditionals, and other features, you can create highly customizable automation processes that adapt to the needs of your infrastructure.