Wednesday, March 13, 2019

Executing an ansible playbook from within PHP

Ansible seems to be the perfect tool to create a device inventory and keep track of all the devices in the network. Having this in mind, I decided to write a web application in PHP with a Postgres database that would hold the data of each device. Below you can see the web app.


Starting with the basics I used the "ios_facts" function to get the data and insert into the database. The Ansible playbook was executed manually, it went through the devices connecting to one after the other and database was updated with the new data.

That worked very well until I decided to trigger the execution of the Ansible playbook from within PHP, in order to create a more dynamic inventory or execute a playbook against a certain network device. Also I wanted to get the output from the execution of the playbook and display it to the web user.

Since PHP runs as a www-data user the privileges for executing anything are rather limited. This is what I had to do in order to make it work.

1. Create a user www-data in Postgress and grand "connect" privileges to my database
2. Grand 'insert', 'update' & 'select' privileges to the www-data user for the table I was interested in
3. Put the ansible playbook in the directory where the PHP application files existed
4. Use the PHP command passthru to execute the playbook and get the output back to the web application as per below
<?php 
passthru("/usr/bin/ansible-playbook -i myinventory mytest.yml"); 
?>
5. Create an "ansible.cfg" file in the directory of the playbook to disable host key checking
****ansible.cfg****
[defaults]
host_key_checking = False
6. Modify write permissions of the application directory, to allow Ansible write on the disk

And this is the output that I get on my browser after executing the script. This is just a Javascript alert, but you get the point..




Please keep in mind my application is running in an internal lab network and the security of the application is not an issue. The above process took place just to make things work in an internal lab environment. You shouldn't take such actions in a production environment where the security of the application and the network itself is critical