The playbook in our Nextcloud installation applies the initial configuration to make the system ready for users.

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 Playbook 4 - Nextcloud Install with Nextcloud installed and the initial configuration screen available in a browser.

Playbook Requirements

In the previous four playbooks we completed all of the usual tasks for building a brand new Ubuntu virtual machine and installed the prerequisite applications, configured the /srv/nextcloud filesystem and Apache2 and have Nextcloud running and waiting for the initial configuration. We now trigger the initial configuration process and to set some installation defaults and the admin user.

This playbook will:

  1. Configure PHP memory limits for Nextcloud
  2. Create the database user
  3. Run the Nextcloud initial installation
  4. Apply a default configuration for region, mail notifications and cache
  5. Configure Nextcloud job processing

This whole playbook could be a role but there's probably little benefit beyond reducing the number of plays needed.

Update the Ansible Inventory

Untill now all the parameters we've needed have been in general host or subnet configuration that I have already had in my Ansible Inventory, or general installation settings specified in the vars files for the playbooks themselves.

In this play we are going to customise this specific Nextcloud instance based partly on the network, which is controlled by a group, and partly on the host itself.

While this could be done within the main inventory file, Ansible provides a couple of nice features in the inventory that can make this easier to manage. And if you've been following along this should already have been completed as part of preparation, but as recap is useful now we're going to use them.

Group Vars

In the 100-dev.yaml file of our example inventory I defined a nextcloud_dev group which included the nextcloud hosts. While I could have put a vars: section in there I created a separate nextcloud_dev.yaml file and placed that in the group_vars folder so that I don't need to edit the 100-dev.yaml just to change global Nextcloud installation parameters.

In my sandpit subnet I have a mail server that will accept mail from any host on the subnet to be delivered to internal mail addresses so I can use this for Nextcloud to send alert and notification messages. I could also use some of the settings from the config_mailalert* entries set in the 000-base.yaml inventory file if I wanted as well.

Filename (in inventory, not playbook): group_vars/nextcloud-dev.yaml

---
# Ansible Vars
# group_vars for nextcloud
nextcloud_mail_smtphost: devmail1
nextcloud_mail_smtpport: 25
nextcloud_mail_smtpsecure: ''
nextcloud_mail_smtpauth: False
nextcloud_mail_from_address: "{{ inventory_hostname_short }}-notify"
nextcloud_mail_domain: sandpit.example.com
...

These settings only apply to the Administration > Basis Settings : Email Server used for sending notifications. The web mail client under Administration > Groupware : Mail App has it's own configuration parameters that would only be needed on selected Nextcloud instances.

Host Vars

We can also do something similar with hosts as well, and this is even more useful in terms of simplifying inventory management. While adding variables under the VMs entry in the main inventory file is workable for a small scale lab it can result in large inventory files and can make automating the inventory a lot more awkward.

By creating a directory named with the full name of the host as it appears in the main inventory, we can simply add yaml files with the desired configuration in the hosts directory for each application we want to deploy on that host. Any automation only needs to be able to process its own config file which will be a much simpler structure too.

Filename (in inventory, not playbook): host_vars/svu-ncdeploy-1.sandpit.example.com/nextcloud.yaml

---
# Ansible Vars
# Variable for host svu-ncdeploy-1
nextcloud_admin_user: ncdevmin
nextcloud_admin_pass: "{{ nextcloud_vault_admin_pass }}"

nextcloud_db_name: nextclouddb
nextcloud_db_user: nextcloud
nextcloud_db_pass: "{{ nextcloud_vault_db_pass }}"
...

We can also have an encrypted vault file which holds the sensitive parameters such as passwords and possibly even usernames might be worth protecting too.

Filename (in inventory, not playbook): host_vars/svu-ncdeploy-1.sandpit.example.com/nextcloud-vault.yaml

---
# Vaulted Nextcloud host vars for svu-ncdeploy-1
nextcloud_vault_admin_pass: AdminPassHere
nextcloud_vault_db_pass: DBpassHere
...

Obviously the nextcloud-vault.yaml should be encrypted as soon as you've created it and certainly before you check it in to source control.

And just because we're using group_vars and host_vars to manage Nextcloud, it doesn't stop us using vars: clauses under the group or host file in the main inventory - both are supported and the precedence rules for variables takes account of this

 

Update the Playbook Launcher

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

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

Simply remove the # from the beginning of the line.

Play: Nextcloud Initial Configuration

This could also be a single role and there's also a good arguement for making the updates to the Nextcloud config.php a role. But since this playbook is intended to be called just once for the initial configuration of a new Nextcloud installation we can do things the quick and simple way.

