Tag Archives: facts

Ansible: Simple template example within a role

Here, we create a role which a) deploys a file into /tmp and b) demonstrates the use of a host variable to modify the contents of this file. As the contents is dynamic we use the ‘template’ module, rather than file.

Using Ansible Galaxy we create the role directory structure:-

steve@devbox:~$ cd ~ansible/roles
steve@devbox:~/ansible/roles$ ansible-galaxy init testtmp
- testtmp was created successfully

Let’s go ahead and create our template file:-

steve@devbox:~/ansible/roles$ cd testtmp/templates
steve@devbox:~/ansible/roles/testtmp/templates$ vi tmp.conf

Swap Free = {{ ansible_swapfree_mb }}

The {{ ansible_swapfree_mb }} indicates a variable (in this case, a host fact).

Now create a simple task top deploy the above template:-

steve@devbox:~/ansible/roles/testtmp/templates$ cd ../tasks/
steve@devbox:~/ansible/roles/testtmp/tasks$ vi main.yml 

---
# tasks file for testtmp
- name: Drop template into /tmp
  template: src=~/ansible/roles/testtmp/templates/tmp.conf dest=/tmp/tmp.txt

We now modify (or create) our site.yml:-

steve@devbox:~/ansible/roles/testtmp/tasks$ cd ~/ansible/
steve@devbox:~/ansible$ ls
roles  site.yml
steve@devbox:~/ansible$ vi site.yml 

---
- name: Deploy test roles
  hosts: all
  become: true

  roles:
    - time
    - testtmp

Now let’s run the playbook:-

steve@devbox:~/ansible$ ansible-playbook site.yml

PLAY [test ntp via time role] **************************************************

TASK [setup] *******************************************************************
ok: [172.0.0.1]

TASK [time : Install NTP] ******************************************************
ok: [172.0.0.1]

TASK [testtmp : Drop template into /tmp] ***************************************
changed: [172.0.0.1]

PLAY RECAP *********************************************************************
172.0.0.1                  : ok=3    changed=1    unreachable=0    failed=0   

Success! Let’s hit the target and check the actual changes:-

steve@devbox:~/ansible$ ssh 172.0.0.1
...
Last login: Tue Nov 22 12:55:29 2016 from 172.0.0.2
steve@testtarget:~$ ls -l /tmp
total 4
-rw-r--r-- 1 root root 17 Nov 22 12:55 tmp.txt
steve@testtarget:~$ cat /tmp/tmp.txt 
Swap Free = 767

Yes! The template is deployed and the variable is set correctly.