FreeKB - Ansible Role Template Files (edit a file j2)
Ansible - Role Template Files (edit a file j2)

Role Templates are similar to Role Files and the copy module. Each are used to copy a file from the control node (that's your Ansible server) to managed nodes (the target systems). The big difference is that template files can contain jinja2 references, whereas Role Files cannot.

At a bare minimum, three playbook are needed to copy a template file to your managed nodes.

  • The playbook that invokes the role that contains the template file
  • The roles main playbook (e.g. /etc/ansible/roles/foo/tasks/main.yml)
  • The template file (e.g. /etc/ansible/roles/foo/templates/bar.j2)

For example, let's say you have a role named foo. The playbook that invokes the foo role would look something like this.

---
- hosts: all
  roles:
    - role: foo
...

 

The foo role main playbook would look something like this. In this example, a template file named bar.j2 will be copied to each managed node.

- name: copy bar.j2 to /tmp/bar.txt
  template:
    src: bar.j2
    dest: /tmp/bar.txt

 

Template files are placed in a roles templates directory. In this example, bar.j2 would be placed in the foo roles templates directory.

/etc/ansible/roles/foo/templates/bar.j2

 

Let's say bar.j2 contains the following.

My favorite fruit is {{ fruit }}

 

Since bar.j2 contains a jinja2 reference named fruit, you would define the fruit variable. Refer to Ansible - Getting Started with Variables to understand the various ways to create variables. Let's say you define the fruit variable using the --extra-vars command line option.

ansible-playbook example.yml --extra-vars "fruit=banana"

 

Running this play will create the /tmp/bar.txt file on the managed node, and the bar.txt file will have something like this.

My favorite fruit is banana

 


Be aware that certain markup in a template file may produce unexpected errors. Let's say bar.j2 contains the following.

LogFormat "%{%Y-%m-%d %T}t"

 

When attempting to copy bar.j2 to your managed nodes, the play may fail and return something like this. This is occurring because {%Y is built in Jinja2 syntax.

Encounted unknown tag 'Y'

 

In this scenario, raw and endraw are used to remedy this issue.

{% raw %}LogFormat "%{%Y-%m-%d %T}t"{% endraw %}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 1c2d6 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |