collecting local facts in ansible from a custom location (not the default)

Hi,

I’m currently collecting remote host facts like this on my servers:

  • name: Copy fact output to file
    copy:
    content: “{{ hostvars[inventory_hostname]|to_json }}”
    dest: ‘/tmp/{{ ansible_hostname }}.yaml’
    delegate_to: localhost

This works well but I want to add some custom/local facts that aren’t located in the default /etc/ansible/facts.d directory. I have fact_path in my ansible.cfg file under [default].

If I create the local fact file and reload the facts in my playbook, with fact_path = /tmp the facts are listed in the output:

Playbook code:

  • name: local facts
    debug: var=ansible_local
    notify:
  • reload facts
  • name: reload facts
    setup: filter=ansible_local

and the output:

“ansible_local”: {

“local”: {
“local_facts”: {
“ami_id”: “ami-12345678900”,
“avail_zone”: “eu-west-1b”,
“callout”: “8-6”,
“cloud”: “AWS”,
“environment”: “Dev”,
“instance_type”: “t2.micro”,
“region”: “eu-west-1”,
“support_team”: “web”
}

my custom local.fact file lives in /tmp but when I run ansible to create the hostfile, it’s missing the local facts.

If I change the way I collect the facts it works, but I don’t think it’s the best way to do it and the hostfile changes.

This is how I can make it work:

  • name: Add facts to a variable
    setup:
    fact_path: /tmp
    register: setupvar
  • name: Store facts indexed by hostname in /tmp/facts
    copy:
    content: ‘{{ setupvar }}’
    dest: /tmp/{{ ansible_hostname }}.yaml
    delegate_to: localhost

I have tried caching facts but the custom/local facts are still missing from the hostfiles.

Does anyone have any suggestions on how I can pick up the fact_path using the hostvars[inventory_hostname] method?

Thanks