Ansible template Module

 It puts the files onto a remote system using jinja2 templating language.

Ansible template Module

Example: Template a single file

   Step 1: Create a file called my_app.conf.j2 and add below content

env = {{ env }}

local_id = {{ ansible_host }}

local_OSFamily = {{ ansible_facts['os_family'] }}

local_OS = {{ ansible_distribution }}

Step 2: Create a ansible play book lets call it template.yaml

---

 - name: Parsing Jinja2 templates

   hosts: "*"

   vars:

     env: staging

   tasks:

     - name: template file onto remote hosts

       template:

         src: my_app.conf.j2

         dest: /tmp/myconfigfile


Step 3: Execute the template playbook and then check on each host machine there will be a /tmp/myconfigfile and the parsed value jinja2 file.

   ansible-playbook template.yaml

Example Set Permission for parsed jinja file

---

 - name: Parsing Jinja2 templates

   hosts: "*"

   vars:

     env: staging

   tasks:

     - name: template file onto remote hosts

       template:

         src: my_app.conf.j2

         dest: /tmp/myconfigfile

     - name: change the permission for the parsed jinja file

       file:

          path: /tmp/myconfigfile

          owner: raman

          mode: '0600'

Example Template Multiple files.

Create one more .j2 file let's say my_host.conf.j2

and write following content

OS = {{ ansible_distribution }}


Create a template.yaml file

---

 - name: Parsing Jinja2 templates

   hosts: "*"

   vars:

     env: staging

   tasks:

     - name: template file onto remote hosts

       template:

         src: '{{ item.src }}'

         dest: '{{ item.dest }}'

       with_items:

               -   { src: my_app.conf.j2, dest: /tmp/myconfigfile }

               -   { src: my_host.conf.j2, dest:  /tmp/myhostconfigfile}

     - name: change the permission for the parsed jinja file

       file:

          path: /tmp/myconfigfile

          owner: raman

          mode: '0600'


Example user loop

Create a jinja file let's call it users.j2

[user]
  name = {{ user.name }}
  username = {{ user.username }}
  email = {{ user.username }}@example.com

Create a playbook that stores the parsed value of the jinja template on remote host machines.

---
 - name: play for template
   hosts: "*"
   vars:
     users:
          - name: John Smith
            username: jsmith
          - name: Mohit Singh
            username: msingh
   tasks:
    - name: users
      user:
        name: "{{ user.username }}"
        comment: "{{user.name }}"
        state: present
      loop: "{{ users }}"
      loop_control:
         loop_var: user
    - name: processing jinja template
      template:
        src: users.j2
        dest: "/home/{{ user.username }}/gitconfig"
      loop: "{{ users }}"
      loop_control:
        loop_var: user

Comments