Home » Ansible Templates

Ansible Templates

by Online Tutorials Library

Ansible Templates

Ansible is used to manage configurations of multiple servers and environments. But these configuration files can vary for each cluster or remote server. But apart from a few parameters, all other settings will be the same.

Creating static files for each of these configurations is not an efficient solution. It will take a lot of time, and every time a new cluster is added, then you have to add more files. If there is an efficient way to manage these dynamic values, it would be beneficial. This is where Ansible template modules come into play.

A template is a file that contains all your configuration parameters, but the dynamic values are given as variables in the Ansible. During the playbook execution, it depends on the conditions such as which cluster you are using, and the variables will be replaced with the relevant values.

You can do more than replacing the variables with the help of the Jinj2 templating engine. You can have loops, conditional statements, write macros, filters for transforming the data, do arithmetic calculations, etc.

Usually, the template files will have the .j2 extension, which denotes the Jinja2 templating engine used.

The double curly braces will denote the variables in a template file, ‘{{variables}}’.

We need to have two parameters when using the Ansible Template module, such as:

  • src: The source of the template file. It can be a relative and absolute path.
  • dest: Dest is the destination path on the remote server.

Template Module Attributes

Here are some other parameters which can be used to change some default behavior of the template module:

  • Force: If the destination file already exists, then the Force parameter will decide whether it should be replaced or not. By default, the value is yes.
  • Mode: This parameter is used to set the permissions for the destination file explicitly.
  • Backup: If you want a backup file to be created in the destination directory, you should set the value of the backup parameter to yes. By default, the value is no. and the backup file will be created every time there is a change in the destination directory.
  • Group: Name of the group that should own the directory. It is similar to executing chown command for a file in Linux systems.

Example

In the below example, we are using the template module on the example1.j2 file that replaces the default variables with values given in the playbook.

File: Playbook.yml

File: example1.j2

File: output.txt

Hello  No change in this line  My first playbook using the template  

You can see, their values replace both variables in the example1.j2 in the above example.


Next TopicAnsible YAML

You may also like