I do like the idea of being able to install and configure specific Nextcloud apps at this point so there's a good chance I'll enhance this at some point.

Filename: nextcloud5.yaml

---
# Ansible Playbook

# New Nextcloud host setup
#  Stage 5: Nextcloud Initial Configuration
#
# Uses the ansible SSH key


- name: Nextcloud Initial Configuration
  hosts: "{{ target }}"

  vars_files:
  - vars/nextcloud.yaml


  tasks:

#######################################
#
#  Configure PHP memory allocations.
#
  - name: Set PHP memory limit
    become: true
    community.general.ini_file:
      create: false
      path: "/etc/php/{{ php_release }}/fpm/php.ini"
      section: PHP
      option: memory_limit
      value: 512M
    notify: Restart PHP

  - name: Set PHP CLI memory limit
    become: true
    community.general.ini_file:
      create: false
      path: "/etc/php/{{ php_release }}/cli/php.ini"
      section: PHP
      option: apc.enable_cli
      value: 1

Nextcloud requires the memory limit for PHP processes to be increased from the default 128 MB to 512 MB. The config file is in INI format and the Ansible community.general collection has a module to make managing .ini files simple.

I should make the memory limit a variable in the next update just to make it easier to change.


#######################################
#
#  Nextcloud initial configuration
#

  - name: Create nextcloud DB user
    become: true
    community.mysql.mysql_user:
      login_unix_socket: /run/mysqld/mysqld.sock
      name: "{{nextcloud_db_user }}"
      password: "{{ nextcloud_db_pass }}"
      state: present
      priv: '{{ nextcloud_db_name }}.*:ALL'

  - name: Nextcloud OCC initialisation
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.shell:
      chdir: "{{ nextcloud_dir_www }}"
      cmd: "php occ maintenance:install --data-dir='{{ nextcloud_dir_data }}' --database=mysql --database-name='{{ nextcloud_db_name }}' --database-user='{{ nextcloud_db_user }}' --database-pass={{ nextcloud_db_pass }} --admin-user='{{ nextcloud_admin_user }}' --admin-pass='{{ nextcloud_admin_pass }}'"
      creates: "{{ nextcloud_dir_www }}/config/config.php"

We created the Nextcloud database in the previous playbook, now we create the user itself and grant it privileges over the databasee. And then providing the config.php file doesn't exist, which is a sign the the initial config hasn't been done, we use occ to run the initial configuration.

For each of the following settings we could also call occ, but given the the official install guide says to just edit the config.php that's good enough for me.

 

#######################################
#
#  Configure Nextcloud config.php
#    [could also use occ commands]
#

  - name: Add default phone region
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: default_phone_region
      line: "  'default_phone_region' => 'GB',"

  - name: Set mail mode
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_smtpmode
      line: "  'mail_smtpmode' => 'smtp',"

  - name: Set mail host
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_smtphost
      line: "  'mail_smtphost' => '{{ nextcloud_mail_smtphost }}',"

  - name: Set mail port
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_smtpport
      line: "  'mail_smtpport' => {{ nextcloud_mail_smtpport }},"

  - name: Set mail connection encryption to none/starttls
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_smtpsecure
      line: "  'mail_smtpsecure' => '{{ nextcloud_mail_smtpsecure }}',"

  - name: Set mail authentication none
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_smtpauth
      line: "  'mail_smtpauth' => '{{ nextcloud_mail_smtpauth }}',"

  - name: Set mail from address
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_from_address
      line: "  'mail_from_address' => '{{ nextcloud_mail_from_address }}',"

  - name: Set mail from domain
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: mail_domain
      line: "  'mail_domain' => '{{ nextcloud_mail_domain }}',"

  - name: Configure memcache - APCu
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertbefore: '^\);'
      regexp: memcache.local
      line: "  'memcache.local' => '\\OC\\Memcache\\APCu',"

  - name: Configure Trusted domains
    become: true
    become_user: "{{ nextcloud_os_user }}"
    ansible.builtin.lineinfile:
      path: "{{ nextcloud_dir_www }}/config/config.php"
      state: present
      insertafter: "^    0 => 'localhost',"
      regexp: 1 => '{{ inventory_hostname }}',
      line: "    1 => '{{ inventory_hostname }}',"

Each parameter is updated in the same way. By specifying a regexp if the setting already exists we will update it. The config.php file is implemented as an array so we can add new parameters by specifying they are added before the closing ); of the array, except for the Configure Trusted Domains step where we're taking a bit of a chance that the line 0 => 'localhost' is in the right place. If Nextcloud change this in future versions I'll have to find some other way of doing it.

 

