The previous playbooks completed all preparations. This playbook effectively follows the Nextcloud installation guide and creates the database and filesystem directories, deploys the Nextcloud files and Apache2 site ready for the initial administrator login.

Automation Overview

If you refer back to the Automation Approach I broke the process for deploying a Nextcloud VM down into six steps:

  1. Create a virtual machine with the operating system installed and ready for Ansible to start configuration ✅
  2. Ansible playbook for initial OS configuration to prepare for the main automation execution. ✅
  3. Ansible playbook to complete OS configuration and install standard utilities and applications.  ✅
  4. Ansible playbook to configure Nextcloud-specific pre-requisites such as filesystems, PHP and MariaDB  ✅
  5. Ansible playbook to create the database and deploy Nextcloud itself
  6. Ansible playbook to do the initial configuration of Nextcloud

This playbook will connect to our target VM as the ansible user with an SSH key so there no need for any further manual intervention (unless something breaks of course).

If you're following along then you'll need to have completed the config from Playbook 1 - First Contact and at least installed the acl package from Playbook 2 - OS Config and the required applications in Playbook 3 - Nextcloud Prerequisites even if you skipped the rest.

Playbook Requirements

In the previous three playbooks we completed all of the usual tasks for building a brand new Ubuntu virtual machine and installed the prerequisite applications. We now get to complete the Nextcloud-specific configuration tasks and then install Nextcloud itself.

This playbook will:

  1. Install the additional PHP modules required by Nextcloud
  2. Properly configure and remount the the filesystems and create the Nextcloud directories
  3. Download the installation archive and extract the files
  4. Configure an Apache2 site
  5. Create the Nextcloud database in MariaDB

This whole playbook could be split into roles but there's probably little benefit unless I have a need for different types of Nextcloud installation.

Update the Ansible Inventory

We don't need any host-specific info for the installation so no need to add to the inventory just yet.

Update the Playbook Launcher

We need to enable nextcloud4.yaml in nextcloud.sh, our playbook launcher script.

RunPlaybookSSH "nextcloud2.yaml"
RunPlaybookSSH "nextcloud3.yaml"
RunPlaybookSSH "nextcloud4.yaml"
#RunPlaybookSSH "nextcloud4.yaml"
#RunPlaybookSSH "nextcloud5.yaml"

Simply remove the # from the beginning of the line.

Play: Deploy Nextcloud

This was designed to work with the a new VM as created by the Ubuntu installer, which doesn't handle Btrfs subvolumes. With the benefit of hindsight it would have been better to done the configuration of the /srv/nextcloud filesystem before creating the OVF template and saved some effort in the playbooks.

Filename: nextcloud4.yaml

---
# Ansible Playbook

# New Nextcloud host setup
#  Stage 4: Deploy Nextcloud
#
# Uses the ansible SSH key

- name: Deploy Nextcloud
  hosts: "{{ target }}"

  vars_files:
  - vars/nextcloud.yaml

  tasks:

  # Configure PHP
  - name: Additional PHP modules for Nextcloud
    become: true
    ansible.builtin.package:
      name:
      - "php{{ php_release }}-apcu"
      - "php{{ php_release }}-bz2"
      - "php{{ php_release }}-cgi"
      - "php{{ php_release }}-cli"
      - "php{{ php_release }}-curl"
      - "php{{ php_release }}-gd"
      - "php{{ php_release }}-imagick" 
      - "php{{ php_release }}-intl" 
      - "php{{ php_release }}-ldap" 
      - "php{{ php_release }}-mbstring"
      - "php{{ php_release }}-mysql" 
      - "php{{ php_release }}-xml"
      - "php{{ php_release }}-zip" 
    notify: Restart PHP  
   
    # phpX.X-json not needed since 8.0

We start by installing the additional PHP modules that Nextcloud requires.


  #####################################
  #
  #  Prepare filesystems
 

  # fix /etc/fstab
  - name: Modify nextcloud mount in fstab
    become: true
    ansible.builtin.lineinfile:
      path: /etc/fstab
      regexp: '^/dev/disk/(.*) /srv/nextcloud btrfs defaults 0 0'
      line: '/dev/disk/\1 {{ nextcloud_dir_nextcloud }} btrfs defaults,subvol={{ nextcloud_subvol_nextcloud }} 0 0'
      backrefs: true
      backup: true
    register: fstab

