How to apply a file template to the target host with Ansible?

This is extremely useful for service configuration files, placeholder web pages, reports, and so much more use cases.

I'm going to show you a live Playbook with some simple Ansible code.

I'm Luca Berton and welcome to today's episode of Ansible Pilot.

Ansible applies a file template

  • ansible.builtin.template
  • Template a file out to a target host
  • ansible_managed, template_host, template_uid, template_path, template_fullpath, template_destpath, and template_run_date

Today we're talking about Ansible module template.

The full name is ansible.builtin.template, it's part of ansible-core and is included in all Ansible installations.

It templates a file out to a target host. Templates are processed by the Jinja2 templating language.

Also you could use also some special variables in your templates: ansible_managed, template_host, template_uid, template_path, template_fullpath, template_destpath, and template_run_date.

It supports a large variety of Operating Systems.

For basic text formatting, use the [Ansible ansible.builtin.copy module](/articles/create-a-text-file-ansible-module-copy) or for [empty file Ansible ansible.builtin.file module](/articles/create-an-empty-file-ansible-module-file).

For Windows, use the ansible.windows.win_template module instead.

Parameters

  • src path - template ("templates/" dir)
  • dest path - target location
  • validate string - validation command before ("%s")
  • backup boolean - no/yes
  • mode/owner/group - permission
  • setype/seuser/selevel - SELinux

Let me highlight the most useful parameters for template module.

The only required parameters are "src" and "dest".

The "src" parameter specifies the template file name. Templates usually are stored under "templates" directories with ".j2" file extension.

The "dest" parameter specifies the path where to render the template on the remote machine.

The "validate" parameters allow you to specify the validation command to run before copying it into place. It's very useful with configuration files for services.

Please note that the special escape sequence "%s" is going to be expanded by Ansible with the destination path.

If the "backup" parameter is enabled Ansible creates a backup file including the timestamp information before copying it to the destination.

Let me also highlight that we could also specify the permissions and SELinux properties.

## Playbook

Apply a file template with Ansible Playbook

code

  • template.yml

```yaml

---

  • name: template module Playbook

hosts: all

become: true

vars:

page_title: "Placeholder"

page_description: |

This is my placeholder page example.

Multiline is possible ;-)

tasks:

- name: install Nginx

ansible.builtin.apt:

name: nginx

state: latest

  • name: apply page template

ansible.builtin.template:

src: templates/placeholder.html.j2

dest: /var/