all in inventory does not resolve in template

I am doing this in a template to generate /etc/hosts

{% for item in groups[‘all’] %}
{{ hostvars[item][‘ansible_ssh_host’] }} {{ item }}
{% endfor %}

My inventory looks like this:

[emmaxd:children]
application_servers
utility_servers
postgres_master
alfresco_application

alfresco_database
alfresco_storage

[application_servers]
apbe01 host_alias=apbe01 ansible_ssh_host=10.124.1.1

[utility_servers]
apbe01

[postgres_master]
apbe01

[alfresco_application]
apbe02 host_alias=apbe02 ansible_ssh_host=10.124.1.2

[alfresco_database]
apbe02

[alfresco_storage]
apbe02

If I replace groups[‘all’] with groups[‘emmaxd’] it works. If I don’t, this error:

fatal: [emmaxdapbe01] => {‘msg’: “AnsibleUndefinedVariable: One or more undefined variables: ‘dict object’ has no attribute ‘ansible_ssh_host’”, ‘failed’: True}
fatal: [emmaxdapbe01] => {‘msg’: “AnsibleUndefinedVariable: One or more undefined variables: ‘dict object’ has no attribute ‘ansible_ssh_host’”, ‘failed’: True}

Why does it not resolve [‘all’] to every machine in the inventory?

First,do NOT use item as it overloads the existing variable from loops

The error you are getting is because not all hosts have ansible_ssh_host defined but all those in emmaxd group do

Good point about item! Would it be better to declare the inventory like this?

[emmaxd]

apbe01 host_alias=apbe01 ansible_ssh_host=10.124.1.1

apbe02 host_alias=apbe02 ansible_ssh_host=10.124.1.2

[application_servers]
apbe01

[utility_servers]
apbe01

[postgres_master]
apbe01

[alfresco_application]
apbe02

[alfresco_database]
apbe02

[alfresco_storage]
apbe02

This made no difference. I’m confused as to how to use [‘all’]. Am I making bad choices in how I organise the inventory?

check:

ansible -m debug -a “msg={{ansible_ssh_host|default(‘MISSING’)}}” all -i /path/to/your/inventory

Brilliant. Found the problem. Somehow “—” had made into the inventory.