0

Is writing a file the only way to render an ansible template? In the past, with python and jinja2, I've rendered jinja templates to python vars directly and was hoping I can do the same with ansible.

What I'm trying to do is take the content of my template and pipe it to another command without writing the template to a file on disk and cat'ing the file. Doable?

user797963
  • 2,907
  • 9
  • 47
  • 88

1 Answers1

2

You have several options for creating a variable from a template. For small templates, you can just use an inline template with set_fact:

- name: render a template to a variable
  set_fact:
    myvar: |-
      This is a template.
      This host is {{ inventory_hostname }}.

For longer templates, you can use the template lookup:

- name: render a template to a variable
  set_fact:
    myvar: "{{ lookup('template', 'template_name.j2') }}"

And of course this isn't limited to the set_fact module. You can do this anywhere you can put a string value in Ansible.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • Nice, this is great. Is it possible to tell if a template updated the same way you can if you use the template module and specify a dest? For example, I would only want to complete the task if the template has been updated. Not a big deal, just wondering and I haven't been able to find this in the doc. – user797963 Jul 29 '20 at 19:11
  • Detection of updates works because the result of rendering the template doesn't match the target file. When you're rendering to a variable, there is no previous content, so from that perspective there is always a change. – larsks Jul 29 '20 at 20:00