Ansible is an excellent automation tool that simplifies the process of configuring systems, especially for managing servers in a consistent and scalable way. In this blog post, I’ll walk you through how to enable PHP 8.1 in Apache 2 on a server (like Ubuntu) using Ansible.
Why PHP 8.1?
PHP 8.1 brings exciting new features, including enumerations, fibers for concurrency, readonly properties, intersection types, and significant performance improvements. Whether you're working on a new project or upgrading an existing one, moving to PHP 8.1 can enhance both code performance and development experience.
Read about how to upgrade to php8.1
Prerequisites
Before we dive in, ensure you have the following:
Ansible Installed: If not, you can install it via pip install ansible.
Access to a Remote Server: Ansible will SSH into your server, so ensure you have SSH access and the necessary permissions.
Apache Installed: Apache 2 should already be installed, but we will include the installation in the Ansible playbook in case it's not.
Step 1: Setup Inventory File
[webservers]
your_server_ip ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/your-key.pem
Step 2: Ansible Playbook to Install and Enable PHP 8.1
---
- hosts: webservers
become: true
tasks:
- name: Update apt repository cache
apt:
update_cache: yes
- name: Install dependencies for adding PPAs
apt:
name: software-properties-common
state: present
- name: Add PPA for PHP 8.1
apt_repository:
repo: ppa:ondrej/php
state: present
update_cache: yes
- name: Install Apache 2
apt:
name: apache2
state: present
- name: Install PHP 8.1 and related modules
apt:
name:
- php8.1
- libapache2-mod-php8.1
- php8.1-cli
- php8.1-mysql
- php8.1-xml
- php8.1-mbstring
- php8.1-curl
state: present
- name: Enable Apache PHP module
shell: a2enmod php8.1
- name: Restart Apache to apply PHP 8.1
service:
name: apache2
state: restarted
- name: Create a PHP info page for testing
copy:
dest: /var/www/html/info.php
content: "<?php phpinfo(); ?>"
Step 3: Running the Playbook
ansible-playbook -i inventory.ini php_apache_setup.yml
Step 4: Testing PHP 8.1
http://your_server_ip/info.php
Conclusion
With this simple Ansible playbook, you can automate the process of installing and enabling PHP 8.1 in Apache 2 across your servers. This playbook can be scaled to multiple servers by simply adding them to your Ansible inventory file, saving time and ensuring consistency across deployments.
Ansible’s power lies in its simplicity, and using it to manage server configurations like installing PHP 8.1 can greatly streamline your server management tasks.
Feel free to expand this playbook by adding more tasks, such as virtual host configurations, SSL setup, or database installation.