- hosts: localhost vars: meta: application_name: Nextcloud playbook_version: 0.6 app_domain: "{{ uberspace_default_web_domain }}" app_db_name: "{{ uberspace_asteroid_name }}_nextcloud" app_data_path: "/home/{{ uberspace_asteroid_name }}/nextcloud_data" app_admin_username: "{{ uberspace_asteroid_name }}" app_admin_mailaddress: "{{ uberspace_mail_sysmail }}" app_admin_password: RANDOM app_install_talk: false app_maintenance_window_start: 1 app_default_phone_region: DE _home: "/home/{{ uberspace_asteroid_name }}" _root: "/var/www/virtual/{{ uberspace_asteroid_name }}/html" _occ: [/usr/bin/php, "{{ _root }}/occ"] _archive: https://download.nextcloud.com/server/releases/latest.tar.bz2 _system_config: trusted_domains: ["{{ app_domain }}", "127.0.0.1:7868"] trusted_proxies: ['127.0.0.1'] overwrite.cli.url: "https://{{ app_domain }}" htaccess.RewriteBase: / memcache.local: '\OC\Memcache\APCu' memcache.distributed: '\OC\Memcache\Redis' memcache.locking: '\OC\Memcache\Redis' redis: host: "{{ _home }}/.valkey/valkey.sock" port: 0 maintenance_window_start: "{{ app_maintenance_window_start | int }}" default_phone_region: "{{ app_default_phone_region | upper }}" mail_smtpmode: sendmail mail_sendmailmode: pipe mail_from_address: "{{ uberspace_asteroid_name }}" mail_domain: uber.space tasks: # Required by `uberspace app install`; skipped during the actual installation. - name: _Return resolved playbook vars debug: var: vars tags: [playbook-vars] - name: Validate installation options assert: that: - app_db_name is match('^[a-zA-Z0-9_]+$') - app_db_name | length <= 63 - app_db_name.startswith(uberspace_asteroid_name + '_') - app_data_path.startswith(_home + '/') - "'..' not in app_data_path.split('/')" - app_maintenance_window_start | string is match('^([0-9]|1[0-9]|2[0-3])$') - app_default_phone_region is match('^[A-Za-z]{2}$') - uberspace_pgsql_password | default('') | length > 0 fail_msg: "Use an account-prefixed database name, a data path inside your home, a maintenance hour from 0 to 23 (UTC), and a two-letter phone region such as DE. The installer must provide your PostgreSQL password." - name: Inspect installation and data paths stat: path: "{{ item }}" loop: ["{{ _root }}", "{{ app_data_path }}"] register: paths - name: Require ordinary directories assert: that: - not item.stat.exists or (item.stat.isdir | default(false) and not item.stat.islnk | default(false)) fail_msg: "{{ item.item }} must be a directory, not a file or symlink." loop: "{{ paths.results }}" loop_control: label: "{{ item.item }}" - name: Inspect existing files including hidden files find: paths: "{{ item.item }}" hidden: true file_type: any excludes: "{{ ['nocontent.html'] if item.item == _root else [] }}" when: item.stat.exists loop: "{{ paths.results }}" loop_control: label: "{{ item.item }}" register: contents - name: Refuse to overwrite existing files assert: that: item.matched | default(0) == 0 fail_msg: "The installation and data directories must be empty. This playbook does not upgrade or repair existing installations." loop: "{{ contents.results }}" loop_control: label: "{{ item.item.item }}" - name: List existing databases command: argv: [psql, --no-psqlrc, --tuples-only, --no-align, '--dbname={{ uberspace_asteroid_name }}', '--command=SELECT datname FROM pg_database'] register: databases changed_when: false check_mode: false - name: Refuse to reuse an existing database assert: that: app_db_name not in databases.stdout_lines fail_msg: "Database {{ app_db_name }} already exists. Choose a new db_name; do not delete a database that contains data you need." - name: Check for an existing Valkey installation stat: path: "{{ item }}" loop: - "{{ _home }}/.valkey/valkey.conf" - "{{ _home }}/.config/systemd/user/valkey.service" register: valkey_files - name: Refuse to replace an existing Valkey service assert: that: not item.stat.exists fail_msg: "An existing Valkey configuration was found. Use a fresh Asteroid or follow the manual guide." loop: "{{ valkey_files.results }}" loop_control: label: "{{ item.item }}" - name: Inspect existing web routes command: argv: [uberspace, web, backend, list, --json] register: routes changed_when: false check_mode: false - name: Refuse to replace another application's routes assert: that: - item.path != '/' or item.destination == 'APACHE' - item.path != '/push' or (item.destination == 'PORT' and item.port == 7867 and item.remove_prefix) fail_msg: "The domain already has a conflicting backend. Resolve it before installing Client Push." loop: "{{ (routes.stdout | default('[]') | from_json) | selectattr('domain', 'equalto', app_domain) | list }}" loop_control: label: "{{ item.path }}" - name: Require unused Client Push ports wait_for: host: 127.0.0.1 port: "{{ item }}" state: stopped timeout: 1 loop: [7867, 7868] when: not ansible_check_mode - name: Create installation directories file: path: "{{ item.path }}" state: directory mode: "{{ item.mode }}" loop: - {path: "{{ _root }}", mode: '0755'} - {path: "{{ app_data_path }}", mode: '0700'} - {path: "{{ _home }}/.config/php", mode: '0700'} - {path: "{{ _home }}/.config/systemd/user", mode: '0700'} - {path: "{{ _home }}/.config/nextcloud-push", mode: '0700'} - {path: "{{ _home }}/.valkey", mode: '0700'} - {path: "{{ _home }}/bin", mode: '0700'} - {path: "{{ _home }}/.cache", mode: '0700'} - name: Select PHP 8.4 command: argv: [uberspace, tool, php, version, set, '8.4'] when: not ansible_check_mode - name: Configure PHP copy: dest: "{{ _home }}/.config/php/nextcloud.ini" mode: '0600' content: | memory_limit=512M output_buffering=0 opcache.enable=1 opcache.enable_cli=1 opcache.interned_strings_buffer=32 opcache.max_accelerated_files=10000 opcache.memory_consumption=128 opcache.save_comments=1 opcache.validate_timestamps=1 opcache.revalidate_freq=2 apc.enable_cli=1 apc.shm_size=64M - name: Limit PHP-FPM concurrency lineinfile: path: "{{ _home }}/.config/php-fpm.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" loop: - {regexp: '^pm.max_children\s*=', line: 'pm.max_children = 2'} - {regexp: '^pm.process_idle_timeout\s*=', line: 'pm.process_idle_timeout = 30s'} - name: Validate PHP-FPM configuration command: argv: [php-fpm, --test, --fpm-config, "{{ _home }}/.config/php-fpm.conf"] changed_when: false when: not ansible_check_mode - name: Restart PHP-FPM systemd: name: php-fpm state: restarted scope: user when: not ansible_check_mode - name: Configure Valkey on a private Unix socket copy: dest: "{{ _home }}/.valkey/valkey.conf" mode: '0600' content: | unixsocket {{ _home }}/.valkey/valkey.sock unixsocketperm 700 port 0 daemonize no save "" - name: Create Valkey service copy: dest: "{{ _home }}/.config/systemd/user/valkey.service" mode: '0600' content: | [Service] ExecStart=/usr/bin/valkey-server %h/.valkey/valkey.conf Restart=on-failure RestartSec=10 [Install] WantedBy=default.target - name: Start Valkey systemd: name: valkey daemon_reload: true enabled: true state: started scope: user when: not ansible_check_mode - name: Verify Valkey command: argv: [valkey-cli, -s, "{{ _home }}/.valkey/valkey.sock", PING] register: ping until: ping.stdout == 'PONG' retries: 10 delay: 1 changed_when: false when: not ansible_check_mode - name: Register the Nextcloud domain uberspace.api.web_domain: data: name: "{{ app_domain }}" state: present - name: Download and extract the verified release when: not ansible_check_mode block: - name: Create temporary download directory tempfile: state: directory prefix: nextcloud-install- register: download - name: Download Nextcloud and verify its published SHA-256 checksum get_url: url: "{{ _archive }}" checksum: "sha256:{{ _archive }}.sha256" dest: "{{ download.path }}/latest.tar.bz2" mode: '0600' timeout: 60 register: release_download until: release_download is succeeded retries: 3 delay: 5 - name: Extract Nextcloud into the empty document root command: argv: [tar, --extract, --bzip2, '--file={{ download.path }}/latest.tar.bz2', '--directory={{ _root }}', --strip-components=1, --no-same-owner, --same-permissions] - name: Remove the default placeholder file: path: "{{ _root }}/nocontent.html" state: absent always: - name: Remove temporary downloads file: path: "{{ download.path }}" state: absent when: download.path is defined - name: Create the PostgreSQL database command: argv: [uberspace, tool, postgresql, database, add, "{{ app_db_name }}"] when: not ansible_check_mode - name: Wait for the PostgreSQL database to accept connections command: argv: [psql, --no-psqlrc, --host=localhost, '--dbname={{ app_db_name }}', '--command=SELECT 1'] register: database_ready changed_when: false until: database_ready is succeeded retries: 24 delay: 5 when: not ansible_check_mode - name: _Choose the installation password once set_fact: _password: "{{ lookup('ansible.builtin.password', '/dev/null length=32 chars=ascii_letters,digits') if app_admin_password == 'RANDOM' else app_admin_password }}" no_log: true when: not ansible_check_mode - name: _Install Nextcloud command: argv: "{{ _occ + _install_args }}" vars: _install_args: - maintenance:install - "--admin-user={{ app_admin_username }}" - "--admin-pass={{ _password }}" - "--admin-email={{ app_admin_mailaddress }}" - --database=pgsql - --database-host=localhost - "--database-name={{ app_db_name }}" - "--database-user={{ uberspace_asteroid_name }}" - "--database-pass={{ uberspace_pgsql_password }}" - "--data-dir={{ app_data_path }}" no_log: true when: not ansible_check_mode - name: Configure domains, caching, sendmail and maintenance window command: argv: "{{ _occ + ['config:import'] }}" stdin: "{{ {'system': _system_config} | to_json }}" when: not ansible_check_mode - name: Enable clean URLs and cron background jobs command: argv: "{{ _occ + [item] }}" loop: [maintenance:update:htaccess, background:cron] when: not ansible_check_mode - name: Install Client Push and optional Talk command: argv: "{{ _occ + ['app:install', item] }}" loop: "{{ (['spreed'] if app_install_talk | bool else []) + ['notify_push'] }}" when: not ansible_check_mode # Both are quick on a fresh installation and clear the corresponding setup warnings. - name: Add optional database indices and run mimetype migrations command: argv: "{{ _occ + item }}" loop: - [db:add-missing-indices, --no-interaction] - [maintenance:repair, --include-expensive, --no-interaction] loop_control: label: "{{ item[0] }}" when: not ansible_check_mode - name: Inspect existing web headers command: argv: [uberspace, web, header, list, --json] register: headers changed_when: false check_mode: false - name: Enable HSTS command: argv: [uberspace, web, header, add, "{{ app_domain }}/", Strict-Transport-Security, max-age=15552000] when: - not ansible_check_mode - headers.stdout | default('[]') | from_json | selectattr('domain', 'equalto', app_domain) | selectattr('name', 'equalto', 'Strict-Transport-Security') | list | length == 0 - name: Configure Client Push block: - name: Configure the localhost-only callback copy: dest: "{{ _home }}/.config/nextcloud-push/Caddyfile" mode: '0600' content: | { admin off auto_https off } http://127.0.0.1:7868 { bind 127.0.0.1 root * {{ _root }} handle /index.php/apps/notify_push/* { php_fastcgi unix//var/lib/php-fpm/{{ uberspace_asteroid_name }}/php-fpm.sock { header_up X-Forwarded-For {http.request.header.X-Forwarded-For} } } handle { respond 404 } } - name: Create callback service copy: dest: "{{ _home }}/.config/systemd/user/nextcloud-push-callback.service" mode: '0600' content: | [Unit] After=php-fpm.service [Service] ExecStart=/usr/bin/caddy run --config %h/.config/nextcloud-push/Caddyfile Restart=on-failure RestartSec=10 [Install] WantedBy=default.target - name: Create Client Push service copy: dest: "{{ _home }}/.config/systemd/user/notify_push.service" mode: '0600' content: | [Unit] After=valkey.service nextcloud-push-callback.service Requires=nextcloud-push-callback.service [Service] Type=notify Environment=PORT=7867 Environment=NEXTCLOUD_URL=http://127.0.0.1:7868 ExecStart={{ _root }}/apps/notify_push/bin/x86_64/notify_push {{ _root }}/config/config.php Restart=on-failure RestartSec=10 [Install] WantedBy=default.target - name: Start Client Push services systemd: name: "{{ item }}" daemon_reload: true enabled: true state: started scope: user loop: [nextcloud-push-callback, notify_push] when: not ansible_check_mode - name: Route the domain root to Apache and /push to Client Push command: argv: "{{ ['uberspace', 'web', 'backend', 'add'] + item }}" loop: - ["{{ app_domain }}/", apache, --force] - ["{{ app_domain }}/push", port, '7867', --remove-prefix, --force] loop_control: label: "{{ item[0] }}" when: not ansible_check_mode - name: Verify Client Push after routing propagates command: argv: "{{ _occ + ['notify_push:setup', 'https://' + app_domain + '/push'] }}" register: push until: push.rc == 0 retries: 24 delay: 5 when: not ansible_check_mode - name: Schedule background jobs without overlapping runs cron: name: Nextcloud maintenance minute: '*/5' job: '/usr/bin/flock -n "{{ _home }}/.cache/nextcloud-cron.lock" /usr/bin/php -f "{{ _root }}/cron.php" > "$HOME/logs/nextcloud-cron.log" 2>&1' - name: Install the update script copy: dest: "{{ _home }}/bin/nextcloud-update" mode: '0700' content: | #!/bin/bash set -euo pipefail export PATH=/usr/local/bin:/usr/bin:/bin cd "/var/www/virtual/$USER/html" php occ status --exit-code case "${1:-}" in core) php updater/updater.phar --no-interaction ;; apps) php occ app:update --all --no-interaction ;; *) echo "Usage: $0 core|apps" >&2; exit 2 ;; esac php occ upgrade --no-interaction systemctl --user restart notify_push url=$(php occ config:system:get overwrite.cli.url) php occ notify_push:setup "${url%/}/push" - name: Schedule daily core and app updates cron: name: "Nextcloud {{ item.kind }} updates" minute: '15' hour: "{{ item.hour }}" job: '/usr/bin/flock -w 3600 "{{ _home }}/.cache/nextcloud-cron.lock" "{{ _home }}/bin/nextcloud-update" {{ item.kind }} > "$HOME/logs/nextcloud-update-{{ item.kind }}.log" 2>&1' loop: - {kind: core, hour: '3'} - {kind: apps, hour: '4'} - name: Verify the public Nextcloud installation uri: url: "https://{{ app_domain }}/status.php" return_content: true register: status until: status.status == 200 and (status.json.installed | default(false)) and not (status.json.maintenance | default(true)) and not (status.json.needsDbUpgrade | default(true)) retries: 12 delay: 5 when: not ansible_check_mode - name: _Report when: not ansible_check_mode debug: msg: | Nextcloud: https://{{ app_domain }} Username: {{ app_admin_username }} Password recovery email: {{ app_admin_mailaddress }} Use "Forgot password?" to set your password, or run: php {{ _root }}/occ user:resetpassword {{ app_admin_username }} Sendmail and caching are configured. Background jobs run every five minutes. Talk: {{ app_install_talk | bool }}; Client Push is configured. Core updates run daily at 03:15 and app updates at 04:15 (server time). Keep regular backups. Guide: https://u8lab.uberspace.de/guide_nextcloud/