LinuxUnity LinuxUnity

Posts / Ansible

[Ansible] Part 6: Writing an Ansible Playbook to Install WordPress on a LAMP Stack

In the previous article, we explored how to write Ansible playbooks. This article applies those skills to deploy a complete WordPress environment on Ubuntu 24 using a LAMP stack.

11/07/2026 7 min read 8 views

Z Zedx

In this article

In the previous article, we learned how to write playbooks in Ansible. In this article, we will apply the knowledge we have acquired to deploy a small project, creating a complete environment for running a website by installing the LAMP Stack and WordPress on a Linux server, specifically Ubuntu 24.

Overview of the LAMP Stack

LAMP Stack is a popular open-source software stack used to build and deploy dynamic web applications. LAMP is an acronym for four main components:

  • Linux: The operating system that provides a stable and secure foundation for web applications.
  • Apache: The web server responsible for processing HTTP requests and serving web pages to users.
  • MySQL: A relational database management system (RDBMS) that stores and manages data for web applications.
  • PHP: A server-side programming language that helps generate dynamic web pages and connect to the MySQL database.

LAMP Stack provides a solid and flexible foundation, particularly well suited for web applications ranging from simple to complex. Since all its components are open source, LAMP is not only free but also easy to customize and extend.

Create a LAMP Stack and WordPress Installation Playbook

Deployment model:

Step 1: Declare the Inventory

Step 2: Write the Playbook

Create and name the playbook file wp.yaml.

  • Header:
text
- hosts: all
  become: yes
  gather_facts: no
  vars:
    http_conf: "000-default.conf"

Define the parameters referenced in the previous article here.

For the var variable http_conf: "000-default.conf": set the name of the Apache configuration file to 000-default.conf.

  • Body:

Use the module apt to update software packages from repositories and install LEMP:

Update software packages: (equivalent to the command sudo apt update Linux)

text
tasks:
  - name: Update apt cache
    apt:
      update_cache: yes

update_cache: yes: Refresh the package lists and update package information to improve accuracy when installing or updating software packages.

Install and start Apache2:

text
    - name: Ensure Apache2 is installed
      apt:
        name: apache2
        state: present

    - name: Ensure Apache2 is running
      service:
        name: apache2
        state: started
        enabled: yes

Download the WordPress source code with the unarchive module:

Module unarchive is a module used to extract compressed archive files (such as .tar.gz, .zip, etc.).

text
    - name: Download and extract WordPress
      unarchive:
        src: https://wordpress.org/latest.tar.gz
        dest: /var/www/html/
        remote_src: yes
        extra_opts: [--strip-components=1]

Specifies remote_src: yes:that the source archive (src) is a URL on the Internet, not a file already available on the local machine. By default, if this parameter is not declared, the value remote_src will be set to no, meaning that Ansible will search for the file on the local machine.

extra_opts: [--strip-components=1]: This option removes the archive's root directory during extraction. When extracting an archive .tar.gz, WordPress is typically contained in a subdirectory (for example: wordpress). Adding this option skips the subdirectory and extracts the contents directly into the directory /var/www/html/.

Set permissions for the WordPress directory with the file module:

Module file in Ansible is used to manage files and directories on remote machines. It allows you to:

  • Create or delete directories/files
  • Set permissions, ownership, and group membership
  • Create symlinks (symbolic links)
text
    - name: Set permissions for the WordPress directory
      file:
        path: /var/www/html/
        owner: www-data
        group: www-data
        mode: '0755'
        recurse: yes

Assign directory ownership /var/www/html/ to www-data and set permissions to 0755.

recurse: yes: apply recursively to all files and subdirectories.

Apache VirtualHost configuration with the copy module combined with the shell module:

Module copy used to copy files or directories to remote servers from content or from a file/directory available on the control server.

text
    - name: Configure VirtualHost for Apache
      copy:
        dest: "/etc/apache2/sites-available/{{ http_conf }}"
        content: |
          <VirtualHost *:{{ http_port }}>
              ServerAdmin webmaster@localhost
              DocumentRoot /var/www/html
              <Directory /var/www/html>
                  AllowOverride All
              </Directory>
              ErrorLog ${APACHE_LOG_DIR}/error.log
              CustomLog ${APACHE_LOG_DIR}/access.log combined
          </VirtualHost>

    - name: Enable Apache configuration and restart
      shell: |
        a2ensite {{ http_conf }}
        a2enmod rewrite
        systemctl restart apache2

In this guide, we use content the entire contents of the VirtualHost configuration file will be copied to the path /etc/apache2/sites-available/000-default.conf on remote servers.

Install MariaDB:

text
    - name: Ensure Mariadb is installed
      apt:
        name:
          - mariadb-server
          - mariadb-client
        state: present

    - name: Ensure Mariadb is running
      service:
        name: mariadb
        state: started
        enabled: yes

Install phpMyAdmin:

text
  - name: Ensure PHPMyadmin is installed
    apt:
      name:
        - software-properties-common
        - phpmyadmin
      state: present
      update_cache: yes
    environment:
      DEBIAN_FRONTEND: noninteractive

