You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Managing configuration files is one of the most common tasks in infrastructure automation. Ansible provides the template module (powered by Jinja2) for dynamic files and the copy module for static files.
| Feature | copy Module | template Module |
|---|---|---|
| Source | Static file | Jinja2 template (.j2) |
| Variables | Not supported | Fully supported |
| Logic | None | Conditionals, loops, filters |
| Use case | Files that never change | Configuration files that vary per host or environment |
Copy static files from the control node to managed nodes:
tasks:
- name: Copy static HTML file
copy:
src: files/index.html
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
- name: Copy with backup
copy:
src: files/app.conf
dest: /etc/app/app.conf
backup: true # Create a backup of the existing file
| Parameter | Description |
|---|---|
| src | Source file on the control node |
| dest | Destination path on the managed node |
| owner | File owner |
| group | File group |
| mode | File permissions (e.g., '0644') |
| backup | Create a backup before overwriting |
| content | Write inline content instead of copying a file |
| validate | Command to validate the file before placing it |
Jinja2 is the templating engine used by Ansible. Templates use the .j2 extension by convention.
| Syntax | Purpose | Example |
|---|---|---|
{{ }} | Variable output | {{ ansible_hostname }} |
{% %} | Logic (if, for, etc.) | {% if env == 'prod' %} |
{# #} | Comments | {# This is a comment #} |
tasks:
- name: Deploy nginx configuration
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
validate: "nginx -t -c %s"
notify: Restart nginx
| Parameter | Description |
|---|---|
| src | Source Jinja2 template on the control node |
| dest | Destination path on the managed node |
| owner | File owner |
| group | File group |
| mode | File permissions |
| validate | Command to validate the rendered file (use %s for the file path) |
| backup | Create a backup before overwriting |
Tip: The
validateparameter is extremely useful for configuration files --- Ansible will only deploy the file if validation passes.
templates/nginx.conf.j2:
worker_processes {{ nginx_worker_processes | default('auto') }};
events {
worker_connections {{ nginx_worker_connections | default(1024) }};
}
http {
server {
listen {{ nginx_port }};
server_name {{ nginx_server_name }};
root {{ nginx_root }};
}
}
{% if env == 'production' %}
log_level = warn
debug = false
{% elif env == 'staging' %}
log_level = info
debug = false
{% else %}
log_level = debug
debug = true
{% endif %}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.