How to Use Ansible to Install and Set Up Apache on Ubuntu 18.04

Introduction

Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of automating server setup by establishing standard procedures for new servers while also reducing human error associated with manual setups.

Ansible offers a simple architecture that doesn’t require special software to be installed on nodes. It also provides a robust set of features and built-in modules which facilitate writing automation scripts.

This guide explains how to use Ansible to automate the steps contained in our guide on How To Install the Apache Web Server on Ubuntu 18.04. The Apache HTTP server is the most widely-used web server in the world. It provides many powerful features including dynamically loadable modules, robust media support, and extensive integration with other popular software.

Prerequisites

In order to execute the automated setup provided by the playbook we’re discussing in this guide, you’ll need:

Before proceeding, you first need to make sure your Ansible control node is able to connect and execute commands on your Ansible host(s). For a connection test, please check step 3 of How to Install and Configure Ansible on Ubuntu 18.04.

What Does this Playbook Do?

This Ansible playbook provides an alternative to manually running through the procedure outlined in our guide on How To Install the Apache Web Server on Ubuntu 18.04.

Running this playbook will perform the following actions on your Ansible hosts:

  1. Install aptitude, which is preferred by Ansible as an alternative to the apt package manager.
  2. Install Apache.
  3. Create a custom document root folder for the new Apache VirtualHost and set up a test page.
  4. Enable the new Apache VirtualHost.
  5. Disable the default Apache website when the variable disable_default is set to true.
  6. Set up UFW to allow HTTP traffic on the configured port (80 by default).

Once the playbook has finished running, you will have a web server running on your target node, based on the options you defined within your configuration variables.

How to Use this Playbook

The first thing we need to do is obtain the Apache playbook and its dependencies from the do-community/ansible-playbooks repository. We need to clone this repository to a local folder inside the Ansible Control Node.

In case you have cloned this repository before while following a different guide, access your existing ansible-playbooks copy and run a git pull command to make sure you have updated contents:

  • cd ~/ansible-playbooks
  • git pull

If this is your first time using the do-community/ansible-playbooks repository, you should start by cloning the repository to your home folder with:

  • cd ~
  • git clone https://github.com/do-community/ansible-playbooks.git
  • cd ansible-playbooks

The files we’re interested in are located inside the apache_ubuntu1804 folder, which has the following structure:

apache_ubuntu1804
├── files
│   ├── apache.conf.j2
│   └── index.html.j2
├── vars
│   └── default.yml
├── playbook.yml
└── readme.md

Here is what each of these files are:

  • files/apache.conf.j2: Template file for setting up the Apache Virtual Host.
  • files/index.html.j2: Template file for setting up a test page on the web server’s root directory.
  • vars/default.yml: Variable file for customizing playbook settings.
  • playbook.yml: The playbook file, containing the tasks to be executed on the remote server(s).
  • readme.md: A text file containing information about this playbook.

We’ll edit the playbook’s variable file to customize a few options. Access the apache_ubuntu1804 directory and open the vars/default.yml file using your command line editor of choice:

  • cd apache_ubuntu1804
  • nano vars/default.yml

This file contains a few variables that require your attention:

vars/default.yml
---
app_user: "sammy"
http_host: "your_domain"
http_conf: "your_domain.conf"
http_port: "80"
disable_default: true

The following list contains a brief explanation of each of these variables and how you might want to change them:

  • app_user: A remote non-root user on the Ansible host that will be set as the owner of the application files.
  • http_host: Your domain name.
  • http_conf: The name of the configuration file that will be created within Apache.
  • http_port: HTTP port for this virtual host, where 80 is the default.
  • disable_default: Whether or not to disable the default website that comes with Apache.

Once you’re done updating the variables inside vars/default.yml, save and close this file. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

You’re now ready to run this playbook on one or more servers. Most playbooks are configured to be executed on every server in your inventory, by default. We can use the -l flag to make sure that only a subset of servers, or a single server, is affected by the playbook. We can also use the -u flag to specify which user on the remote server we’re using to connect and execute the playbook commands on the remote hosts.

To execute the playbook only on server1, connecting as sammy, you can use the following command:

  • ansible-playbook playbook.yml -l server1 -u sammy

You will get output similar to this:

