-1

We have several playbooks that use hostvars[item]['ansible_nodename'] where item is a host alias. It usually works. But sometimes does not, giving the following error:

'dict object' has no attribute 'ansible_nodename` 

I printed the contents of hostvars and did not see this attribute there.

I could not find the documentation of hostvars to be able to see what we can safely use instead ansible_nodename. So, the questions are:

  • Can I safely replace ansible_nodename with ansible_host?
  • Where can I find a description of the contents of hostvars and algorithm of its creation?
GMichael
  • 2,726
  • 1
  • 20
  • 30
  • `hostvars` contain facts gathered from multiple sources (inventory, regular gather_facts, local facts, facts defined during the run). There is no single description, they also depend on OS. "*Where can I find a description*" is off-topic for SO, "*Can I safely replace*" is too broad. You should already know that with 2k rep. – techraf Jan 17 '18 at 09:29
  • Please keep your Questions to one question per Question. Questions which contain multiple questions which are not *very* tightly related are considered too broad and tend to be closed. The reason for this is that the Stack Overflow format is intended to provide a base of questions and answers which are useful to people in the future, not just the person currently asking. Questions with multiple issues tend to be too specific to be useful to others searching for help to their problems. Often, to solve a larger issue it is necessary to combine the answers from multiple questions. – Makyen Jan 17 '18 at 23:14

1 Answers1

7

But sometimes does not, giving the following error...

This can be because facts for those hosts are not gathered at that moment in time.

You may want to add empty play to gather facts for all hosts at the very top of your playbook:

- name: gather facts
  hosts: all

- name: balancer configuration
  hosts: balancer
  tasks:
    - name: generate configs
      template:
        src: conf.j2
        dest: "/conf/{{ hostvars[item]['ansible_nodename'] }}.conf"
      with_hostnames: nodes

Without 'gather facts' play, configuration task for balancer will fail because ansible_nodename is not gathered.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193