After doing some preliminary code review on the path followed for the facts import; I've at least got a better understanding on what's going on here. Seems it is expected, by the API, that facts for a none existing host create a new one:
https://github.com/theforeman/foreman/blob/develop/app/controllers/api/v2/hosts_controller.rb#L280
A little bit further down the line, it can be observed that the import_host is being called, which in turn searched either by certname, if it is provided or falls back to a regular "name" search, based upon hostname:
https://github.com/theforeman/foreman/blob/8a76900b31d4a6bb18852a7803e85d0c6e54be23/app/models/host/base.rb#L111
So, looks to me there are 2+1 possibilities:
- Either we adapt the callback script from ansible to always send facts based upon the system's hostname (and not the inventory hostname); but this probably is brittle and there are probably use-cases in which this isn't the safest route to take
- Adapt foreman to look for a host by name, but, in case none is found, try to do a deep search for a hostname associated to any of a host's network interfaces. (Not sure if there is already such a function available). I propose this one, as it is a controlled way moving forward. Tests can be easily written for this and have no further dependencies.
(-) Override the find by name function for a host altogether, making it always look for a hostname on all registered NICs. This would also have, as a side effect, that one could search in the foreman UI for any hostname and it would return the correct host. This might be dangerous and would need a more in depth review before we could think about proposing this one. I just gave this one for completeness sake; in case somebody things this should be the winning proposal.
Thought? Proposals? Recommendations?
(My final 5 cents is, I don't really think this issue is related to just Ansible?)