Output
PLAY [all] ***************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************** ok: [server1] TASK [Install prerequisites] *********************************************************************************************************** ok: [server1] => (item=aptitude) TASK [Install Apache] ****************************************************************************************************************** changed: [server1] TASK [Create document root] ************************************************************************************************************ changed: [server1] TASK [Copy index test page] ************************************************************************************************************ changed: [server1] TASK [Set up Apache virtualhost] ******************************************************************************************************* changed: [server1] TASK [Enable new site] ***************************************************************************************************************** changed: [server1] TASK [Disable default Apache site] ***************************************************************************************************** changed: [server1] TASK [UFW - Allow HTTP on port 80] ***************************************************************************************************** changed: [server1] RUNNING HANDLER [Reload Apache] ******************************************************************************************************** changed: [server1] PLAY RECAP ***************************************************************************************************************************** server1 : ok=10 changed=8 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Note: For more information on how to run Ansible playbooks, check our Ansible Cheat Sheet Guide.

When the playbook is finished running, go to your web browser and access the host or IP address of the server, as configured in the playbook variables:

http://server_host_or_IP

You will see a page like this:

it works page

That means the automation was fully executed on your server, and Apache is now ready to serve static HTML pages and assets placed in the document root directory that you’ve set up within the playbook configuration variables.

The Playbook Contents

You can find the Apache server setup featured in this tutorial in the apache_ubuntu1804 folder inside the DigitalOcean Community Playbooks repository. To copy or download the script contents directly, click the Raw button towards the top of each script.

The full contents of the playbook as well as its associated files are also included here for your convenience.

vars/default.yml

The default.yml variable file contains values that will be used within the playbook tasks, such as the HTTP port and domain name to configure within your Apache VirtualHost.

vars/default.yml
---
app_user: "sammy"
http_host: "your_domain"
http_conf: "your_domain.conf"
http_port: "80"
disable_default: true

files/apache.conf.j2

The apache.conf.j2 file is a Jinja 2 template file that configures a new Apache VirtualHost. The variables used within this template are defined in the vars/default.yml variable file.

files/apache.conf.j2
<VirtualHost *:{{ http_port }}>
   ServerAdmin webmaster@localhost
   ServerName {{ http_host }}
   ServerAlias www.{{ http_host }}
   DocumentRoot /var/www/{{ http_host }}
   ErrorLog ${APACHE_LOG_DIR}/error.log
   CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

files/index.html.j2

The index.html.j2 file is another Jinja template, used to set up a test HTML page in the document root of the newly configured Apache server.

files/index.html.j2
<html>
   <head>
       <title>Welcome to {{ http_host }} !</title>
   </head>
   <body>
       <h1>Success! The {{ http_host }} virtual host is working!</h1>
   </body>
</html>

playbook.yml

The playbook.yml file is where all tasks from this setup are defined. It starts by defining the group of servers that should be the target of this setup (all), after which it uses become: true to define that tasks should be executed with privilege escalation (sudo) by default. Then, it includes the vars/default.yml variable file to load configuration options.

playbook.yml
---
- hosts: all
  become: true
  vars_files:
    - vars/default.yml

  tasks:
    - name: Install prerequisites
      apt: name={{ item }} update_cache=yes state=latest force_apt_get=yes
      loop: [ 'aptitude' ]

    - name: Install Apache
      apt: name=apache2 update_cache=yes state=latest

    - name: Create document root
      file:
        path: "/var/www/{{ http_host }}"
        state: directory
        owner: "{{ app_user }}"
        mode: '0755'

    - name: Copy index test page
      template:
        src: "files/index.html.j2"
        dest: "/var/www/{{ http_host }}/index.html"

    - name: Set up Apache virtuahHost
      template:
        src: "files/apache.conf.j2"
        dest: "/etc/apache2/sites-available/{{ http_conf }}"

    - name: Enable new site
      shell: /usr/sbin/a2ensite {{ http_conf }}
      notify: Reload Apache

    - name: Disable default Apache site
      shell: /usr/sbin/a2dissite 000-default.conf
      when: disable_default
      notify: Reload Apache

    - name: "UFW - Allow HTTP on port {{ http_port }}"
      ufw:
        rule: allow
        port: "{{ http_port }}"
        proto: tcp

  handlers:
    - name: Reload Apache
      service:
        name: apache2
        state: reloaded

    - name: Restart Apache
      service:
        name: apache2
        state: restarted

Feel free to modify these files to best suit your individual needs within your own workflow.

Conclusion

In this guide, we used Ansible to automate the process of installing and configuring Apache on Ubuntu 18.04.

If you’d like to include other tasks in this playbook to further customize your server setup, please refer to our introductory Ansible guide Configuration Management 101: Writing Ansible Playbooks.

Creative Commons License