Nicolas Stojanovic
Nicolas Stojanovic

Reputation: 1

Ansible collect facts from server not part of the inventory

I want to collect remote facts from hosts that are not in my inventory.

"{{ record[1] }}" is the host I want the facts from.

I'm using:

- name: Gather facts
  ansible.builtin.gather_facts:
  delegate_to: "{{ record[1] }}"
  delegate_facts: true
  register: facts_polled

Unfortunately the facts registered are the one from my localhost and not the remote one. I tried with the setup module, with delegate_facts to true or false same issues :(

Any idea?

Thanks, Nicolas

Upvotes: 0

Views: 1579

Answers (1)

Zeitounator
Zeitounator

Reputation: 44760

Preliminary note: There might be other issues since you did not provide a full playbook example. More specifically, I strongly suspect you have used connection: local on your play/inventory which will make any host use the local connection to localhost. You should check this and fix if it is the case.


Quoting the documentation

Warning
Although you can delegate_to a host that does not exist in inventory (by adding IP address, DNS name or whatever requirement the connection plugin has), doing so does not add the host to your inventory and might cause issues. Hosts delegated to in this way do not inherit variables from the “all” group’, so variables like connection user and key are missing. If you must delegate_to a non-inventory host, use the add host module.

This is a pseudo-example of how to do this respecting the above rules:

- name: Your playbook
  hosts: my_group
  
  tasks:
    # A few tasks here where you get at some point
    # the `record` variable holding your host and to the point
    # where you need to gather facts on it

    - name: Add external host to in memory inventory
      add_host:
        name: "{{ record[1] }}"

    - name: Gather facts from added host
      setup:
      delegate_to: "{{ record[1] }}"
      delegate_facts: true
      run_once: true

    - name: Use gathered facts (show all for server)
      debug:
        msg: "{{ hostvars[record[1]] }}"

     # Rest of your play...


Upvotes: 1

Related Questions