Inline template into variable

Hi there,

I’ve been trying to do something I think I already saw done, but I can’t get it to work: I want to parse an inline template into a variable.

Everything I find is either to file (ansible.builtin.template task), template lookup from a template file, or just mentions regular {{ var }} templates, which are obvious, but I need loops and the fancy bits of jinja :-p

In essence, I have a nested dict:

config:
  default:
    instance: prodbox
  auth:
    admin_user: francis
    admin_password: heloveshismomandcatandpancakes
  database:
    type: mysql
    schema: pancake
    user: mom
    password: kitty99

And I need to build that into a bunch of individual lines in a variable that basically flatten the structure.

I’ve tried a million variations of this task:

    - ansible.builtin.set_fact:
        config_blob: |-
          {% for section, conf in config %}
            {% for key, value in conf %}
              {{ 'GF_' + section | upper + '_' + key | upper + '=' + value }}
            {% endfor %}
          {% endfor %}

but depending on the variation, I get errors about unexpected % signs, something not being able to convert to dict or list, etc.

Any help would be appreciated. Being told that my memory is broken and it totally isn’t possible is less fun but would at least put me at rest to find a less elegant solution with tempfiles :slight_smile:

If you need key and value in the loop you’d need to use .items() method on the dictionary to convert it to key-value tuples.

Also, note that whitespace is preserved in the loops, so you might not want the nesting.

Try this:

{% for section, conf in config.items() %}
{% for key, value in conf.items() %}
{{ 'GF_' + section | upper + '_' + key | upper + '=' + value }}
{% endfor %}
{% endfor %},'
2 Likes

There is also the ansible.builtin.dict2items filter and since it looks like you are writing conf/ini format you might also consider the community.general.ini_file module and the community.general.to_ini filter.

@chris It’s not ini or toml, it just looks a little like it - and I’m also not writing it, as I said, I need it in a var.

@kristianheljas has pointed out exactly what I was missing - and I actually used that before, but apparently I’m getting old and forgetful :slight_smile: . Marking as solved, thank you !

2 Likes

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