Render Jinja2 template into variable

Hello there,

I’m have a kind of big variable to build that is containing a JSON payload. I was thinking of using a Jinja2 template file alongside to describe the content and render it into the variable. The only thing I could come up with is using something like:

"{{ lookup('template', './myTemplate.j2') }}"

as in:

tasks:
      - debug:
          var: rendered_template
        vars:
          rendered_template: "{{ lookup('template', './myTemplate.j2') }}"

Is this the way it should be achieved or am I doing something very wrong? Or is the idea of rendering into a variable even flawed to the core :grimacing: ?

Thanks in advance,

Json is very easy to manipulate as variables in Ansible. If your json payload is already saved to disk as a raw file, you can use {{ lookup('file', 'payload.json') | from_json }}.

tasks:
  - debug:
      msg: "{{ payload.data[0].properties }}"
    vars:
      payload: "{{ lookup('file', 'payload.json') | from_json }}"

Templates are jinja2 files that contain variables that need to be replaced… although technically they don’t have to have any variables and be a plaintext json file. It would still work, but would waste some overhead on loading the jinja2 libraries and processing the file.

On the other hand, if you’re querying the json payload from an API using the uri: module for e.g., you can just register the module’s output directly to a variable.

1 Like

The idea in my case is that this payload has to be rendered first because there are indeed some variables that need to be replaced by Jinja2.

Then yes, what you’re doing would work more or less. Ansible is pretty good about interpreting json, but piping to from_json to make sure wouldn’t hurt.

Edit: in fact, piping to from_json would make sure your rendered json is well-formatted. Your template could potentially render successfully and register to the variable as a malformed-json and you wouldn’t know until later in the play.

4 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.