Deploying a LAMP Stack
local graph
Chapter 4 — Deploying a LAMP Stack
Section titled “Chapter 4 — Deploying a LAMP Stack”This chapter will look at deploying a complete LAMP stack using the various core modules that ship with Ansible. We will target the local Multipass virtual machine we first used in Chapter 1, Installing and Running Ansible.
We will discuss the following:
- The playbook layout – how our playbook is going to be structured
- Linux – preparing the Linux server
- Apache – installing and configuring Apache
- MariaDB – installing and configuring MariaDB
- PHP – installing and configuring PHP
This chapter covers the following topics:
- The playbook structure
- The LAMP stack
- The LAMP playbook
Before we start writing the playbook, we will discuss the structure we will use after we briefly discuss what we need for the chapter.
Technical requirements
Section titled “Technical requirements”We will again use the local Multipass virtual machine we launched in the previous chapters. As we will be installing all the elements of a LAMP stack on the virtual machine, your Multipass virtual machine will need to be able to download packages from the internet; in all, there is around 500 MB of packages and configuration to download.
You can find a complete copy of the playbook in the repository accompanying this book at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter04.
The playbook structure
Section titled “The playbook structure”In Chapter 1, Installing and Running Ansible, the playbooks we ran were as basic as possible. They have been in a single file, accompanied by a host inventory file, and, if required, a template file. Then, in Chapter 2, Exploring Ansible Galaxy, we extended our playbook files to include roles rather than putting all our tasks, handlers, and variables into one file.
As you can see from the following layout, there are several folders and files:

