
PHP and PHP-FPM configuration
As we saw in the last section, there are a few variables defined for PHP in roles/stack-config/defaults/main.yml, and these are:
php:
ip: "127.0.0.1"
port: "9000"
upstream: "php"
ini:
- { regexp: '^;date.timezone =', replace: 'date.timezone = Europe/London' }
- { regexp: '^expose_php = On', replace: 'expose_php = Off' }
- { regexp: '^upload_max_filesize = 2M', replace: 'upload_max_filesize = 20M' }
The first configuration task is to deploy the PHP-FPM configuration; this is what the template looks like:
; {{ ansible_managed }}
[{{ wordpress_system.user }}]
user = {{ wordpress_system.user }}
group = {{ wordpress_system.group }}
listen = {{ php.ip }}:{{ php.port }}
listen.allowed_clients = {{ php.ip }}
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
php_admin_value[error_log] = /var/log/php-fpm/{{ wordpress_system.user }}-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/fpm/session
php_value[soap.wsdl_cache_dir] = /var/lib/php/fpm/wsdlcache
As you can see, we have a few replacements in this file. Starting at the top between the square brackets, we are defining the PHP-FPM pool name; we are using the content of the wordpress_system.user for this. Next up, we have the user and group we want our pool to run under; here, we are using wordpress_system.user and wordpress_system.group. Finally, we are setting the IP address and port we want our PHP-FPM pool to listen on by using the php.ip and php.port variables.
The task in roles/stack-config/tasks/main.yml to deploy the template looks as follows:
- name: copy the www.conf to /etc/php-fpm.d/
template:
src: "php-fpmd-www.conf.j2"
dest: "/etc/php-fpm.d/www.conf"
notify: "restart php-fpm"
The handler to restart PHP-FPM in roles/stack-config/handlers/main.yml is just:
- name: "restart php-fpm"
service:
name: "php-fpm"
state: "restarted"
enabled: "yes"
The next task in roles/stack-config/tasks/main.yml uses the lineinfile module:
- name: configure php.ini
lineinfile:
dest: "/etc/php.ini"
regexp: "{{ item.regexp }}"
line: "{{ item.replace }}"
backup: "yes"
backrefs: "yes"
with_items: "{{ php.ini }}"
notify: "restart php-fpm"
What we are doing here is taking the content of php.ini and looping through it by looking for the value defined by the regexp key. Once we find the value, we are replacing it with the content of the replace key. If there are changes to the file, we are making a backup first, just in case. Also, we are using backrefs to ensure that if there is no matching regex in the file, then it will be left unchanged; if we didn't use them, the restart php-fpm handler would be called every time the playbook runs, and we do not want PHP-FPM to be restarted if there is no reason to.