The second custom module

Building upon the last module, let's utilize the common module Boilerplate from Ansible as in the module development documentation at http://docs.ansible.com/ansible/dev_guide/developing_modules_general.html. We will modify the last custom module in custom_module_2.py to utilize ingesting inputs from the playbook.

First, we will import the boilerplate code from ansible.module_utils.basic:

    from ansible.module_utils.basic import AnsibleModule

if __name__ == '__main__':
main()

From there, we can then define the main function where we will house our code. AnsibleModule provides lots of common code for handling returns and parsing arguments. In the following example, we will parse three arguments for host, username, and password, and make them as a required field:

    def main():
module = AnsibleModule(
argument_spec = dict(
host = dict(required=True),
username = dict(required=True),
password = dict(required=True)
)
)

The values can then be retrieved and used in our code:

     device = module.params.get('host')
username = module.params.get('username')
password = module.params.get('password')

url='http://' + host + '/ins'
switchuser=username
switchpassword=password

Finally, we will follow the exit code and return the value:

    module.exit_json(changed=False, msg=str(data))

Our new playbook will look identical to the last one with the exception now that we can pass values for different devices in the playbook:

     tasks:
- name: Show Version
action: custom_module_1 host="172.16.1.142" username="cisco"
password="cisco"
register: output

When executed, this playbook will produce the exact same output as the last playbook; however, notice that this playbook and module can be passed around for other people to use without them knowing the details of our module.

Of course, this is a functional but incomplete module; for one thing, we did not perform any error checking or documentation. However, it demonstrates how easy it is to build a custom module from scripts that we have already made.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.134.17