Jie
Jie

Reputation: 45

AnsibleUnderfinedVariable: 'dict object' has no attribute 'ansible_fqdn'

I want to get the fqdns of remote hosts, and I planned to get it by:

{% for host in groups['all'] %}
Hello {{ hostvars[host]['ansible_facts']['ansible_fqdn'] }}
{% endfor %}

but then I got an error saying "AnsibleUnderfinedVariable: 'dict object' has no attribute 'ansible_fqdn'", but I can get the information of a fqdn by this command:

$ ansible all -m setup -a "filter=*fqdn*"
172.25.250.9 | SUCCESS => {
    "ansible_facts": {
        "ansible_fqdn: "workstation.lab.example.com",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

So my confusion is Why I can get the variable by setup in a command line, but can't do by a playbook? Can you rescue me? Thanks a lot!

Upvotes: 0

Views: 1639

Answers (1)

larsks
larsks

Reputation: 311387

I believe you're looking for:

{% for host in groups['all'] %}
Hello {{ hostvars[host]['ansible_fqdn'] }}
{% endfor %}

This requires that you've gathered facts on all the hosts in your inventory; otherwise, facts like ansible_fqdn won't be available. You may want to handle missing values more gracefully:

{% for host in groups['all'] %}
Hello {{ hostvars[host]['ansible_fqdn']|default("(missing)") }}
{% endfor %}

For example:

# This play is necessary to gather facts on all the hosts
# in our inventory.
- hosts: all
  gather_facts: true

# Now we can use host facts in our templates.
- hosts: localhost
  gather_facts: true
  tasks:
    - debug:
        msg: |-
          {% for host in groups['all'] %}
          Hello {{ hostvars[host]['ansible_fqdn']|default("(missing)") }}
          {% endfor %}

Upvotes: 2

Related Questions