Figure 4.1 – The folder structure we will use for our playbook
While there is a copy of the structure in the repository, let’s work on creating the structure and discuss each item as we create it. The first folder we need to create is our top-level folder. This is the folder that will contain our playbook folders and files:
$ mkdir Chapter04$ cd Chapter04The next folder we are going to create is one called group_vars. This will contain the variable files used in our playbook. For now, we are going to create a single variable file called common.yml:
$ mkdir group_vars$ touch group_vars/common.ymlNext, we are going to create two files – our host inventory file, which we will name hosts, and our master playbook, which is typically called site.yml:
$ touch production$ touch site.ymlThe final folder we are going to create manually is called roles. Here, we are going to use the ansible-galaxy command, which we learned about in Chapter 2, Exploring Ansible Galaxy, to create a role called common. To do this, we use the following commands:
$ mkdir roles$ ansible-galaxy role init roles/commonThis should create all the files needed to start writing the common role.
The cloud-init.yaml, example_key, example_key.pub, and hosts.example files are all lifted straight from Chapter 1, Installing and Running Ansible, and Chapter 2, Exploring Ansible Galaxy, so we will not cover them again in this chapter.
Note
While we will work through each of the files individually in this and the following sections, a complete copy of the playbook is available in the accompanying GitHub repository.
Let’s look at each of the four roles in our playbook and install and configure our LAMP stack.
The LAMP stack
Section titled “The LAMP stack”The LAMP stack is the term used to describe an all-in-one web and database server. Typically, the components are as follows:
- Linux is the underlying operating system; in our case, we will use Ubuntu 22.04
- Apache is the web server element of the stack
- MariaDB is what we will use as the database component of the stack; typically, it is based on MySQL, which could also be used
- PHP is the dynamic language used by the web server to generate content
A common variation of the LAMP stack is called LEMP; this replaces Apache with NGINX, which is pronounced engine-x, hence the E rather than the N.
We are going to look at creating roles to deal with these components; these are as follows:
common: This role will prepare our Ubuntu server, installing any supporting packages and services we needapache: This role will install the Apache web server and configure a default virtual hostmariadb: This role will not only install MariaDB but also secure the installation and create a default database and user, as well as optionally download and import a database to usephp: This role will install PHP and configure a set of common PHP modules, and if we set the option to a database admin tool written in PHP, we can interact with our test database via the browser
Let us begin by looking at the common role.
The common role
Section titled “The common role”In the previous section of this chapter, we used the ansible-galaxy role init command to create the common role. This creates several folders and files; as discussed in Chapter 2, Exploring Ansible Galaxy, we will not go into any detail here but instead dive straight into the role itself.
Let’s make a start by adding some tasks.
Updating installed packages
Section titled “Updating installed packages”First of all, let’s update our server by adding the following to the beginning of the roles/common/tasks/main.yml file:
- name: "Update apt cache and upgrade packages" ansible.builtin.apt: name: "*" state: "latest" update_cache: trueYou will notice a difference from when we last used the ansible.builtin.apt module to update all the installed packages.
We now start the task using the name key; this will print out the content of the value we assigned to the name key when the playbook runs, which will give us a better idea of what is going on during the playbook run, rather than just printing the name of the module that is executed.
Installing common packages
Section titled “Installing common packages”Now that we have updated the installed packages, let’s install the packages we want to install on all the Linux servers we will target with the Playbook:
- name: "Install common packages" ansible.builtin.apt: state: "present" pkg: "{{ common_packages }}"As you can see, we again use the ansible.builtin.apt module, and we have added a descriptive name for the task. Rather than providing a list of packages in the task, we use a variable called common_packages, which is defined in the roles/common/defaults/main.yml file as follows:
common_packages: - "ntp" - "sntp" - "ntp-doc" - "vim" - "git" - "unzip"As you can see, we install ntp, sntp, and ntp-doc; we will configure ntp shortly. Next, we install vim, git, and unzip, as they are always helpful to have installed on a server.
Another thing that you may have noticed is that we pass a list of packages using {{ common_packages }} to the pkg key in the ansible.builtin.apt module, resulting in the module looping through the list of packages we pass in and installing them all in one go, rather than having to call the module to install each package individually.
Configuring Network Time Protocol (NTP)
Section titled “Configuring Network Time Protocol (NTP)”Next, we copy the ntp.conf file from the templates folder, adding the list of NTP servers as we have done in the previous chapters, and then informing Ansible to restart NTP whenever the configuration file changes.
Creating a key, group, and user
Section titled “Creating a key, group, and user”In the roles/common/defaults/main.yml file, the following variable is defined:
users: - { name: "lamp", group: "lamp", state: "present", key: "/tmp/id_ssh_lamp_rsa", }This is slightly different from the variables we have used so far, as it is a single variable called users, which is made up of a single item, and that item contains the name, group, state, and key key-value pairs.
Because we are using items, we need to change our approach to how we use the variables within the task, the first of which in roles/common/tasks/main.yml creates an OpenSSH key pair; if one doesn’t already exist, we need to save it at the path that is defined in the key key-value pair:
- name: "Generate a ssh keypair" community.crypto.openssh_keypair: path: "{{ item.key }}" with_items: "{{ users }}" delegate_to: "localhost" become: falseWorking through the task, you can see that we use the community.crypto.openssh_keypair module, in which we pass just one value, which is the path to the file where we would like our OpenSSH key stored.
As you can see, we use the {{ item.key }} variable to enter the path, but we do not define that the variable is called users here; instead, we use the with_items option and pass in the {{ users }} variable here.
While we only pass one item in this example, you could take this approach to execute a single task multiple times – for example, if our variable looked like this:
users: - { name: "lamp", group: "lamp", state: "present", key: "/tmp/id_ssh_lamp_rsa", } - { name: "user2", group: "lamp", state: "present", key: "/tmp/id_ssh_user2_rsa", }Then, when the task is executed, it would create two OpenSSH keys, and the subsequent tasks, which we will get into in a moment, would create a single group called lamp and then two users, lamp and user2.
Back to the task at hand – you will notice that we have defined two other options, delegate_to and become.
If we were to run the community.crypto.openssh_keypair module without defining delegate_to, then the module will be executed on the remote host, which is not what we want to happen in this case, as we want a copy of the private and public portions of the OpenSSH key on our local machine. Therefore, by using localhost as the value in the delegate_to option, we tell Ansible to run this task locally.
The next option, become, tells Ansible not to become an escalated user using the sudo command, which is the default action for all the hosts we have defined at the top of our main site.yml playbook file – this is because we want the community.crypto.openssh_keypair module to run as the user you are logged in as, rather than your local machine’s root user.
The logic for this task, minus the delegate_to and become options, as we want the remainder of the tasks to be executed against the target machine, is followed through to the remaining tasks in the role, starting with creating the group by executing the ansible. ``builtin.group module:
- name: "Add group for our users" ansible.builtin.group: name: "{{ item.group }}" state: "{{ item.state }}" with_items: "{{ users }}"Once the group has been created, we can then add the user using ansible.builtin.user, or users if we have defined more than one item in the users variable:
- name: "Add users to our group" ansible.builtin.user: name: "{{ item.name }}" group: "{{ item.group }}" comment: "{{ item.name }}" state: "{{ item.state }}" with_items: "{{ users }}"The final task in the role takes the public portion of the OpenSSH key, which we generated earlier, and adds the contents to the user(s) created during the previous task, using the ansible.builtin.authorized_key module:
- name: "Add keys to our users" ansible.posix.authorized_key: user: "{{ item.name }}" key: "{{ lookup('file', item.key + '.pub') }}" with_items: "{{ users }}"You may have noticed that the value we pass for the key option is new to us; this uses the lookup plugin to read the file’s contents at the item.key path with .pub appended to the end, meaning, in our case, it reads the contents of the file at /tmp/id_ssh_lamp_rsa.pub. This file is the public portion of the OpenSSH key-pair, which was created when we executed the "generate a ssh keypair" task earlier in the role.
The lookup plugin is designed to be executed locally, so in this case, we do not need to use the delegate_to and become options, as we want the task to be executed on the target host because that is where our user has been created, but we want to populate the /home/lamp/.ssh/authorized_key file on the remote host with the contents of the /tmp/id_ssh_lamp_rsa.pub file that we have on our local host.
That concludes the tasks in the common role; before we move on to the next role, which will install and configure apache, you should know one more thing.
The "generate a ssh keypair" task will not overwrite any existing key-pairs when executed, meaning the first time you run the role and no files exist at /tmp/id_ssh_lamp_rsa and /tmp/id_ssh_lamp_rsa.pub, the key-pair will be created, and on subsequent Playbook runs, as the files now exist, the task will return an OK, as there is nothing for it to do, as a valid key-pair is already at the location, and we ask the community.crypto.openssh_keypair module to create the key-pair.
The Apache role
Section titled “The Apache role”Once the common role has finished running our remote host, we will be ready to install and configure the Apache web server.
Installing the Apache packages
Section titled “Installing the Apache packages”The first task in roles/apache/tasks/main.yml installs the packages we need to run the Apache web server; it uses the ansible.builtin.apt module and looks like the following:
- name: "Install apache packages" ansible.builtin.apt: state: "present" pkg: "{{ apache_packages }}"As you can see, it calls a variable called {{ apache_packages }}, which is defined in roles/apache/defaults/main.yml as follows:
apache_packages: - "apache2" - "apache2-ssl-dev" - "ca-certificates" - "openssl"As we learned when we walked through the common role, this will install the four packages defined in the variable.
Once Apache has been installed, which is a single task, we can now progress to configuring our Apache installation.
Configuring Apache
Section titled “Configuring Apache”The first task when configuring Apache is to take the user that was created when the common role was run and add them to the Apache group; to do this, we run the following task:
- name: "Add user to apache group" ansible.builtin.user: name: "{{ item.name }}" groups: "{{ apache_group }}" append: true with_items: "{{ users }}"This takes the {{ users }} variable from the previous role and loops over the items defined in the variable, adding the user to the group defined under the {{ apache_group }} variable in the roles/apache/defaults/main.yml file. A full list of the variables defined to configure Apache, which we will use throughout the next few tasks, is as follows:
apache_group: "www-data"web_root: "web"document_root: "/home/{{ users.0.name }}/{{ web_root }}"index_file: index.htmlvhost_path: "/etc/apache2/sites-enabled/"vhost_default_file: "000-default.conf"vhost_our_file: "vhost.conf"You may have noticed that the value of the document_root variable is a little different from the ones we have used so far; there’ll be more on that in a moment.
The next task creates a folder within the users directly, which we will use to store the files served via Apache:
- name: "Create the document root for our website" ansible.builtin.file: dest: "{{ document_root }}" state: directory mode: "0755" owner: "{{ users.0.name }}" group: "{{ apache_group }}"As you can see, we use {{ users.0.name }} as we did for the document_root variable value; why is this?
As we know, the common role only creates a single user; we can’t simply use {{ users.name }}, as the name key exists within an item within the variable, so using {{ users.name }} would result in an error, stating that the variable can’t be found.
Because of this, we can reference the first item in the list of items by using its position within the list, which, because Ansible counts from zero, will be 0 rather than 1.
Using the values that we have defined in the defaults for the common and apache roles, this task will create a folder at /home/lamp/web/; the lamp user would own the folder and would be assigned to the www-data group, which is the group the Apache process will run as.
The next task will ensure the correct read, write, and execute permissions are set on the / home/lamp/ folder:
- name: "Set the permissions on the user folder" ansible.builtin.file: dest: /home/{{ users.0.name }}/ state: directory mode: "0755" owner: "{{ users.0.name }}"That task concludes configuring the folder structure needed to serve our web pages; now, it is time to configure Apache itself.
The first thing we need to do is remove the default virtual host configuration file; to do this, we will execute the following task:
- name: "Remove the apache default vhost config" ansible.builtin.file: path: "{{ vhost_path }}{{ vhost_default_file }}" state: absent notify: "Restart apache2"This uses the ansible.builtin.file module to set the state of the file defined by {{ vhost_default_file }} in the {{ vhost_path }} folder to absent, which means, if the file exists, remove it.
It also uses notify to call the "Restart apache2" handler, which is defined as the following task in the roles/apache/handlers/main.yml file:
- name: "Restart apache2" ansible.builtin.service: name: "apache2" state: "restarted" enabled: trueOnce the default file has been removed, we can add our virtual host configuration file.
The template for this virtual host configuration file can be found at roles/apache/templates/vhost.conf.j2, and it contains the following:
# {{ ansible_managed }}<VirtualHost *:80> ServerName {{ ansible_hostname }} DocumentRoot {{ document_root }} DirectoryIndex {{ index_file }} <Directory {{ document_root }}> AllowOverride All Require all granted </Directory></VirtualHost>When loaded, this configuration file serves the contents of the {{ document_root }} folder when someone visits the site’s URL in their browser.
The task to deploy this template file to the remote host looks like the following:
- name: "Copy the our vhost.conf to the sites-enabled folder" ansible.builtin.template: src: vhost.conf.j2 dest: "{{ vhost_path }}{{ vhost_our_file }}" mode: "0644" notify: "Restart apache2"As you can see, this also calls the "Restart apache2" handler if there are any changes to the file.
With Apache now configured, there is one final task.
Optionally copying an index.html file
Section titled “Optionally copying an index.html file”The final task in this role uses the following variables block:
html_deploy: truehtml_heading: "Success !!!"html_body: | This HTML page has been deployed using Ansible to <b>{{ ansible_host }}</b>.<br> The user is <b>{{ users.0.name }}</b> who is in the <b>{{ apache_group }}</b> group.<br> The weboot is <b>{{ document_root }}</b>, the default index file is <b>{{ index_file }}</b>.<br>As you can see, it contains a heading and some HTML code for the body; these variables are used by the following task:
- name: "Copy the test HTML page to the document root" ansible.builtin.template: src: index.html.j2 dest: "{{ document_root }}/index.html" mode: "0644" owner: "{{ users.0.name }}" group: "{{ apache_group }}" when: html_deployThis uses a template that can be found at roles/apache/templates/index.html.j2 and looks like the following:
<!--{{ ansible_managed }}--><!doctype html><title>{{ html_heading }}</title><style> body { text-align: center; padding: 150px; } h1 { font-size: 50px; } body { font: 20px Helvetica, sans-serif; color: #333; } article { display: block; text-align: left; width: 650px; margin: 0 auto; }</style><article> <h1>{{ html_heading }}</h1> <div> <p>{{ html_body }}</p> </div></article>However, the task is only called if the html_deploy variable is set to true; this is managed by the following statement at the end of the task:
when: html_deploySo, if, for any reason, the html_deploy variable is not equal to true, then the task will be skipped when the playbook is executed.
That’s all we need to do to install and configure Apache; let us now look at installing the M in LAMP and review the role to install and configure MariaDB.
The MariaDB role
Section titled “The MariaDB role”Of the four roles we cover in this chapter, this, the MariaDB one, is the most complicated, as it installs MariaDB, configures it, and optionally downloads and imports a sample database.
Let’s start by covering the installation.
Installing MariaDB
Section titled “Installing MariaDB”You may have started to spot a trend in the roles; the tasks always start with installing a few packages, and MariaDB is no different.
The task from roles/mariadb/tasks/main.yml is as follows:
- name: "Install mariadb packages" ansible.builtin.apt: state: "present" pkg: "{{ mariadb_packages }}"The mariadb_packages variable in roles/mariadb/defaults/main.yml looks like the following:
mariadb_packages: - "mariadb-server" - "mariadb-client" - "python3-pymysql"As you can see, we installed the MariaDB client and server. Also, we installed the python3-pymysql package; this is required for the tasks that need to interact with MariaDB once it is installed to function. Without it, Ansible cannot establish a connection to and interact with our MariaDB server.
Once the packages have been installed, we need to start the MariaDB server by using the following task:
- name: "Start mariadb" ansible.builtin.service: name: mariadb state: started enabled: trueYou might be thinking, why aren’t we using a handler as we have done for previous tasks? Well, handlers are only called once the playbook execution has been completed and Ansible knows all the services that need to be restarted.
However, in this case, we need to interact with the MariaDB service to be able to configure it as part of the playbook run, so rather than using a handler, we just start the service as a task using the same block we would use as the handler.
Now that MariaDB is installed and started, we can start the configuration.
Configuring MariaDB
Section titled “Configuring MariaDB”Before we dive into the tasks, quickly look at the variables in roles/mariadb/defaults/main.yml, which will be used to configure our MariaDB server:
mariadb_root_username: "root"mariadb_root_password: "Pa55W0rd123"mariadb_hosts: - "127.0.0.1" - "::1" - "{{ ansible_nodename }}" - "%" - "localhost"Now that we know what variables we will use, it’s time to work through the configuration, which is a little complex due to the default way that MariaDB is configured when it starts immediately after installation.
By default, MariaDB starts with no password in place, meaning that anyone can connect to the database as the root user, which is not ideal, so the first thing we need to do is to secure our installation by setting the root password.
That sounds easy enough, you might be thinking to yourself.
Technically, it is; however, if the playbook were to be run a second time, meaning that there is now a password set, then the task we are about to define, which sets the initial password, will error, as we need to configure the task not to use a password. Once the password has been set, the server will only accept a connection using the already set password.
We also need to consider that once a password has been configured, we need to use that password each time we need to connect to the MariaDB server – so we need an easy way to ensure we can connect smoothly once the password has been set.
Luckily, there is a function built into MariaDB and MySQL that allows you to put your credentials into a file on the server; the file should be placed in the home directory of the user you are logged in as. Once in place, each time you attempt to connect to the database server using that user, the database client will read the file and connect you, without you having to type the credentials – this file should be called ~/.my.cnf (the ~/ part is a shortcut for the user’s home folder).
For our scenario, this works because we can check for the presence of the ~/.my.cnf file, and if it is not there, then it will be safe to assume that the password has not been configured yet.
The task that checks for the presence of the file is as follows:
- name: "Check to see if the ~/.my.cnf file exists" ansible.builtin.stat: path: ~/.my.cnf register: mycnfThis uses the ansible.builtin.stat module to check for the file and then uses the register option to register a runtime variable, called mycnf.
Now that we have a dynamically registered variable that contains details on whether the ~/.my.cnf file exists on the remote host’s filesystem or not, we can now proceed with changing the password or skip the task if the ~/.my.cnf file is present.
Ansible has several built-in modules to interact with MySQL and MariaDB; the one we will use here is ansible.builtin.mysql_user:
- name: "Change mysql root password if we need to" community.mysql.mysql_user: name: "{{ mariadb_root_username }}" host: "{{ item }}" password: "{{ mariadb_root_password }}" check_implicit_admin: "yes" priv: "*.*:ALL,GRANT" login_user: "{{ mariadb_root_username }}" login_unix_socket: /var/run/mysqld/mysqld.sock with_items: "{{ mariadb_hosts }}" when: not mycnf.stat.existsIn the task, we instruct Ansible to set the password for the user defined in the {{ mariadb_root_username }} variable to the password stored in the {{ mariadb_root_password }} variable, giving the user full admin access to all the databases across all possible host combinations, which are defined in the {{ mariadb_hosts }}, which we loop over using the with_items function.
When logging in to do this, Ansible should use the {{ mariadb_root_username }} username and connect over a Unix socket, which can be found at /var/run/mysqld/mysqld.sock; this means we don’t have to establish a network connection to interact with the database because, if we did, Ansible wouldn’t be able to connect, as it can’t send a blank password.
Finally, only run this task when the mycnf.stat.exists variable is equal to false.
Now that we have set the actual password and secured the MariaDB installation, we need to create the ~/.my.cnf file to carry on with the configuration.
To do this, we will again use a template, which can be found at roles/mariadb/templates/my.cnf.j2. This template looks like the following:
# {{ ansible_managed }}[client]user='{{ mariadb_root_username }}'password='{{ mariadb_root_password }}'As you can see, it contains the username and password needed to connect to the database server.
Because the file contains credentials, when the task creates the file on the server, we need to ensure that the file can only be read and written to by the root user, by setting the read, write, and execute permissions of the file as it is created:
- name: "Set up ~/.my.cnf file" ansible.builtin.template: src: "my.cnf.j2" dest: "~/.my.cnf" mode: "0600"Now that we have the ~/.my.cnf file on the remote host, we can progress with securing our MariaDB installation; the subsequent task removes the anonymous user, again looping through the hosts that user could be associated with:
- name: "Delete anonymous MySQL user" community.mysql.mysql_user: user: "" host: "{{ item }}" state: absent with_items: "{{ mariadb_hosts }}"The final task that deals with securing our MariaDB installation removes the default test database:
- name: "Remove the MySQL test database" community.mysql.mysql_db: db: "test" state: "absent"The remainder of the tasks in the role, such as copying the index.html file in the apache role, are optional, so let’s review those tasks now.
Downloading and importing the example database
Section titled “Downloading and importing the example database”There is one more block of variables in roles/mariadb/defaults/main.yml; these deal with downloading and importing an example database. There are a lot of keys in the mariadb_sample_database variable, starting with the flag to enable the option, the URL of the file to download, and the path to save it to:
mariadb_sample_database: create_database: true source_url: "https://github.com/russmckendrick/test_db/archive/master.zip" path: "/tmp/test_db-master"Next, we have the name of the example database being created as well as the username and password to use for the new database:
db_name: "employees"db_user: "employees"db_password: "employees"Finally, there is a list of the files that need to be imported. The first two files contain the schema:
dump_files: - "employees.sql" - "show_elapsed.sql"The remaining files contain the actual data to be loaded:
- "load_departments.dump"- "load_employees.dump"- "load_dept_emp.dump"- "load_dept_manager.dump"- "load_titles.dump"- "load_salaries1.dump"- "load_salaries2.dump"- "load_salaries3.dump"Now that we know what variables are defined, we can work through the remaining tasks, the first of which downloads and unarchives the ZIP file that contains the example database files:
- name: "Download and unarchive the sample database data" ansible.builtin.unarchive: src: "{{ mariadb_sample_database.source_url }}" dest: /tmp remote_src: "yes" when: mariadb_sample_database.create_databaseAs you can see, the ansible.builtin.unarchive module allows you to download and unarchive the file, meaning we can do everything we need in a single task. Also, we only run the when task when the mariadb_sample_database.create_database equals true. We will do this for the remainder of the tasks and even expand upon the when statement toward the end of the role.
The next task creates the example database:
- name: "Create the sample database" community.mysql.mysql_db: db: "{{ mariadb_sample_database.db_name }}" state: present when: mariadb_sample_database.create_databaseOnce the database has been created, we can run a task that creates the user and assigns permissions to the newly created user to access the database we just added:
- name: "Create the user for the sample database" community.mysql.mysql_user: name: "{{ mariadb_sample_database.db_user }}" password: "{{ mariadb_sample_database.db_password }}" priv: "{{ mariadb_sample_database.db_name }}.*:ALL" state: present with_items: "{{ mariadb_hosts }}" when: mariadb_sample_database.create_databaseWe are now down to the final two tasks, and here is where we need to add a little more logic to our playbook to ensure that we only import the example data once; if we don’t have the logic in place, we can run into all sorts of problems if the playbook is rerun and could risk data being overwritten or duplicate data being inserted if the import task is allowed to run again.
As the databases are stored on the host’s filesystem, we can use the same logic that we used to check for the presence of the ~/.my.cnf file, but this time, we check for a database file:
- name: "Check to see if we need to import the sample database dumps" ansible.builtin.stat: path: /var/lib/mysql/{{ mariadb_sample_database.db_name }}/{{ mariadb_sample_database.db_name }}.frm register: db_imported when: mariadb_sample_database.create_databaseWe register a variable called db_imported, which we will use with the when condition of the next and final task; this is the one that loops through mariadb_sample_database.dump_files and imports the databases:
- name: "Import the sample database" community.mysql.mysql_db: name: "{{ mariadb_sample_database.db_name }}" state: import target: "{{ mariadb_sample_database.path }}/{{ item }}" with_items: "{{ mariadb_sample_database.dump_files }}" when: db_imported is defined and not db_imported.stat.existsWe have changed the when condition slightly here; rather than referencing mariadb_sample_database.create_database, we only use db_imported.
The first part ensures that the playbook doesn’t error if we decide not to import the database by setting mariadb_sample_database.create_database to false, as db_imported can only be defined if mariadb_sample_database.create_database is set to true, as the task that sets the db_imported variable is only ever executed when that condition is met.
As you can also see, we use and, thus adding a second condition to the when statement; this means that the task will only be executed if db_imported is defined and not db_imported.stat.exists are both met.
That final task brings us to the end of the MariaDB role and leaves us with one role to work through – the PHP role.
The PHP role
Section titled “The PHP role”This, our final role, installs PHP, optionally copies a PHP Info file along with it, and installs a database management interface written in PHP, called Adminer, so that we can access the database server we used in the previous role.
Installing the PHP packages
Section titled “Installing the PHP packages”It should come as no surprise to you that the first task executed in the PHP role installs the packages needed for us to run PHP.
The full list of packages is defined in the roles/php/default/main.yml file, as follows:
php_packages: - "php" - "php-cli" - "php-curl" - "php-gd" - "php-intl" - "php-mbstring" - "php-mysql" - "php-soap" - "php-xml" - "php-xmlrpc" - "php-zip" - "libapache2-mod-php"The task itself looks familiar:
- name: "Install php packages" ansible.builtin.apt: state: "present" pkg: "{{ php_packages }}" notify: "Restart apache2"The thing to note is that we restart Apache once PHP is installed because we run PHP as an Apache module. So, once installed, Apache needs to be restarted to load in the module and enable PHP on our Apache web server.
That’s it. PHP is installed, and Apache asks to be restarted; everything from here is optional.
Copying the PHP Info file
Section titled “Copying the PHP Info file”The next task is a simple one that copies roles/php/files/info.php to the web root of the server if the php_info variable is set to true:
- name: "Copy the PHP info to the document root" ansible.builtin.copy: src: info.php dest: "{{ document_root }}/info.php" mode: "0755" owner: "{{ users.0.name }}" group: "{{ apache_group }}" when: php_infoThe only difference is that we copy the file from our local host to the remote one with this task – we do not use the ansible.builtin.template module this time but instead, the ansible.builtin.copy one. This is because info.php is made up of three lines of code, none of which we need to update based on the environment or any variables we set.
Installing and configuring Adminer
Section titled “Installing and configuring Adminer”The variables for the remaining tasks in the roles/php/default/main.yml file look like the following:
adminer: install: true path: "/usr/share/adminer" download: "https://github.com/vrana/adminer/releases/download/v4.8.1/adminer-4.8.1-mysql.php"They define where to download the file from and where on the remote to download it to, which is where the first of the three tasks comes in, as this creates the folder on the remote virtual machines filesystem for us to download Adminer to:
- name: "Create the document root for adminer" ansible.builtin.file: dest: "{{ adminer.path }}" state: directory mode: "0755" when: adminer.installOnce we have the download target folder created, we can download Adminer itself:
- name: "Download adminer" ansible.builtin.get_url: url: "{{ adminer.download }}" dest: "{{ adminer.path }}/index.php" mode: "0755" when: adminer.installAs you may have spotted from the download URL and destination, Adminer is a single PHP file that we save as index.php. So, how will we access Adminer via our Apache web server?
Well, to do that, we need to copy across another virtual host configuration file:
- name: "Copy the adminer.conf to sites-enabled folder" ansible.builtin.template: src: adminer.conf.j2 dest: "{{ vhost_path }}adminer.conf" mode: "0755" when: adminer.install notify: "Restart apache2"As you can see, this renders and copies across roles/php/templates/adminer.conf.j2 to adminer.conf, the site-enabled folder on our remote host, and instructs the Apache service to restart to load the newly added configuration.
The adminer.conf.j2 file contains the following:
# {{ ansible_managed }}Alias /adminer "{{ adminer.path }}" <Directory "{{ adminer.path }}"> DirectoryIndex index.php AllowOverride All Require all granted </Directory>This tells Apache that whenever someone visits http://someurl/adminer/, the Adminer index.php file should be served.
With that task covered, we have completed the walk-through of the four roles that go into installing and configuring our LAMP stack, and now it is time to review and execute the playbook itself.
The LAMP playbook
Section titled “The LAMP playbook”As mentioned at the start of this chapter when we discussed the playbook structure, the main playbook file is called site.yml, which contains the following:
---- name: "Install LAMP stack" hosts: ansible_hosts gather_facts: true become: true become_method: ansible.builtin.sudo vars_files: - group_vars/common.yml roles: - common - apache - mariadb - phpAs you can see, it calls the four roles we have already walked through and also loads a variables file from group_vars/common.yml; this file contains an override for html_body, which is configured in roles/apache/defaults/main.yml and looks like the following:
html_body: | This HTML page has been deployed using Ansible to <b>{{ ansible_nodename }}</b>.<br> The user is <b>{{ users.0.name }}</b> who is in the <b>{{ apache_group }}</b> group.<br> The weboot is <b>{{ document_root }}</b>, the default index file is <b>{{ index_file }}</b>.<br><br> You can access a <a href="/info.php">PHP Info file</a> or <a href="/adminer/">Adminer</a>.This means that when we run the playbook, the index.hml page will have links to info.php and the /adminer URL to access the additional content easily.
Note
The Chapter04 folder in the GitHub repo that accompanies this title contains the example hosts file and keys to launch a local virtual machine using Multipass. If you are following along, refer to the instructions in Chapter 1, Installing and Running Ansible, for how to launch the virtual machine and prepare your own hosts file.
So, without further ado, let’s run the playbook:
$ ansible-playbook -i hosts site.ymlOn the first run, this should give us some output that looks like the following:
PLAY [ansible_hosts]TASK [Gathering Facts]ok: [ansiblevm]TASK [roles/common : update apt cache and upgrade packages]ok: [ansiblevm]…. lots of other output here ….RUNNING HANDLER [roles/apache : restart apache2]changed: [ansiblevm]PLAY RECAPansiblevm : ok=34 changed=26 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0As you can see, the Playbook has made 26 changes to the target virtual machine.
Let’s run the playbook a second time:
$ ansible-playbook -i hosts site.ymlThen, in the play recap, you should see that some tasks were skipped:
PLAY RECAPansiblevm : ok=30 changed=0 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0As expected, one of those tasks was updating the root password for the database user:
TASK [roles/mariadb : change mysql root password if we need to]skipping: [ansiblevm] => (item=127.0.0.1)skipping: [ansiblevm] => (item=::1)skipping: [ansiblevm] => (item=ansiblevm)skipping: [ansiblevm] => (item=%)skipping: [ansiblevm] => (item=localhost)skipping: [ansiblevm]The second task that is skipped is importing the database files:
TASK [roles/mariadb : import the sample database]skipping: [ansiblevm] => (item=employees.sql)skipping: [ansiblevm] => (item=show_elapsed.sql)skipping: [ansiblevm] => (item=load_departments.dump)skipping: [ansiblevm] => (item=load_employees.dump)skipping: [ansiblevm] => (item=load_dept_emp.dump)skipping: [ansiblevm] => (item=load_dept_manager.dump)skipping: [ansiblevm] => (item=load_titles.dump)skipping: [ansiblevm] => (item=load_salaries1.dump)skipping: [ansiblevm] => (item=load_salaries2.dump)skipping: [ansiblevm] => (item=load_salaries3.dump)skipping: [ansiblevm]Both are to be expected, as that is how we configured the tasks to respond on subsequent Playbook runs.
Now, if you open your browser and enter http:// and then the name of your Ansible host (for me, this was http://192.168.64.20.nip.io; I suspect yours will be different, so the link will likely not work), then you should be greeted by the index.html page that Ansible generated:

Figure 4.2 – Success!!! – viewing the index.html page
Clicking on the link for the PHP Info file should take you to something like http://192.168.64.20.nip.io/info.php, which will display information on your PHP installation:

Figure 4.3 – Viewing the PHP Info page
The final link to click is the one for Adminer; clicking it will take you to http://192.168.64.20.nip.io/adminer/, which will prompt you to log in:

Figure 4.4 – The Adminer login page
To log in, use the following credentials:
- Username:
root - Password:
Pa55W0rd123 - Database:
employees
Once logged in, you will be taken straight to an overview of the employees database:

Figure 4.5 – The employees database overview
Feel free to click around, and once you have finished, ensure that you terminate the Multipass virtual machine; instructions on how to do this can be found at the end of Chapter 1, Installing and Running Ansible.
Summary
Section titled “Summary”In this chapter, we worked through writing a playbook that installs a LAMP stack on our Multipass virtual machine. We created four roles, one for each element of the stack, and within each of the roles, we built in a bit of logic that can be overridden to deploy additional elements, such as test HTML and PHP pages, and we also built in the option to create a test database that contains over 40,000 records.
So far, we installed some basic packages. In the next chapter, we will write a playbook that installs, configures, and maintains a WordPress installation.
This updated playbook will reuse some of the elements from the roles we covered in this chapter and make some improvements, as some of the elements we covered in this chapter were a little too simplistic. The biggest change is that we will not use a hardcoded password for the database instance moving forward.
Further reading
Section titled “Further reading”You can find the project pages for the third-party tools covered throughout the chapter at the following URLs:
- Apache: https://httpd.apache.org/
- MariaDB: https://mariadb.org/
- Datacharmer test database: https://github.com/datacharmer/test_db
- PHP: https://php.net/
- Adminer: https://www.adminer.org
- NGINX: https://nginx.org