AttributeError when accessing groups in ansible jinja template

745 Views Asked by At

I am running an ansible playbook with the following inventory structure:

[appservers]
xy.example.com

[db_servers]
abc.example.com

In a task of a role, the template command is executed with a jinja templace having the following code:

{% for host in groups["appservers"] %}
print host: {{ host }}
{% endfor %}

However, execution of this task fails with the message:

fatal: [xy.example.com]: FAILED! => {"msg": "UndefinedError: 'list object' has no attribute 'appservers'", "failed": true, "changed": false}

From all examples I found, this should be possible, since groups["appservers"] should be a dict, which can be used to iterated over in a template as explained here

Do you know what is wrong with my code or how I can debug the error?

If I change the template code to

{% for host in groups %}
print host: {{ host }}
{% endfor %}

The resulting file contains

print host: appservers
print host: all
print host: db_servers
1

There are 1 best solutions below

0
On

This question does not contain enough information and should be edited or deleted as it cannot be reproduced with this simple amount of information.

It is possible that the group is missing during the run of the task trying to render the list.

As suggested in the comment you should try to debug the variable with another task before trying to render the template

- debug: msg: '{{ groups }}'

Ansible is capable of dynamically allocating hosts to groups, therefore one intuition could be that the order of inventory creation is not complete, or perhaps there is a bug in a dynamic inventory script, or some other reason for the group missing.