We need to change the fstab file to reference the btrfs subvolume we're going to create. We use a regular expression to find a line in the /etc/fstab file that starts with /dev/disk/ followed by some other text that we tell it to remember which will be the device identified, then continues with /srv/nextcloud btrfs defaults 0 0 which is how the installer left it.

We replace this line with /dev/disk/ as before, then the device identifer we remembers (the \1 means the first section of remembered text) and then the path to the nextcloud filesystem which is also /srv/nextcloud at this time. We still keep the btrfs filesytem type and defaults but add in the subvol= and the name of our btrfs subvolume.

We want to use the properties of fstab later so we need to regester this task. And given that fstab is essential for booting, we keep a backup of this file just in case something breaks.

 

  - name: Remount /srv/nextcloud
    block:

    - name: Create subvol @nextcloud
      become: true
      ansible.builtin.shell: 
        cmd: btrfs subvol create /srv/nextcloud/{{ nextcloud_subvol_nextcloud }}
        creates: /srv/nextcloud/{{ nextcloud_subvol_nextcloud }}

    - name: Unmount /srv/nextcloud
      become: true
      ansible.builtin.shell: 
        cmd: umount /srv/nextcloud
  
    - name: Mount /srv/nextcloud
      become: true
      ansible.builtin.shell: 
        cmd: mount {{ nextcloud_dir_nextcloud }}

    - name: Set nextcloud permissions
      become: true
      ansible.builtin.file:
        path: "{{ nextcloud_dir_nextcloud }}"
        owner: "{{ nextcloud_os_user }}"
        group: "{{ nextcloud_os_group }}"
        mode: '0755'      

    when: fstab.changed

If we need to rerun the playbook we need to make sure it doesn't keep repeating this process endlessly so we put it within a block that will only run if we made a change to the fstab file in the previous step.

We start by creating the nextcloud subvolume in the current /srv/nextcloud directory, the creates: parameter means this shell command only runs if the named file or directory doesn't alreay exist.

We then unmount /srv/nextcloud and then mount it again and this time it will mount using the subvolume we specified in the fstab file but it will still appear as /srv/nextcloud, or whatever set in the vars file if different and finally set the permissions.

 

  - name: Create subvol @nextcloud/www
    become: true
    ansible.builtin.shell:
      cmd: btrfs subvol create {{ nextcloud_dir_www }}
      creates: "{{ nextcloud_dir_www }}"

  - name: Set nextcloud/www permissions
    become: true
    ansible.builtin.file:
      path: "{{ nextcloud_dir_www }}"
      owner: "{{ nextcloud_os_user }}"
      group: "{{ nextcloud_os_group }}"
      mode: '0750'

Next we create the /srv/nextcloud/www directory for the Nextcloud site files and executables as a btrfs subvolume if it doesn't already exist and set permissions on it. As a subvolume we can then use snaphots for backup.

 

  - name: Create subvol @nextcloud/data
    become: true
    ansible.builtin.shell: 
      cmd: btrfs subvol create {{ nextcloud_dir_data }}
      creates: "{{ nextcloud_dir_data }}"

  - name: Set nextcloud/data permissions
    become: true
    ansible.builtin.file:
      path: "{{ nextcloud_dir_data }}"
      owner: "{{ nextcloud_os_user }}"
      group: "{{ nextcloud_os_group }}"
      mode: '0750' 

And also create the /srv/nextcloud/data directory as a btrfs subvolume too, if it doesn't already exist, and set permission on it.

 

  - name: Create backup (+ db) directory
    become: true
    ansible.builtin.file:
      path: "{{ nextcloud_dir_nextcloud }}/backup/db"
      state: directory
      mode: '0750'
      owner: root
      group: root

