There’s a module for that!

Ansible Module Development walk-through

What are Ansible Modules?

Modules are the work-horse behind Ansible.

What if there’s no standard module for the thing you want to do?

We can write our own custom modules. Typically custom modules are located inside library folder. (hint: ansible.cfg)

Custom Module Skeleton

 'metadata_version': '1.1',
 'status': ['development'],
 'supported_by': 'community'

from ansible.module_utils.basic import *

def main():

# parameter type are str, int, dict, list ...
fields = {
 "param1" : {"required": True, "type": "str"},
 "param2" : {"required": True, "type": "str"},

result = dict(
 changed = False,
 message = ''

module = AnsibleModule(argument_spec=fields)

response = "%s + %s"%(module.params['param1'] , module.params['param2'])

result['message'] = response.upper()


if __name__ == '__main__':
Direct Local Testing

Create a file that contains arguments we will be passing to our module


 "param1": "hello",
 "param2": "world"

And pass it to our custom module

# python library/ args.json

{"invocation": {"module_args": {"param2": "world", "param1": "hello"}}, "message": "HELLO + WORLD", "changed": false}
Testing using Playbook

Create test_custom.yml playbook.


  - name: Test Ansible Custom Module
    hosts: test
      - name: Execute custom_mod
          param1: "hello"
          param2: "world"
        register: result
        delegate_to: localhost

      - debug: var=result.message

And let’s test it..

# ansible-playbook test_custom.yml

PLAY [Test Ansible Custom Module] ********************************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************************************

ok: [instance-1]

TASK [Execute custom_mod] ****************************************************************************************************************************************************************************

ok: [instance-1 -> localhost]

TASK [debug] *****************************************************************************************************************************************************************************************

ok: [instance-1] => {

    "result.message": "HELLO + WORLD"


PLAY RECAP *******************************************************************************************************************************************************************************************

instance-1                 : ok=3    changed=0    unreachable=0    failed=0


Leave a Reply