Scripting libvirt with php on CentOS or Redhat 7

Libvirt is virtualization API used to interact with different hypervisorrs. In this article we will look into scripting with php using libvirt api. This is very basic overview and designed for very basic scripting needs. This particular configuration was tested against KVM on CentOS 7.

In order to script libvirt with php we will need libvirt-php module which is a php module that provides PHP bindings for libvirt virtualization toolkit and therefore you can access libvirt directly from your PHP scripts with no need to have virt-manager or libvirt-based CLI/GUI tools installed.

Installing php lib-virt

First lets Install LAMP stack

#yum install httpd
#systemctl start httpd.service
#systemctl enable httpd.service
#yum install mariadb-server mariadb
#systemctl start mariadb
#systemctl enable mariadb.service
#yum install php php-mysql
#systemctl restart httpd.service


Libvirt-php installation

yum install libvirt-devel
yum install libxml2-devel
yum install php-devel.x86_64
yum groupinstall "Development tools"
yum install libxslt
yum install virt-manager
yum install ssh-askpass
yum install openssh-askpass # on host
gunzip -c libvirt-php-0.4.8.tar.gz | tar xvf -
cd libvirt-php-0.4.8
make install
php -m | grep libvirt > /dev/null; echo $?
# make sure 0 returned
# create file below
vi /etc/php.d/libvirt.ini


Use the following php script to get hostname and print list of active virtual machines.

ini_set('display_errors', 1);
$conn = libvirt_connect($uri);
$doms1 = libvirt_list_domains($conn);
$doms = libvirt_list_active_domains($conn);

If you want to use php scripts on remote hosts the following has to be done.

1. Create file on the KVM host that you want to control

The name of the file is up to you, but needs to start with a two digit number and end with .pkla.
 [SSH access]

2. Make sure user that runs httpd has ssh key generated and copied to KVM host. You can optionally chnage apache username with username
that has ssh access. You will also need to add user to apache group.