Ansible 模块开发 - 重用选项

问题描述

我正在开发一些与 REST API 交互的 Ansible 模块。在编写它们时,我发现我正在复制/粘贴常用选项。例如,在模块 1 中:

module1.py
def run_module():

    module_args = dict(
        api_key=dict(type='str',required=True),host=dict(type='str',port=dict(type='int',required=False,default=443),module1_option=dict(type='str',required=True)
    )

    result = dict(
        changed=False,)

    module = AnsibleModule(
        argument_spec = module_args,supports_check_mode = True
    )

    if module.check_mode:
        module.exit_json(**result)

    host = module.params['host']
    api_key = module.params['api_key']
    port = module.params['port']

    module1_option= module.params['module1_option']
    #do module1 stuff here
   

def main():
    run_module()

if __name__ == '__main__':
    main()

然后在 module2 中,它与相同的 REST API 交互因此需要许多相同的选项:

module2.py
def run_module():

    module_args = dict(
        api_key=dict(type='str',module2_option1=dict(type='str',module2_option2=dict(type='bool',required=False)
    )

    result = dict(
        changed=False,supports_check_mode = True
    )

    if module.check_mode:
        module.exit_json(**result)

    host = module.params['host']
    api_key = module.params['api_key']
    port = module.params['port']

    module2_option1= module.params['module2_option1']
    module2_option2= module.params['module2_option2']
    #do module2 stuff here
   

def main():
    run_module()

if __name__ == '__main__':
    main()

这里的设置和要求非常相似。我还复制/粘贴了大部分 DOCUMENTATION 字符串,为简洁起见,这里省略了这些内容

我想知道这是否被认为是好的做法。我可以将其中的一些内容包括基本的 DOCUMENTATION 字符串)提取一个公共文件中,或者将功能包装在我为每个模块扩展的基类中......我真的不确定最佳实践是什么在这种情况下,我在 Ansible 模块开发中没有看到任何关于继承的内容。谁能给我一点建议?此外,这些是我编写的第一个 Ansible 模块,因此也将不胜感激任何其他建议,非常感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)