首页 > 解决方案 > 如何手动评估 ansible 模块?

问题描述

我正在使用 ansible 和 python,并且正在使用 f5networks 模块,特别是 bigip_device_info 模块。

目前模块参数为:

user:f5 主机用户名密码:f5 主机密码 validate_certs:标志服务器:要连接的 f5 主机。

我希望它改为采用一组服务器,并返回一组响应,但我想在 python 中执行此操作,因为 .yml 文件与 jinja 模板混淆。

我发现我可以解决我需要的导入:

from ansible_collections.f5networks.f5_modules.plugins.modules.bigip_device_info import ArgumentSpec, ModuleManager, F5ModuleError

该模块的当前实现有一个 main() 函数,如下所示:

def main():
    spec = ArgumentSpec()
    module = AnsibleModule(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode
    )
    try:
        mm = ModuleManager(module=module)
        results = mm.exec_module()
        ansible_facts = dict()
        for key, value in iteritems(results):
            key = 'ansible_net_%s' % key
            ansible_facts[key] = value
        module.exit_json(ansible_facts=ansible_facts, **results)
    except F5ModuleError as ex:
        module.fail_json(msg=str(ex))


if __name__ == '__main__':
    main()

我想做这样的事情:

class BigipDeviceInfo:

    @staticmethod
    def get_device_info(**module_args):
        # Do something to use module_args as the input for module
        spec = ArgumentSpec()
        mock_module = AnsibleModule(argument_spec=spec,
                                    supports_check_mode=spec.supports_check_mode)
        try:
            mm = ModuleManager(module=mock_module)
            results = mm.exec_module()
            return results
        except F5ModuleError as e:
            return e

    @staticmethod
    def run(server_array: list):
        res = []
        for server in server_array:
            res.extend(BigipDeviceInfo.get_device_info(**server))
        return res

if __name__ == "__main__":
    module_args = dict(
        server_array=dict(type='list', required=True)
    )
    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False)
    module.exit_json(**{"output": BigipDeviceInfo.run(**module.params)})

我是 ansible 的新手,虽然我确信我可以找到一种 hacky 的方式来做事,但我希望有一些遵循最佳实践的东西。主要问题是我不太确定使用 ArgSpec 收集参数时发生了什么,以及我可以在哪里设置这些参数以使其正常工作,而 17,000 SLOC 文件并没有提供很多见解。有没有办法手动评估模块?(除了导入main,并通过shell直接通过管道传输它,通过类似的东西os.system("python3 my_module.py")

标签: python-3.xansiblef5

解决方案


推荐阅读