Python 在模块代码中使用ansible_事实

Python 在模块代码中使用ansible_事实,python,ansible,ansible-facts,Python,Ansible,Ansible Facts,我正在尝试创建自己的ansible模块(它将更新cmdb),我正在寻找如何在模块代码中使用ansible_事实 我的模块脚本示例如下: #!/usr/bin/python from ansible.module_utils.basic import * import json, ast from servicenow import ServiceNow from servicenow import Connection def __get_server_info(table,serve

我正在尝试创建自己的ansible模块(它将更新cmdb),我正在寻找如何在模块代码中使用ansible_事实

我的模块脚本示例如下:

#!/usr/bin/python

from ansible.module_utils.basic import *

import json, ast

from servicenow import ServiceNow
from servicenow import Connection


def __get_server_info(table,server_name="", sys_id=""):
     if sys_id == "":
       return table.fetch_one({'name': server_name})

     if server_name == "":
       return table.fetch_one({'sys_id': sys_id})

def __update_cmdb_hwinfo(table, sys_id, server_name=""):
    return table.update({'sys_id': sys_id,{'hw_ram': 'Here for example i want to put ansible_facts about server ram size'})


def main():


    fields = {
       "snow_instance": {"required": True, "type": "str"},
       "snow_username": {"required": True, "type": "str"},
       "snow_password": {"required": True, "type": "str"},
       "server_name":   {"required": True, "type": "str" },
       "api_type":      {"default": "JSONv2", "type": "str"},
    }

    module = AnsibleModule(argument_spec=fields)
    snow_connection = Connection.Auth(username=module.params['snow_username'], password=module.params['snow_password'], instance=module.params['snow_instance'], api=module.params['api_typ
e'])
    server = ServiceNow.Base(snow_connection)
    server.__table__ = 'cmdb_ci_server_list.do'

    machine = __get_server_info(server, )
    ## Define connection object to ServiceNow instance
    module.exit_json(changed=False, meta=module.params, msg=machine)


if __name__ == '__main__':
    main()

我应该使用什么变量来调用模块脚本中的ansible_事实?(甚至可能吗?)

我怀疑这在模块内部是可能的,因为它们是在具有预定义参数的远程机器的上下文中执行的

但您可以使用动作插件(在本地上下文中执行)包装您的模块,从可用变量中收集所需数据,并将它们作为参数传递给您的模块

像这样(./action\u plugins/a\u test.py):

在这种情况下,如果您的模块需要
mem\u size
参数,则它将通过操作插件设置为
ansible\u memtotal\u mb
的值

模块示例(./library/a_test.py):

测试剧本:

---
- hosts: all
  tasks:
    - a_test:

非常感谢您使用@Konstantin这个示例,但是您能帮助我正确使用这个示例吗?我一直在尝试这样使用它:`x=ActionModule()module.exit_json(changed=False,meta=module.params,msg=x)`并得到错误:`x=ActionModule()\nTypeError:`u init\u_u()正好接受7个参数(给定1个参数)\n“module_stdout:“,”msg:“module FAILURE”,“rc:”1`或者请展示一些文档,在那里我可以找到这个类的示例。对于这个问题我真的很抱歉,但我是python的新手(也是ansible)。提前谢谢。用module example更新了我的答案。非常感谢@Konstantin它正在工作!你救了我一天
#!/usr/bin/python

def main():
    module = AnsibleModule(
        argument_spec = dict(
            mem_size=dict(required=False, default=None),
        ),
        supports_check_mode = False
    )

    module.exit_json(changed=False, mem_size=module.params['mem_size'])

from ansible.module_utils.basic import *
from ansible.module_utils.urls import *

main()
---
- hosts: all
  tasks:
    - a_test: