Building Ansible Modules

Ansible comes with a lot of modules working out of the box. However, at times, if we need to write a custom module, then we can do so. An Ansible module can be written in any programming language but it is easiest to write a module in Python. A full guide is available on Ansible's documentation. We will create a simple module to check the return code of a website.

We have created the module and the code is available at github. To create a module, we need to create a directory called library where the modules will be kept. A main() function is mandatory and this is where the execution begins.

#!/usr/bin/python

import urllib2
from ansible.module_utils.basic import *

def main():
    module = AnsibleModule(argument_spec={"url": {"required": True, "type": "str" }})
    response = urllib2.urlopen(module.params["url"])
    module.exit_json(changed=True, meta={"return_code":response.code})

if __name__ == '__main__':  
    main()

The module above can be called in a playbook like this:

- name: what is the return code 
  url_code: url=http://trainingdevops.com