---
title: "How to Create Ansible Templates to Save Configuration Time"
description: "If you need to create dynamic configuration files in Ansible, you have to check out Ansible templates and the template module."
canonical: "https://adamtheautomator.com/ansible-template/"
---

# How to Create Ansible Templates to Save Configuration Time

> If you need to create dynamic configuration files in Ansible, you have to check out Ansible templates and the template module.

Source: https://adamtheautomator.com/ansible-template/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How to Create Ansible Templates to Save Configuration Time](https://adamtheautomator.com/wp-content/uploads/2021/03/How-to-Create-Ansible-Templates-to-Save-Configuration-Time.jpg)

# How to Create Ansible Templates to Save Configuration Time

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)25 March 20217 min. read

Categories: [DevOps](/category/devops/)

Tags:[Ansible](/tag/ansible/)

Table of Contents

*   [Prerequisites](#h-prerequisites)
*   [What is an Ansible template?](#h-what-is-an-ansible-template)
*   [What does an Ansible template look like?](#h-what-does-an-ansible-template-look-like)
*   [How are templated files created on remote hosts?](#h-how-are-templated-files-created-on-remote-hosts)
*   [Rendering a Configuration File: A Template Example](#h-rendering-a-configuration-file-a-template-example)
*   [Updating File Permissions with the Template Module](#h-updating-file-permissions-with-the-template-module)
*   [Using Loops to Template Multiple Files](#h-using-loops-to-template-multiple-files)
*   [Conclusion](#h-conclusion)

Managing configurations of multiple servers and environments is a big benefit of using Ansible. But what happens when configuration files vary from server to server? Rather than create a separate configuration for each server or environment, you should look into Ansible templates.

In this tutorial, you’re going to learn what Ansible templates are, how they work and how you can use the [Ansible template module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_lookup.html#ansible-collections-ansible-builtin-template-lookup) to save tons of time.

## Prerequisites

This post will be a step-by-step tutorial. If you’d like to follow along, be sure you have an [Ansible controller host](https://docs.ansible.com/ansible/latest/installation_guide/index.html). This tutorial will be using Ansible v2.9.18

## What is an Ansible template?

Sometimes you need to transfer text files to remote hosts. Those text files are typically some kind of configuration file. If you’re working with a single server, for example, you might need to create a configuration file called _app.conf_ that some service uses.

That configuration file may contain information specific to that server like hostname, IP address, etc. Since you’re working with a single server, you could create the file on the Ansible controller and then use the [copy module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html) in a [playbook](https://docs.ansible.com/ansible/latest/user_guide/playbooks.html) to copy it to the server.

But what if you have multiple web servers each needing that same configuration file but each with their own specific values? You can’t just copy the configuration file to all machines; it’s only built for a single server with a specific hostname, IP address, etc. You need an Ansible template.

Ansible templates allow you to define text files with variables instead of static values and then replace those variables at playbook runtime.

## What does an Ansible template look like?

An Ansible template is a text file built with the [Jinja2 templating language](https://docs.ansible.com/ansible/latest/user_guide/playbooks_templating.html) with a _j2_ file extension. A Jinja2 template looks exactly like the text file you’d like to get onto a remote host. The only difference is that instead of static values, the file contains variables.

For example, maybe you need to get a configuration file called _app.conf_ on all of your webservers that contains references to each respective server’s IP address, the Ansible host and the Ansible user. A single server’s _app.conf_ file may look like the example below.

```json
my_ip    = "192.168.0.1"
my_host  = "ANSBILECONTROL"
my_user  = "ansible_user"
```

You can’t copy this file to each webserver because each item will be unique depending on the remote host’s IP, the Ansible controller’s hostname, and the Ansible user.

Instead of statically setting each of these values, an Ansible template allows you to define variables that get interpreted at runtime and replaced on the remote host.

Below you’ll find an example of the _app.conf.j2_ template file. You can now see that each static value has been replaced with a variable noted with double curly braces on either side. In this instance, these variables come from [Ansible facts](https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html#ansible-facts).

> _Templates files always have the J2 file extension and typically have the same name as the file they create on the target host._

```json
my_ip    = "{{ansible_default_ipv4["address"]}}"
my_host  = "{{ansible_host}}"
my_user  = "{{ansible_user}}"
```

## How are templated files created on remote hosts?

Once you’ve created a template, you need to get that template file transferred to the remote host and “converted” into the actual text file of what it’s supposed to look like. To do that, you need to reference the template file in a playbook.

Most Ansible admins use the [copy module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html) to transfer files to remote hosts but, as mentioned above, this isn’t feasible with templates.

Below you can see a simple example reference from a playbook that copies the _app.conf_ file to the _/opt_ directory on all the playbook’s target hosts.

```json
- name: copy file from local host to remote host
  copy:                               # Declaring Copy Module 
    src: "app.conf"                   # Source Location 
    dest: "/opt/app.conf"             # Destination Location on remote host
```

Now let’s say you’ve “templatized” the _app.conf_ configuration file to become an _app.conf.j2_ template file covered in the previous section on your Ansible controller. You now need to ensure _app.conf_ still gets to the _/opt_ directory but with the variables replaced with real values.

To tell the playbook to create the _app.conf_ file in the _/opt_ directory, simply replace the `copy` reference to `template` as shown below. When you do this, Ansible then invokes the [template module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_lookup.html#ansible-collections-ansible-builtin-template-lookup) to both transfer the template and replace the variables with static values.

```json
- name: template file to remote host
  template:                 # Ansible template module
    src: "app.conf.j2"      # This is template src i.e source location 
    dest: "/opt/app.conf"   # Destination of Remote host
```

Once the above task in the playbook executes, Ansible will copy the _app.conf.j2_ to the remote host’s _/opt_ directory, replace all variables inside with static values and rename the file to _app.conf_.

> _When you provide the template `src` with a directory path, Ansible looks for templates in the /<ansible\_installation\_directory>/files/ directory. If you simply provide the file name, Ansible will look for the template in the /<ansible\_installation\_directory>/templates/ directory instead._

## Rendering a Configuration File: A Template Example

Let’s now jump into a demo to see how to set up an Ansible template and use the Ansible template module to dynamically generate a configuration file. In this example, you’re creating a file called _app.conf_ in the _/etc_ directory on a server called _SRV1_.

> _The steps in this section will work for any kind of text file. The tutorial will use a configuration file as a single example._

1\. SSH into your Ansible controller host using whatever user you typically use to manage Ansible.

2\. Create a folder in your home directory to hold this tutorial’s demo files and change the working directory to it.

```powershell
mkdir ~/ansible_template_demo
cd ~/ansible_template_demo
```

3\. Create a template file called _app.conf.j2_ in the directory that looks like below.

```json
my_ip = {{ansible_default_ipv4["address"]}}
my_host  = {{ansible_host}}
my_user  = {{ansible_user}}
```

> _You can also use [various variables specific to the Ansible template module itself](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html) in your template._

4\. Create a simple playbook in the same directory called _my\_playbook.yml_. This playbook creates the _app.conf_ file in the _/etc_ directory.

```json

name: Ansible template example 
hosts: myserver 
remote_user: ubuntu   # Using Remote host as ubuntu 
tasks: 
 - name: Create the app.conf configuration file
   template:
     src: "~/ansible_template_demo/app.conf.j2"
     dest: "/etc/app.conf"
   become: true 
```

5\. Invoke the Ansible playbook targeting the _SRV1_ remote host.

```bash
ansible-playbook my_playbook.yml --inventory SRV1
```

![You should then see Ansible execute the playbook. ](https://adamtheautomator.com/wp-content/uploads/2021/03/Untitled-2021-03-20T102009.577-1.png)

You should then see Ansible execute the playbook.

6\. Now confirm the _/etc/app.conf_ configuration file exists and has the expected values.

![confirm the /etc/app.conf configuration file](https://adamtheautomator.com/wp-content/uploads/2021/03/Untitled-2021-03-20T102113.021.png)

confirm the _/etc/app.conf_ configuration file

## Updating File Permissions with the Template Module

Now that you’ve seen the basics of using the template module, let’s now get a bit more advanced. For this demo, you’re going to create the same _app.conf_ file as previously shown. But this time, you’re going to set the file owner and permission on that file.

Related:[A Windows Guy in a Linux World: User and File Permissions](https://adamtheautomator.com/linux-file-permissions/)

To change permissions on the file that the template module creates, you must use three parameters inside of the playbook:

*   **owner –** The file owner
*   **group** – The group the file should be member of
*   **mode** – The permissions. This string can be either expressed in symbols or as octal numbers

> _In symbolic mode, `u` represents “user”, `g` represents “group” and `o` represents “other”._

Assuming you still have the _~/ansible\_template\_demo_ folder created from the previous section, open the _my\_playbook.yml_ playbook and replace the contents with that below. In this example, Ansible will set the owner and group to the Ansible user using [connection variables](https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html#connection-variables). It then sets the file permissions to `0644` which represents:

*   Owner has read/write permission
*   Users in the group and everyone else has read permission

```json
---
- name: Ansible file permission example
  remote_user: ubuntu
  tasks:
    - name: Create the app.conf configuration file and assign permissions
      template:
          src: "~/ansible_template_demo/app.conf.j2"
          dest: "/etc/app.conf"
	  owner: "{{ ansible_user }}"
          group: "{{ ansible_user }}"
          mode:  0644 ## OR  mode: u=rw, g=w,o=r       
      become: true
```

> _You can find all of the available template module parameters in the [Ansible template module documentation](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html)._

Now, execute the playbook again as shown below.

```bash
ansible-playbook my_playbook.yml --inventory SRV1
```

You can now see the _app.conf_ has the expected file permissions assigned to it.

![app.conf](https://adamtheautomator.com/wp-content/uploads/2021/03/Untitled-2021-03-20T102320.833.png)

_app.conf_

## Using Loops to Template Multiple Files

Sometimes a single file isn’t enough; you need to add multiple files on a remote host. In that case, you can use the loops with the template module. Defining a loop using the `loop` parameter allows you to add many text files stored in a directory.

Assuming you still have the _~/ansible\_template\_demo_ folder created from the previous section, you should already have the _app.conf.j2_ in there.

1\. Create a second template file called _app2.conf.j2_ in the _~/ansible\_template\_demo_ folder as shown below.

```json
 template_host = "{{ template_host }}"
 template_uid = "{{ template_uid }}"
 template_path = "{{ template_path }}"
 template_fullpath = "{{ template_fullpath }}"
 template_run_date = "{{ template_run_date }}"
```

2\. Open the _my\_playbook.yml_ book and replace all contents with the below YAML. This playbook uses the `{{item}}` variable to represent each template file processed in the loop. The `loop` parameter then defines each of the template files for the loop to process.

```yaml
---
- name: Ansible file permission example 
  remote_user: ubuntu 
  tasks: 
   - name: Create the app.conf configuration file and assign permissions 
     template:   
        src: "~/ansible_template_demo/{{item}}.j2"    # Iterates over 2 templates   
        dest: "/etc/{{item}}"
        owner: "{{ ansible_user }}"   
        group: "{{ ansible_user }}"   
        mode:  0644 ## OR  mode: u=rw, g=w,o=r        
     become: true     
     loop: # Tell the template module to find each of these templates and process                                              
      - app1.conf 
      - app2.conf 
```

3\. Now run the playbook again. `ansible-playbook my_playbook.yml --inventory SRV1`

```bash
ansible-playbook my_playbook.yml --inventory SRV1
```

![Notice now that Ansible sees each template file and processes them accordingly. ](https://adamtheautomator.com/wp-content/uploads/2021/03/Untitled-2021-03-20T102604.329.png)

Notice now that Ansible sees each template file and processes them accordingly.

## Conclusion

Ansible templates and the template module can save you tons of time and create dynamic text files on all of your remote hosts. The copy module provides similar functionality but if ever need to create dynamic text files, the template module is your friend.

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-template%2F&text=How%20to%20Create%20Ansible%20Templates%20to%20Save%20Configuration%20Time)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fansible-template%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-template%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2021/04/A-Step-by-Step-Guide-to-Getting-Started-with-Ansible-on-Windows.jpg)

### [Mastering Ansible on Windows: Your Go-To Expert Guide](/ansible-on-windows/)

Ansible on Windows made simple. A complete guide to hassle-free installation and configuration, perfect for users seeking quick and effective mastery.

![](https://adamtheautomator.com/wp-content/uploads/2022/10/How-to-Manage-Python-Libraries-with-Ansible-Pip.jpg)

### [How to Manage Python Libraries with Ansible Pip](/ansible-pip/)

Learn how to effectively manage Python libraries with the Ansible Pip module and take control of your Python dependencies!

![](https://adamtheautomator.com/wp-content/uploads/2022/06/Highly-Effective-Automation-with-Ansible-AWX.jpg)

### [Highly Effective Automation with Ansible AWX](/ansible-awx/)

Learn how Ansible AWX can take your Ansible playbooks to the next level and automate all the things with this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
