Custom module in ansible using php

Ansible is the very simple way to automate your installation, build and deployment process. Specially meant for IT automation on remote servers.

Quick installation of ansible.

  • Download tar file of ansible package. 
  • Extract tar.
  • Run setup script.
  • Add into bash.rc


[appa@localhost ~]$ wget
[appa@localhost ~]$ tar -xvzf ansible-latest.tar.gz
[appa@localhost ~]$ cd ansible-latest
[appa@localhost ~]$ source hacking/env-setup
[appa@localhost ~]$ echo 'if [ -f ~/ansible-latest/hacking/env-setup ]; then
source ~/ansible-latest/hacking/env-setup -q
fi' > ansibleinrc
[appa@localhost ~]$ cat ansibleinrc > ~/.bashrc

[appa@localhost ~]$  ansbile --version


Write module using php script.  

Its very simple to write custom module in ansible using php script. We need to follow some standard code for language compatibility, you must need to specify binary of your language on top of your script.


In case of php language


In case of python


Ansible understands fixed set of params to be returned in form of json format from script. These are as following …

$output=array("changed"=>false,"time"=>date('Y-m-d h:i:s'),"failed"=>false,"msg"=>"PHP runs successfully","param1"=>"$argv[1]","stdout"=>"$argv[1]");
echo json_encode($output);

 Receive params into module 

When we pass params to module from ansible playbook, we can receive them into module script. But way to receive them is different. Ansible put params into file and that file name is passed as in a param. So we can do file get content for value of params. e.g.

$arguments = file_get_contents($argv[1]);
$arguments = explode("\n", $arguments);
$result = array('changed' => false,'failed' => false,'msg' => 'host app111 added successfully','passed_arguments' => $arguments[0],'stdout' => $arguments[0]);

Playbook Code


- hosts: local
user: prod
gather_facts: no
connection: local

- name: 'Insert Service in db'
action: testModule appa
register: output

<span style="text-decoration: underline;">Module Colde</span>
&lt; ?php //testModule $arguments = file_get_contents($argv[1]); $arguments = explode("\n", $arguments); $output=array("changed"=&gt;false,"time"=&gt;date('Y-m-d h:i:s'),"failed"=&gt;false,"msg"=&gt;"PHP runs successfully","param1"=&gt;" $arguments[0]","stdout"=&gt;" $arguments[0]");

<em><span style="color: #993300;">echo json_encode($output);</span></em>
<em><span style="color: #993300;"> ?&gt;</span></em>

Categories: Linux