Ansible Templates

Ansible_Logo

Ansible templates allows users to dynamically generate text-based files using templates, variables, and facts for configuration and other purposes.

The difference between Ansible Facts and Templates is as follows:

An ansible Fact stores variables that can be used by a playbook when executed

An ansible template, which used ansible facts and pulls values of variable defined in facts, used them to create files which incorporates these values.

Let us create a template file in the controller node in Jinja format:

[root@centos9vm ~]# cat template.j2

===== ====
Welcome to the {{ ansible_facts[‘hostname] }} from the {{ ansible_facts[‘fqdn’] }}

===== ===

Let us create a playbook to copy the template to managed node and execute the playbook to create a new file

[root@centos9vm ~]# cat example7.yml

===== ====
    – – –
    – name: Share the jinja tempate with values to managed node
        hosts: testGRP
        tasks:

            – name: Using copied template to generate file
                ansible.builtin.template:
                    src: /root/template.j2
                    dest: /root/file_created_from_template.txt
==== ====

[root@centos9vm ~]# ansible-navigator run -m stdout example7.yml

===== ====

PLAY [Share the jinja tempate with values to managed node] *********************

TASK [Gathering Facts] *********************************************************
ok: [192.168.48.129]

TASK [Copy the template.j2 file to managed node] *******************************
changed: [192.168.48.129]

TASK [Using copied template to generate file] **********************************
changed: [192.168.48.129]

PLAY RECAP *********************************************************************
192.168.48.129 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

===== ===

Let us verify if the file got created in the managed node

[root@centosMYOBvm ~]# cat file_created_from_template.txt

===== ==== ==
Welcome to the centosMYOBvm from the centosMYOBvm