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.
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.
While very similar, template serves an extra function. copy takes a file from host, "as-is", and copies it to the remote destination.
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.
Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts. You can use templating with the template module.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With