Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering Ansible template into the fact variable

Tags:

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.

like image 435
kay Avatar asked Jan 02 '17 10:01

kay


People also ask

How do I use Ansible template module?

You can use Ansible facts, variables, and user-defined variables in your Jinja2 templates. On your Jinja2 template, you can print the value of a variable using the {{ variableName }} syntax. If the variable is an object, you can print individual object properties using the {{ objectVariable. propertyName }} syntax.

What is the difference between template and copy module in Ansible?

While very similar, template serves an extra function. copy takes a file from host, "as-is", and copies it to the remote destination.

What is .j2 file in Ansible?

Jinja2 templates are simple template files that store variables that can change from time to time. When Playbooks are executed, these variables get replaced by actual values defined in Ansible Playbooks. This way, templating offers an efficient and flexible solution to create or alter configuration file with ease.

Why is Jinja2 used in Ansible?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts. You can use templating with the template module.


1 Answers

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"   } 
like image 68
techraf Avatar answered Dec 16 '22 10:12

techraf