Ansible: Templates

This blog receives a commission from affiliate partners through the affiliate links that we share with you in our posts. Although we receive a commission for using and linking their products, all our opinions and suggestions are unbiased.

Ansible templates:

  • Templates will copy the source file to the target host destination.
  • While the template module gets executed it will read the template file and change all the variables to its value and copy the file to the target host.
  • Template file ends with .j2 extension which stands for Jinja2 templates.


Create a directory.

#mkdir templates

Sample template file.

#vi templates/file.j2


<h1> Hello! Venkat </h1>

<h1> GoodDay {{username}} </h1>


Ansible Templates in Playbooks:

#vi playbooks/pb1.yml

- hosts: dev
- username: Venkat
- file_path: /var/www/html
- name: Copy site files
src= templates/file.j2
dest= {{file_path}}/index.html mode=0777

–> Use template module to copy the template file and the variables used in the template.

Ex-2: To change Tomcat port

#vi templates/demo.j2


<Connector port= "{{myport}}"
protocol= "HTTP/1.1"

(server.xml content)

After changing the Port edit the playbook.

#vi playbooks/pb2.yml

- hosts: web
become: true
- myport: 9090
- file_path: /etc/tomcat7/
- name: to update packages
apt: update_cache=yes

- name: to install java
state: latest

- name: to install tomcat
name: tomcat7 
state: latest
- name: to change tomcat port
src: templates/demo.j2
dest: {{file_path}}/server.xml
- restart tomcat

- name: restart tomcat
name: tomcat7
state: restarted

Venkata Narayana Yarava

Venkata Narayana Yarava is an experienced Cloud DevOps Engineer with exposure to various technologies, he has a experience in DevOps Training and with different IT environments. He has a huge passion for automation technologies, specifically DevOps Tools, OpenStack, AWS, Linux, open source software. If you enjoy our articles please support us and make a small contribution: Buy Us A Coffee