How to deploy files with Ansible templates
Generate configuration files from Jinja2 templates with host-specific variables using Ansible.
How to deploy files with Ansible templates
Generate configuration files from Jinja2 templates with host-specific variables using Ansible.
Prerequisites
- Ansible installed with a working inventory.
Step-by-Step: Deploy Templates with Ansible
Create a Jinja2 template file (e.g.,
templates/nginx.conf.j2):server { listen 80; server_name {{ server_name }}; root {{ document_root }}; location / { try_files $uri $uri/ =404; } }Define the variables in the inventory or playbook:
vars: server_name: example.com document_root: /var/www/exampleUse the
templatemodule in a task to render and deploy the file:- name: Deploy Nginx configuration template: src: nginx.conf.j2 dest: /etc/nginx/sites-available/example.conf owner: root group: root mode: '0644' notify: Reload NginxDefine a handler to reload Nginx when the template changes:
handlers: - name: Reload Nginx service: name: nginx state: reloaded
How to Verify Template Deployment
Run the playbook in check mode with diff to see what would change:
ansible-playbook site.yml --check --diff