34

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
kay
  • 693
  • 2
  • 7
  • 13

1 Answers1

60

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"
      }
    
Thomas Decaux
  • 21,738
  • 2
  • 113
  • 124
techraf
  • 64,883
  • 27
  • 193
  • 198
  • 2
    Up-to-date link to documentation: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_lookup.html P.S. Can't edit post since 'Suggested edit queue is full' – user2988142 Aug 18 '22 at 11:44
  • This solution is not suitable for every use case, as set_facts doesn't change the variable value. So if another task depends on on a change, it will not run. – alixander Nov 22 '22 at 15:51