ansible_facts access within a custom module

Hi,

how can I access the ansible_facts within a custom module which was initialized with the AnsibleModule class ?

I either:

a) need to pass the facts as a module parameter

or

b) access the facts directly inside the module

Thanks in advance.

Christian

You can access the fact functions by importing the “module_utils” code for the facts functions and calling them directly from within your module.

This is in fact how the setup module itself is written.

Take a look at what it does and follow suit, and it should be pretty straightforward.

In the future, this is about developing on Ansible, so probably better suited for ansible-devel. I’m trying to get that list to have a bit nicer momentum :slight_smile:

Thanks!

Hi Michael,

I’ll give that a try.

Thank you !

Hi,

import exceptions
import subprocess
from ansible.module_utils.basic import *

def main():
module = AnsibleModule(argument_spec = dict(data=dict(required=False, default=None),),supports_check_mode = True)
dt = {“System_Details”:{‘Kernel_version’:ansible_hostname}}

module.exit_json(ansible_facts=dt)
main()

Above is my custom module, where i am trying to access the ansible facts.
I am getting the below error:

fatal: [172.19.3.60]: FAILED! => {“changed”: false, “failed”: true, “module_stderr”: “”, “module_stdout”: “Traceback (most recent call last):\r\n File "/root/.ansible/tmp/ansible-tmp-1463490863.86-275822236207074/get_system_specific_details", line 2014, in \r\n main()\r\n File "/root/.ansible/tmp/ansible-tmp-1463490863.86-275822236207074/get_system_specific_details", line 2011, in main\r\n dt = {"System_Details":{‘Kernel_version’:ansible_hostname}}\r\nNameError: global name ‘ansible_hostname’ is not defined\r\n”, “msg”: “MODULE FAILURE”, “parsed”: false}

Can you please help me out??

Thanks in advance,
Mona G

Any required facts need to be passed in, a module normally executes on a remote machine and we pass only the options given to the module. We do not pass all the data that the ansible controller has, both for security and performance reasons.