1

I am developing some ansible modules for interactions with a REST API. As I am writing them I am finding that I am copy/pasting common options. For example, in module1:

module1.py
def run_module():

    module_args = dict(
        api_key=dict(type='str', required=True),
        host=dict(type='str', required=True),  
        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()

Then in module2, which interacts with the same REST API thus needs many of the same options:

module2.py
def run_module():

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

    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']

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

def main():
    run_module()

if __name__ == '__main__':
    main()

The setup and requirements are very similar here. I am also copying/pasting much of the DOCUMENTATION string, which I omitted here for brevity.

What I am wondering is if this is considered good practice or not. I could extract some of these things, including the base DOCUMENTATION string, into a common file OR perhaps wrap the functionality in a base class which I extend for each module... I'm really not sure what best practice is in this case and I didn't see anything in the Ansible module development regarding inheritance. Could anyone give me a bit of advice on this? Also these are my first Ansible modules I have written so any other advice would be appreciated as well, thanks much!

TheMethod
  • 2,893
  • 9
  • 41
  • 72
  • 1
    Take a look at collections of modules that interact with the same service -- for example, see how the [openstack modules](https://github.com/openstack/ansible-collections-openstack) handle argument specs. – larsks Feb 18 '21 at 14:59

0 Answers0