Writing custom module in ansible
While Writing custom module in ansible in ansible you need to setup ansible environment. If you are not aware from it you can follow step by step instruction in my post “Getting started with ansible“
After successfully setup ansible environment create your module directory inside “library/”.
I have created module directory named “custom_module/” and module name “userinfo” . Please make your module executable using chmod +x
$ cd ansible
$ mkdir custom_module
$ touch custom_module/userinfo
$ chmod +x custom_module/userinfo
You can write ansible module in bash, C++, clojure, Python, Ruby, PHP and other language as well. Only thing you need to take care about standard output.
I have written simple “userinfo” module which check if user exist or not.
Use your ansible custom module in ansible playbook like describe below:
playbook.yml
- hosts: mylocal
user: prod
gather_facts: no
connection: local
tasks:
#Call ansible module "userinfo" with parameter "username=testuser"
- name: 'Ansible module in shell'
action: userinfo username=testuser
register: userInfoVariable
- name: 'Abort execution if user does not exist'
fail: msg="User does not exist"
when: userInfoVariable.isUserExist == False
- name: 'Execute task if user exist'
#action: someaction
shell: echo 'User exist - Replace shell with your action here.'
register: userExist
when: userInfoVariable.isUserExist == True
- debug: var=userExist
Write custom module in ansible using Bash :
custom_module/userinfo
#!/bin/bash
# we are getting username value from ansible playbook parameter
source ${1}
if id -u $username >/dev/null 2>&1; then
isUserExist="True"
else
isUserExist="False"
fi
echo "changed=True msg=OK isUserExist='$isUserExist'"
# You can write module Failed condition similarly
# echo "changed=False"
Playbook Command:-
$ ansible-playbook playbook.yml
Output:-
PLAY [mylocal] ****************************************************************
TASK: [Ansible module in shell] ***********************************************
changed: [127.0.0.1]
TASK: [Abort execution if user does not exist] ********************************
skipping: [127.0.0.1]
TASK: [Execute task if user exist] ********************************************
changed: [127.0.0.1]
TASK: [debug var=userExist] ***************************************************
ok: [127.0.0.1] => {
"userExist": {
"changed": true,
"cmd": "echo 'User exist - Replace shell with your action here.' ",
"delta": "0:00:00.002614",
"end": "2014-05-04 03:22:24.391232",
"invocation": {
"module_args": "echo 'User exist - Replace shell with your action here.'",
"module_name": "shell"
},
"rc": 0,
"start": "2014-05-04 03:22:24.388618",
"stderr": "",
"stdout": "User exist - Replace shell with your action here.",
"stdout_lines": [
"User exist - Replace shell with your action here."
]
}
}
PLAY RECAP ********************************************************************
127.0.0.1 : ok=3 changed=2 unreachable=0 failed=0