1

I am trying to iterate through a list using jinja2 template. I have the following variables defined

vars:
  app_name: testapp
  testapp_env_vars:
    - name: environment
      value: prod
    - name: type
      value: api

I want to check the following

1) Whether the list "test_app_env_vars" is defined

2) if defined, then iterate through the key-value pair in the list using FOR loop and print the following

environment: prod
type: api

I tried using the following template, but its failing

{% if {{ app_name }}_env_vars is defined %}
{% for item in {{ app_name }}_env_vars %}
{{ item.name }}: {{ item.value }}
{% endfor %}
{% endif %}

where "app_name" = "testapp" which is already defined in the vars section.

Any idea why { app_name }}_env_vars inside IF condition is not evaluating to testapp_env_vars?

Muhammed Roshan
  • 81
  • 1
  • 1
  • 4
  • You cannot use Jinja2 expressions inside Jinja2 statements. To refer to a value with a dynamic variable name in Ansible, see the answer under the dup-target. – techraf May 22 '18 at 08:38
  • @techraf Thanks for the response. I want to do this within Jinja template file using "IF" condition, not from the Ansible tasks. – Muhammed Roshan May 22 '18 at 08:47
  • Yes. The same answer applies. – techraf May 22 '18 at 08:48
  • I added the following in the template file myvar: '{{ lookup('vars', {{ ocp_deployment_app }} + '_env_vars')}}' But I am getting this error fatal: [localhost]: FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'. String: myvar: '{{ lookup('vars', {{ ocp_deployment_app }} + '_env_vars')}}'\n"} – Muhammed Roshan May 22 '18 at 09:18
  • I already said, you cannot nest Jinja2 expressions inside Jinja2 expressions. Once you open `{{` you are writing Jinja2 code. And lookup will fail on its own when variable does not exist; use `vars` as suggested at the top of the answer under the dup-target. – techraf May 22 '18 at 09:19
  • Could you please show me an example of doing this ? – Muhammed Roshan May 22 '18 at 09:21
  • StackOverflow is not a tutoring site, but here you are: `{% if vars[app_name + '_env_vars'] is defined %}` – techraf May 22 '18 at 09:22
  • @techraf Thanks, it worked. – Muhammed Roshan May 23 '18 at 02:50

0 Answers0