Pages

Monday, August 8, 2016

Ansible Custom Modules – Using Shell

Modules in Ansible are reusable, stand alone scripts that can be used by an Ansible API or by Ansible programs like Ansible or ansible-playbook. They return information to the Ansible by printing a JSON string to stdout before existing.

Ansible support multiple scripting and programming language where we can write out modules including bash, C++, clojure, Python, Ruby etc.

In this article we will see how we can write a shell script ,make it an Ansible module and use it in our playbooks.

1. Lets write our shell script that will be used in our Ansible playbook as

[root@puppet centos7]# cat ./library/chkuptime
#!/bin/bash

if [ -f "/proc/uptime" ]; then
   uptime=$(</proc/uptime)
   uptime=${uptime%%.*}
   days=$(( uptime/60/60/24 ))
   hours=$(( uptime/60/60%24 ))
   minutes=$(( uptime/60%60 ))
   seconds=$(( uptime%60 ))
   uptime="$days days, $hours hours, $minutes minutes,$seconds seconds"
else
   uptime=""
fi
   echo -e "{\"uptime\":\""$uptime"\"}"

The script is pretty self explanatory which uses the uptime command which is a measure of the system. Then we parse the uptime to days ,hours ,minutes and seconds.

The output displayed needs to be in a JSON format as that is the only format supported by Ansible to display in stdout.

2. Location – Now once the script is completed. We need to place the script in the library location which will be identified by Ansible while running playbook. The location on my system looks as,

[root@puppet centos7]# tree .
.
+-- ansible.cfg
+-- hosts
+-- library
¦   +-- chkuptime
+-- playbook.yml

We can see that the script saved as “chkuptime” Is located under the library folder.

3. Write the playbook – in order to use out shell  script in our playbook we can write the playbook as,

[root@puppet centos7]# cat uptime.yml
---
- hosts: all
  sudo: yes
  tasks:
   - name: Check Up Time
     action: chkuptime
     register: uptime

   - debug: var=uptime

4. Test the playbook – We can see the below output when we run the playbook as,

[root@puppet centos7]# ansible-playbook uptime.yml
PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [172.16.202.96]

TASK [Check Up Time] ***********************************************************
ok: [172.16.202.96]

TASK [debug] *******************************************************************
ok: [172.16.202.96] => {
    "uptime": {
        "changed": false,
        "uptime": "4 days, 0 hours, 26 minutes,9 seconds"
    }
}

PLAY RECAP *********************************************************************
172.16.202.96              : ok=3    changed=0    unreachable=0    failed=0  


More to Come , Happy learning J

2 comments :