#######################################
#
#  Deploy systemd units for cron.php
#

  - name: Deploy nextcloud-cron service
    become: true
    ansible.builtin.template:
      src: nextcloud-cron.service.j2
      dest: /etc/systemd/system/nextcloud-cron.service
      owner: root
      group: root
      mode: '0644'
    notify: Systemd nextcloud-cron-service enable

  - name: Deploy nextcloud-cron timer
    become: true
    ansible.builtin.copy:
      src: nextcloud-cron.timer
      dest: /etc/systemd/system/nextcloud-cron.timer
      owner: root
      group: root
      mode: '0644'
    notify: Systemd nextcloud-cron-timer enable

Nextcloud has an internal batch processing system that can be trigged in three different ways: user activty, a webcron service or cron jobs on the host. Instead of cron, these two tasks deploy a systemd service unit that runs the cron.php and a timer unit that triggers the service every 5 minutes. As soon as the cron.php is called Nextcloud will show that Cron is being used, which can be checked via via Administration > Basic Settings : Background Jobs.

 


  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

  - name: Systemd nextcloud-cron-service enable
    become: true
    ansible.builtin.systemd:
      state: restarted
      daemon_reload: true
      name: nextcloud-cron.service

  - name: Systemd nextcloud-cron-timer enable
    become: true
    ansible.builtin.systemd:
      state: restarted
      enabled: true
      daemon_reload: true
      name: nextcloud-cron.timer

...

We need to restart php-fpm and Apache2 for the changes we made here, and reload systemd daemons and enable our two new units. Using handlers means we can save any needed restart until the end of the play.

Variables: Nextcloud

We created this file in Playbook 3 - Nextcloud Prerequisites so we could get the PHP version we needed and added the file system in Playbook 4 - Nextcloud Install, and we need both again here there to update the configuration.

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: Nextcloud cron.php Service Unit

This template creates a systemd service unit that will call execute the cron.php for Nextcloud background jobs.  The playbook generates and saves this file in /etc/systemd/system.

Filename: templates/nextcloud-cron.service.j2

[Unit]
Description=Nextcloud cron.php job

 

[Service]
User={{ nextcloud_os_user }}
ExecStart=/usr/bin/php -f {{ nextcloud_dir_www }}/cron.php
KillMode=process

 

File: Nextcloud cron.php Timer Unit

This template creates a systemd timer unit that will trigger the nextcloud-cron service we defined above every 5 minutes. The playbook saves this file in /etc/systemd/system too.

Filename: files/nextcloud-cron.timer

[Unit]
Description=Run Nextcloud cron.php every 5 minutes

[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Unit=nextcloud-cron.service

[Install]
WantedBy=timers.target

 

Series Review

You should now be able to create a complete installation of a Nextcloud, running on Ubuntu 20.04 LTS in an ESXi virtual machine ready to start playing with. It used to take me a couple of evenings to install a Nextcloud server from scratch, now it's down to less than 20 minutes and most of that is waiting for apt updates to apply which seem to take a disproportionate amount of time under Ansible.

I have some additional articles in preparation / todo to expand on related topics, especially around my GeekLab and ways of making the best use of some of the Nextcloud capabilities from a users point of view, plus of course the roles reused from other playbooks.

Nextcloud Installation Checklist

Now that Nextcloud is installed and running there's still some final checks and actions these playbooks don't (and probably shouldn't) do:

  • Check for any alerts in Administration > Overview : Security & setup warning
  • Install the TLS certificate requested in Playbook 2 - OS Config and enable HTTPS if you haven't done so already
  • Configure backup - see Test Nextcloud 26 Installation #Backup Config for example Bacula scripts and config using btrfs snapshots and a database dump.
  • Update to latest version. Nextcloud 28.0.2 is the latest at the time of writing. See Administration > Overview : Update for the latest release and to trigger the update process.
  • Install and configure additional applications
  • Create users or connect to an LDAP service
  • Apply all remaining Ubuntu updates via apt

Future ideas

And at the time of writing (February '24) we're only a couple of months away from the release of Ubuntu 24.04 LTS which will almost certainly needs some adjustments and will be a good time to incorporate some of the improvements I've highlighted in this series. And we've also had the recent announcement from Broadcom about  killing off the free ESXi hypervisor which means I need to reconsider the entire setup of my Geeklab and while that won't be an immediate change there could be some very interesting opportunities opened up through using a different virtualisation layer.

Other ideas, which I may do sooner if I find I'm setting these up regularly include:

  • Configure a connection to an LDAP for user accounts. Ideally it would also create a bind user in the LDAP too.
  • Configure the webmail client to point to an IMAP4 server.
  • Install and configure a list of additional applications
  • Disable a list of default applications
  • Deploy Bacula scripts automatically
  • Deploy the OVF template