Ansible is using the Python lib socket to fill the fqdn and domain value in the facts (ansible_facts).

But for the hostname, it uses the lib platform.

And of course, as their names suggest it, they are retrieving the data with different approach:

  • socket uses sockets and thus the network (in this cas: DNS resolution)
  • platform only works locally

The lib socket can sometimes be weird!

In a corner case I encountered (see also https://bugs.python.org/issue5004):

  • OpenBSD
  • no DNS records
  • an entry in /etc/hosts ( my.host.localdomain)

the domain value in ansible_facts was empty and thus unexpected behaviours occured. The lib socket was obviously lost…

To avoid such problem, the solution is to rely only on the lib platform.

So replace your ansible_facts['domain] with:

ansible_facts['nodename'].split('.')[1:] | join('.')

And your ansible_facts['fqdn] with: