Sobes.tech
Junior — Middle

Can you show an example of using Jinja2 templates in Ansible for dynamic configuration file generation?

sobes.tech AI

Answer from AI

In Ansible, Jinja2 templates are often used for dynamic generation of configuration files based on variables. For example, you can create a template nginx.conf.j2:

server {
    listen {{ nginx_port }};
    server_name {{ server_name }};

    location / {
        proxy_pass http://{{ backend_host }}:{{ backend_port }};
    }
}

In a playbook, you can use the template module to generate the final file:

- hosts: webservers
  vars:
    nginx_port: 80
    server_name: example.com
    backend_host: 127.0.0.1
    backend_port: 8080
  tasks:
    - name: Generate nginx configuration
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf

This approach allows easy modification of configuration parameters without editing the files themselves, using Ansible variables.