Set environment variables DEBIAN_FRONTEND: noninteractive will be configured, allowing the phpMyAdmin installation process to run without user interaction and automatically answering “yes” to the prompts during installation.

Install the repository ppa:ondrej/php:

text
   - name: Add PPA repository for PHP (ondrej/php)
      apt_repository:
        repo: ppa:ondrej/php
        state: present

    - name: Update apt cache after adding PPA
      apt:
        update_cache: yes

Install PHP 8.1 and the required extensions:

text
    - name: Install PHP and extensions
      apt:
        name: "{{ item }}"
        state: present
        update_cache: yes
      loop: [php8.1, libapache2-mod-php8.1, php-net-ldap2, php-net-ldap3, php-imagick, php8.1-common, php8.1-gd, php8.1-imap, php8.1-mysql, php8.1-curl, php8.1-zip, php8.1-xml, php8.1-mbstring, php8.1-bz2, php8.1-intl, php8.1-gmp, php8.1-redis]
      notify:
        - Restart Apache

Instead of separating each PHP extension into a different task, we will group them into a single task with a loop shorter playbook.

ignore_errors: yes: If this task fails (unless an extension is installed to retry it), the playbook will not stop but will continue with the subsequent tasks.

Install python3-pip and python3-pymysql:

text
    - name: Install python3-pip
      apt:
        name: python3-pip
        state: present

    - name: Install python3-pymysql
      apt:
        update_cache: yes
        name: python3-pymysql
        state: present

??? python3-pymysql This is a library for working with MySQL databases in Python. If this library is not installed on the remote servers, the MySQL-related module in the next step will not work.

Create a database for the WordPress website using the mysql_db and mysql_user modules:

mysql_db and mysql_user: both modules belong to the Ansible MySQL group and are used to manage MySQL/MariaDB.

text
  - name: Create database wordpress 
    mysql_db:
      login_unix_socket: /var/run/mysqld/mysqld.sock
      name: wordpress
      state: present

  - name: Create user wordpressuser
    mysql_user:
      login_unix_socket: /var/run/mysqld/mysqld.sock
      name: wordpressuser
      host: localhost
      password: wordpresspassword
      priv: 'wordpress.*:ALL'
      state: present

Create the database wordpress and user wordpressuser, while granting this user full access to the newly created database.

Create the wp-config.php file from wp-config-sample.php

text
    - name: Create file wp-config.php from wp-config-sample.php
      copy:
        src: /var/www/html/wp-config-sample.php
        dest: /var/www/html/wp-config.php
        remote_src: yes

Continue using the copy module, but add a declaration remote_src: yes so that Ansible knows the source file is located on the remote host.

Edit the database information in the configuration file wp-config.php using the replace module:

Module replace is used to find and replace a string in a file on remote servers. It works similarly to the command sed in Linux.

text
    - name: Config database in wp-config.php
      replace:
        path: /var/www/html/wp-config.php
        regexp: "{{ item.regexp }}"
        replace: "{{ item.replace }}"
      loop:
        - { regexp: 'username_here', replace: 'wordpressuser' }
        - { regexp: 'database_name_here', replace: 'wordpress' }
        - { regexp: 'password_here', replace: 'wordpresspassword' }

Where: path: specifies the path to the file to be edited.

regexp: searches for the keyword to replace.

replace: replaces it with the value corresponding to the matched keyword.

In Ansible, loop allows a task to run multiple times with different values. When using loop, the variable item represents each element in the list that loop iterates over.

  • Final section:

If the Apache configuration changes, the handler is invoked to restart Apache.

text
  handlers:
  - name: Restart Apache
    service:
      name: apache2
      state: restarted
  • See the complete playbook here.

Step 3: Run the Playbook

Run the following command:

text
ansible-playbook -i inventory-lab wp.yaml

ansible  ansible playbook wordpress

The playbook ran successfully.

Step 4: Verify

Access the URL http://<IP>/wp-admin to open the WordPress setup interface.

cài đặt wordpress

WordPress was successfully installed on 2 remote servers.

Conclusion

After successfully installing WordPress and the LAMP stack using an Ansible Playbook, the automated deployment process was completed efficiently. This article also introduced several Ansible modules to help you better understand how to use them to optimize system installation and configuration steps.

Series: Ansible · Part 6/8

  1. Intro Automation in Linux Configuration Management
  2. Part 1 [Ansible] Part 1: Introduction to Ansible
  3. Part 2 [Ansible] Part 2: Installing and Getting Started with Ansible
  4. Part 3 [Ansible] Part 3: How to Create and Manage Inventory Effectively in Ansible
  5. Part 4 [Ansible] Part 4: Exploring Commonly Used Modules in Ansible
  6. Part 5 [Ansible] Part 5: A Beginner’s Guide to Writing Simple, Effective Playbooks
  7. Part 6 [Ansible] Part 6: Writing an Ansible Playbook to Install WordPress on a LAMP Stack
  8. Part 7 [Ansible] Part 7: Install Ansible CMDB and Create System Reports in Minutes

Related posts