The second custom module

Building upon the last module, let's utilize the common module boilerplate from Ansible that's stated in the module development documentation (http://docs.ansible.com/ansible/dev_guide/developing_modules_general.html). We will modify the last custom module and create custom_module_2.py to ingest 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 define the main function where we will house our code. AnsibleModule, which we have already imported, 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 required fields:

    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, chapter8_15.yml, will look identical to the last playbook, except now 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, because we are using arguments in the custom module, the custom module can now be passed around for other people to use without them knowing the details of our module. They can write in their own username, password, and host IP in the playbook. 

Of course, this is a functional but incomplete module. For one, we did not perform any error checking, nor did we provide any documentation for usage. However, it is a good demonstration of how easy it is to build a custom module. The additional benefit is that we saw how we can use an existing script that we already made and turn it into a custom Ansible module.

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

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