Ansible

How to use Ansible Jinja template

In this blog, we will see how we can use the Ansible Jinja template and how it helps in the automation.

If you want to see the video for this article, click here

Problem Statement:

  • In many applications, you always have some property file which stores all the variables like database details,memory setting, JAVA VM arguments etc.
  • And that property file can have different values across environments.

Solution:

  • Create a file test.properties.j2 under templates folder in your ansible playbook
  • Create all the variables which are required in your template file

Option 1 —  How to use the variable directly

test.jdbc.maxActive={{ test_jdbc_maxactive | default('60') }}

Option 2 —How to use if/else condition in your template file and then use variables

{% if test_db_embedded %}
test.embeddedDatabase.port={{ test_db_embedded_port | default('8080') }}
{% else %}
test.jdbc.username={{ test_db_user }}
test.jdbc.password={{ test_db_pass }}
test.jdbc.url={{ test_jdbc_url }}
{% endif %}

How to use it in playbook

- name: "copy properties file"
template:
src: "test.properties.j2"
dest: "test/test.properties"
Please follow and like us: