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 http://releases.ansible.com/ansible/ansible-latest.tar.gz
[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.

e.g.

In case of php language

#!/usr/bin/php

In case of python

#!/usr/bin/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

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

<span style="text-decoration: underline;">Module Colde</span>
#!/usr/bin/php
&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