And finally we create the backup directory where we will mount backup snaphots and also dump the database to as part of the backup process.

 

  #####################################
  #
  #  Download and extract archive

  - name: Download nextcloud archive
    become: true
    ansible.builtin.get_url:
      url: "{{ nextcloud_install_location }}/{{ nextcloud_install_archive }}"
      dest: "{{ nextcloud_dir_nextcloud }}"
      checksum: "{{ nextcloud_install_checksum }}"

  - name: Install unzip
    become: true
    ansible.builtin.package:
      name: unzip

  - name: Unzip nextcloud
    become: true
    ansible.builtin.unarchive:
      remote_src: true
      src: "{{ nextcloud_dir_nextcloud }}/{{ nextcloud_install_archive }}"
      dest: "{{ nextcloud_dir_www }}"

I downloaded the Nextcloud 28.0.0 installation zip from https://nextcloud.com/changelog/ file and keep that on an internal webserver (actually a site on my main Nextcloud host!) and put the address and the archive name into the var/nextcloud.yaml file which means I get a known-good installation to work from each time and it save a bit of time too. As new versions are release I can easily switch to one of those instead. This is then downloaded from my webserver and unzipped into our /srv/nextcloud/www directory, installing unzip first.


      
  - name: Move files
    become: true
    ansible.builtin.shell:
      cmd: "mv -f {{ nextcloud_dir_www }}/nextcloud/* {{ nextcloud_dir_www }}"
      creates: "{{ nextcloud_dir_www }}/occ"

  - name: Move files
    become: true
    ansible.builtin.shell:
      cmd: "mv -f {{ nextcloud_dir_www }}/nextcloud/.htaccess {{ nextcloud_dir_www }}"

  - name: Move files
    become: true
    ansible.builtin.shell:
      cmd: "mv -f {{ nextcloud_dir_www }}/nextcloud/.user.ini {{ nextcloud_dir_www }}"

  - name: Clean extract directory
    become: true
    ansible.builtin.file:
      path: "{{ nextcloud_dir_www }}/nextcloud"
      state: absent

  - name: Set Nextcloud file owner
    become: true
    ansible.builtin.file:
      recurse: true
      path: "{{ nextcloud_dir_www }}"
      owner: "{{ nextcloud_os_user }}"
      group: "{{ nextcloud_os_group }}"

Unfortunately an additional nextcloud directory is created during the unzip so we have to move all the files back into the right place and delete it. Then set file ownerships but leave permissions alone.
      

  #####################################
  #
  #  Configure Apache2

  - name: Drop Apache HTTP Nextcloud config
    become: true
    ansible.builtin.template:
      src: apache_nextcloud.conf.j2
      dest: /etc/apache2/sites-available/nextcloud.conf
      owner: root
      group: root
      mode: '0640'

  - name: Enable Nextcloud HTTP site
    become: true
    ansible.builtin.shell:
      cmd: a2ensite nextcloud
    notify: Restart Apache2

  - name: Disable Default HTTP site
    become: true
    ansible.builtin.shell:
      cmd: a2dissite 000-default
    notify: Restart Apache2

  - name: Drop Apache2 HTTPS Nextcloud config
    become: true
    ansible.builtin.template:
      src: apache_nextcloud.conf.j2
      dest: /etc/apache2/sites-available/nextcloud_s.conf
      owner: root
      group: root
      mode: '0640'

  - name: Info Apache2 HTTPS
    ansible.builtin.debug:
      msg: TLS certs and SSL module needed to enable HTTPS.

With the Nextcloud files extracted we can now create the Apache2 sites using a pair of Jinja2 templates: apache_nextcloud.conf.j2 (an HTTP site)  and apache_nextcloud_s.conf.j2 (an HTTPS). For the HTTP site we enable it and disable the default site, but for the HTTPS site we need to install the certificates we requested during Playbook 2 - OS Config first which is a manual process so we can't enable it here.


  #####################################
  #
  #  Create Database

  - name: Install Python support for Ansible MySQL collection
    become: true
    ansible.builtin.package:
      name: python3-pymysql

  - name: Create MariaDB database
    become: true
    community.mysql.mysql_db:
      login_unix_socket: /run/mysqld/mysqld.sock
      name: "{{ nextcloud_db_name }}"
      state: present

The final step is to create the database that Nextcloud will use. I could have done this with a shell command instead and saved the dependencies on the mysql collection.


  handlers:

  - name: Restart PHP
    become: true
    ansible.builtin.systemd:
      state: restarted
      name: "php{{ php_release }}-fpm"

  - name: Restart Apache2
    become: true
    ansible.builtin.systemd:
      state: restarted
      name: apache2
