Console9

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

  1. 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;
        }
    }
  2. Define the variables in the inventory or playbook:

    vars:
      server_name: example.com
      document_root: /var/www/example
  3. Use the template module 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 Nginx
  4. Define 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