Rendering Ansible template into the fact variable

kay picture kay · Jan 2, 2017 · Viewed 13.3k times · Source

Is there a way to render Ansible template into the fact? I tried to find a solution but it looks like temp file is the the only way.

Answer

techraf picture techraf · Jan 2, 2017

I think you might be just looking for the template lookup plugin:

- set_fact:
    rendered_template: "{{ lookup('template', './template.j2') }}"

Usage example:

  • template.j2

      Hello {{ value_for_template }}
    
  • playbook.yml

      ---
      - hosts: localhost
        gather_facts: no
        connection: local
        vars:
          value_for_template: world
        tasks:
          - debug:
              var: rendered_template
            vars:
              rendered_template: "{{ lookup('template', './template.j2') }}"
    
  • The result:

      TASK [debug] *******************************************************************
      ok: [localhost] => {
          "rendered_template": "Hello world\n"
      }