...

We need to restart php-fpm and Apache2 for some of the changes we made here. Using handlers means we can save any needed restart untill the end of the play.

Variables: Nextcloud

We created this file in the previous playbook so we could get the PHP version we needed. We now need to add the rest of the configuration variables that set the version and where I've cached the Nextcloud deployment zip and also where we will install to.

I'm thinking it might be better to move these to a defaults file so they could potentially be overridden by inventory variables.

Filename vars/nextcloud.yaml

---
# Ansible Vars
# Variables for Nextcloud playbook
#   Commented variables should be in inventory

php_release: "8.2"

nextcloud_install_version: 28.0.0
nextcloud_install_archive: nextcloud-28.0.0.zip
nextcloud_install_location: http://intraweb.example.com/deploy/nextcloud
nextcloud_install_checksum: sha256:45faa3e89afa002fc722c2750b3aadbcc62e6b0581d9ea904f770c57dad4544a

nextcloud_dir_nextcloud: /srv/nextcloud
nextcloud_dir_data: /srv/nextcloud/data
nextcloud_dir_www: /srv/nextcloud/www
nextcloud_subvol_nextcloud: "@nextcloud"

nextcloud_os_user: www-data
nextcloud_os_group: www-data

...

 

Template: Apache2 Nextcloud HTTP site

This template is an Apache2 site conf file into which we substitute the path to the Nextcloud www directory and the hostname. The playbook generates and saves this file in the task Drop Apache HTTP Nextcloud config.

Filename: templates/apache_nextcloud.conf.j2

<VirtualHost *:80>
  DocumentRoot {{ nextcloud_dir_www }}
  ServerName  {{ inventory_hostname }} 

  ErrorLog /var/log/apache2/nextcloud.error.log
  CustomLog /var/log/apache2/nextcloud.access.log combined

  <Directory {{ nextcloud_dir_www }}>
    Require all granted
    AllowOverride All
    Options FollowSymLinks MultiViews

    SetEnv HOME {{ nextcloud_dir_www }}
    SetEnv HTTP_HOME {{ nextcloud_dir_www }}

    Satisfy Any

    <IfModule mod_dav.c>
      Dav off
    </IfModule>
  
  </Directory>

</VirtualHost>

 

Template: Apache2 Nextcloud HTTPS site

This template is an Apache2 HTTPS site conf wth extra parameters for the TLS key and certificate into which we substitute the path to the Nextcloud www directory and the hostname. The playbook generarates and saves this file in the task Drop Apache HTTPS Nextcloud config.

Filename: templates/apache_nextcloud.conf.j2

<VirtualHost *:443>
  DocumentRoot {{ nextcloud_dir_www }}
  ServerName  {{ inventory_hostname }}

  ErrorLog /var/log/apache2/nextcloud_s.error.log
  CustomLog /var/log/apache2/nextcloud_s.access.log combined

  SSLEngine on
  SSLCertificateFile /etc/ssl/certs/nextcloud-cert.pem
  SSLCertificateKeyFile /etc/ssl/private/nextcloud-key.pem

  <Directory {{ nextcloud_dir_www }}>
    Require all granted
    AllowOverride All
    Options FollowSymLinks MultiViews

    SetEnv HOME {{ nextcloud_dir_www }}
    SetEnv HTTP_HOME {{ nextcloud_dir_www }}

    Satisfy Any

    <IfModule mod_dav.c>
      Dav off
    </IfModule>
  
  </Directory>

</VirtualHost>

Ideally the TLS certificate and private key will be named as specified in the SSLCertificateFile and SSLCertificateKeyFile parameters otherwise you'll need to modify the generated site config file.

Review

Most of the complexity in this playbook is in creating the btrfs subvolumes and remounting /srv/nextcloud in such a way that rerunning the the playbook doesn't result in a horrible mess. The Nextcloud deployment is quite straightforward really.

At the end of this play Nextcloud will be running and if you were to start a browser session to the server you'll get the Nextcloud initial configuration screen. In the final playbook we will connect Nextcloud to its database and apply some initial configuration parameters.