How to save whole ansible_facts to file

Hi,

Running Ansible 2.4, I am trying to save all Ansible facts to a file, with a task like this:

`

  • name: save all facts to host specific file
    copy:
    content: “{{ ansible_facts }}”
    dest: “/some/directory/{{ ansible_fqdn }}”
    delegate_to: localhost
    `

However it fails with the error “‘ansible_facts’ is undefined”.

Do you think there is a workaround? I really do not want to have to select facts one by one…

Regards,
Yvan

The facts is not stored under "ansible_facts" but "vars" so use

  content: '{{ vars }}'

Thanks for the hint!

I forgot to say that I want to save all Ansible facts host by host, so “{{ vars }}” contains to much data for me. Here is what I found to remove vars from master and other hosts:

`

  • name: save all facts to host specific file
    copy:
    content: “{{ ansible_delegated_vars[inventory_hostname].vars | to_nice_json }}”
    dest: "/some/directory/{{ ansible_fqdn }}"
    delegate_to: localhost
    `

This still contains variables from inventory, but it is better than nothing…

Thanks for the hint!

I forgot to say that I want to save all Ansible facts *host by host*, so
"{{ vars }}" contains to much data for me. Here is what I found to remove
vars from master and other hosts:

Look into the facts caching feature of Ansible, that will only store the gathered facts and not inventory in one file per host.
https://docs.ansible.com/ansible/latest/playbooks_variables.html#fact-caching

  - name: save all facts to host specific file
    copy:
      content: "{{ ansible_delegated_vars[inventory_hostname].vars |
to_nice_json }}"
      dest: "/some/directory/{{ ansible_fqdn }}"
    delegate_to: localhost

This still contains variables from inventory, but it is better than nothing…

This will also only store the gathered facts and not inventory

  - setup:
    register: setupvar

  - copy:
      content: '{{ setupvar.ansible_facts }}'
      dest: /some/directory/{{ ansible_fqdn }}
    delegate_to: localhost

I did not think about registering results of “setup” task, that is perfect!

Thanks,
Yvan

Use the jsonfile ansible cache, it will automatically store facts (and
only facts) into files.

In 2.5 we do have facts under ansible_facts and we hope to ONLY have
them there in the future, currently it is a toggle to allow them in
'main vars' or not.