Skip to content

Instantly share code, notes, and snippets.

@JZfi
Last active January 4, 2017 16:02
Show Gist options
  • Save JZfi/e2bf0138e454dd2d9218c8ace0279015 to your computer and use it in GitHub Desktop.
Save JZfi/e2bf0138e454dd2d9218c8ace0279015 to your computer and use it in GitHub Desktop.
Call a python function with a dict of arguments
import inspect
# Call a python function with a dict of arguments
# The dict can contain excess values. This function only picks the supported ones and if they exist in the passed arguments
def call_python_function(module, function_name, argument_dictionary):
funcpointer = getattr(module, function_name)
# Find what arguments the module's function takes
argspec = inspect.getargspec(funcpointer)
# Remove the self that is a python self-reference
argspec.args.remove('self')
# argspec.args is now an empty list if the func doesn't take any arguments
# Create a dictionary with the arguments taken from the passed data (if the key exists)
args = {argname: argument_dictionary[argname] for argname in argspec.args if argname in argument_dictionary.keys()}
# Call the command with the dictionary passed as arguments
return funcpointer(**args)
@JZfi
Copy link
Author

JZfi commented Jan 4, 2017

Example of a minimal Ansible module that can be used to call python functions in some utility library:

from ansible.module_utils.basic import AnsibleModule
import inspect
def call_python_function(module, function_name, argument_dictionary): 
...
def main():
    module = AnsibleModule(
            argument_spec = dict(
                api      = dict(required=True, type='str'),
                args     = dict(required=True, type='dict')
                )
            )
    instance = create_some_python_object()
    result = call_python_function(instance, module.params['api'], module.params['args'])
    module.exit_json(changed=True, result=result)

if __name__ == '__main__':
        main()

Save the above as library/world_control.py and replace the instance creation line with some magic library initialization call.
The ansible task below calls our imaginary python function shutdown_everything(target_list, white_gloves=True, force=False) in that library.

- world_control:
    api: shutdown_everything
    args:
      force: True
      target_list:
        - all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment