The first custom module

Writing a custom module does not need to be complicated; in fact, it doesn't even need to be in Python. But since we are already familiar with Python, we will use Python for our custom modules. We are assuming that the module is what we will be using ourselves and our team without submitting back to Ansible, therefore ignoring some of the documentation and formatting for the time being.

By default, if you make a library folder in the same directory of the playbook, Ansible will include the directory in the module search path. All the module needs is to return a JSON output back to the playbook.

Recall that in Chapter 3, API and Intent-Driven Networking, we used the following NXAPI Python script to communicate to the NX-OS device:

    import requests
import json

url='http://172.16.1.142/ins'
switchuser='cisco'
switchpassword='cisco'

myheaders={'content-type':'application/json-rpc'}
payload=[
{
"jsonrpc": "2.0",
"method": "cli",
"params": {
"cmd": "show version",
"version": 1.2
},
"id": 1
}
]
response = requests.post(url,data=json.dumps(payload),
headers=myheaders,auth=(switchuser,switchpassword)).json()

print(response['result']['body']['sys_ver_str'])

When we executed it, we simply got the system version. If we simply modify the last line to be a JSON output, we will see the following:

    version = response['result']['body']['sys_ver_str']
print json.dumps({"version": version})

We can then use the action plugin (https://docs.ansible.com/ansible/dev_guide/developing_plugins.html) in our playbook, chapter5_14.yml, to call this custom module:

    ---
- name: Your First Custom Module
hosts: localhost
gather_facts: false
connection: local

tasks:
- name: Show Version
action: custom_module_1
register: output

- debug:
var: output

Note that just like the ssh connection, we are executing the module locally with the module making API calls outbound. When you execute this playbook, you will get the following output:

$ ansible-playbook chapter5_14.yml
[WARNING]: provided hosts list is empty, only localhost is available

PLAY [Your First Custom Module] ************************************************

TASK [Show Version] ************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
"output": {
"changed": false,
"version": "7.3(0)D1(1)"
}
}

PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0

As you can see, you can write any module that is supported by API, and Ansible will happily take any returned JSON output.

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

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