Skip to content

ManagedExternal Database

spec.database.mode: ManagedExternal lets an instance get its PostgreSQL database from a shared database provider (an HTTPS service that hands out one database per instance on shared PostgreSQL shards) instead of running a PostgreSQL cluster per instance (Managed PostgreSQL) or pointing at a database you run yourself.

The operator never talks to PostgreSQL directly in this mode. It asks the provider for a database, waits until the provider reports it Ready, and writes the connection details into the instance's <instance>-nextcloud-db Secret.

Mode Who runs PostgreSQL Set by
Managed The operator, one Percona cluster per instance managed: true, type: postgresql
External You host / credentialsSecret
ManagedExternal The shared database provider mode: ManagedExternal

mode has no default. An instance without it behaves exactly as before.

1. Configure the operator

Set the provider URL and reference two Secrets in the operator's own namespace:

# Operator Helm values
databaseProvider:
  url: https://db-provider.example.internal
  caSecretName: db-provider-ca        # key: ca.crt
  tokenSecretName: db-provider-token  # key: token
kubectl -n <operator-namespace> create secret generic db-provider-ca \
  --from-file=ca.crt=./provider-ca.pem
kubectl -n <operator-namespace> create secret generic db-provider-token \
  --from-literal=token='<bearer token>'
  • The Secret keys are fixed: ca.crt and token.
  • databaseProvider.url must start with https://. The chart refuses to render any other URL, and the operator refuses it at runtime (DatabaseProviderUnavailable, "provider URL must be https"), so the bearer token is never sent in clear text.
  • If databaseProvider.url is set, both Secret names are required; the chart refuses to render otherwise.
  • The CA you supply is the only trust root used for the provider (the system trust store is not consulted), and redirects are not followed.
  • With the default (empty) values the chart renders a Deployment identical to one without this feature: no extra environment variables, volumes or mounts.

The values become the environment variables DB_PROVIDER_URL, DB_PROVIDER_CA_FILE (/etc/db-provider/ca.crt) and DB_PROVIDER_TOKEN_FILE (/etc/db-provider/token). Both Secrets are mounted as one projected directory (/etc/db-provider).

Rotating the token or CA without a restart

The token file is read on every provider call and the CA file is passed to every request, and a directory mount is refreshed in place by the kubelet. To rotate, update the Secret:

kubectl -n <operator-namespace> create secret generic db-provider-token \
  --from-literal=token='<new token>' --dry-run=client -o yaml | kubectl apply -f -

The new value is picked up once the kubelet has synced the volume (typically within a minute or two). No pod restart is needed. Do not switch the mount to subPath: such mounts never update.

Provider version

The operator requires the provider to report a minimum API version. A provider that is too old is treated as a rejection (see DatabaseProviderRejected below).

2. Request ManagedExternal on an instance

spec:
  database:
    mode: ManagedExternal
    type: postgresql      # optional; the only supported value
    sizeClass: small      # optional; passed to the provider, which defines the classes

A ManagedExternal spec must not set managed: true (managed: false is allowed), and must not set host, port, name, credentialsSecret, user or password. The provider decides the connection details, including the generated database name. Such a spec is rejected at create (DatabaseReady=False, reason InvalidConfig, phase Failed). This rejection is permanent: a failed create handler is not retried, so correct the spec and recreate the instance. The Helm values always take host, port and database name from the <instance>-nextcloud-db Secret, never from the spec.

The provider identifies the database by the instance's metadata.uid.

sizeClass is create-time only

The provider receives sizeClass only while the database is being created (until it first reports Ready). After that the operator never sends it again. If you change sizeClass on an instance whose database is ready, the operator sets the informational condition DatabaseSizeClassChangeIgnored=True and makes no provider call. The rest of the edit, such as a version upgrade, is applied normally. To resize a database, ask the provider operator for a change on their side. status.database.provider.sizeClass shows the class the database was created with (empty means the provider default).

Network egress to the provider database

Profiles may render a namespace-wide default-deny NetworkPolicy through helm.values.extraManifests. Such a policy blocks the connection to the provider's shard, and the wait-for-db init container then waits forever.

If the provider's host is an IPv4 address that is global or private unicast, the operator adds one NetworkPolicy to the HelmRelease values for you. It is appended to extraManifests; the profile's and your own entries are kept. In the map form of extraManifests it uses the key bnerd-db-provider-egress.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: <release>-db-provider-egress
  namespace: <instance namespace>
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress:
    - to: [{ipBlock: {cidr: <provider host>/32}}]
      ports: [{port: <provider port>, protocol: TCP}]

Host and port are the values in <instance>-nextcloud-db. Helm applies the policy, so the operator needs no extra RBAC. The policy only adds an allow rule. It has no effect in a namespace without a default-deny egress policy.

If the provider's host is a hostname, the operator renders nothing (it does not resolve DNS). It sets DatabaseEgressNotRendered=True (reason HostNotIPv4), and the message names the host and port. If the namespace denies egress by default, allow egress to that host and port yourself, for example with your own NetworkPolicy in helm.values.extraManifests. The condition is cleared (False) when a later render includes the policy.

If the host is an IPv4 address that is loopback (127.0.0.0/8), unspecified (0.0.0.0), link-local (169.254.0.0/16, which includes cloud metadata services), multicast, reserved (240.0.0.0/4) or broadcast, the operator renders nothing either. It sets DatabaseEgressNotRendered=True with reason HostNotAllowed. Such an answer is a provider error: ask the provider operator to fix it.

Other instances (Managed, External, SQLite) get no such policy.

SSL to the provider database

The connection to the provider database always uses SSL. The operator adds these to nextcloud.extraEnv in the HelmRelease values; the chart sets them on the Nextcloud container, the cron sidecar and the cron job:

Variable Value
PGSSLMODE require
PGSSLCERT /nonexistent/client.crt
PGSSLKEY /nonexistent/client.key

PGSSLMODE is require whatever the provider sends:

Provider sslmode Used Operator log
none, require require none
disable, allow, prefer require (these would allow plaintext) warning
verify-ca, verify-full require (no root CA is configured yet, so the server certificate cannot be verified) info

The log line is written once when the provider's value is first stored or changes, not on every reconcile. With require the connection is encrypted, but the server's identity is not verified. Verification with a root CA comes in a later release.

The two paths must not exist. Nextcloud's database driver (libpq) runs as www-data with HOME=/root. By default it opens /root/.postgresql/postgresql.crt, which www-data may not read. That fails the connection with could not open certificate file "/root/.postgresql/postgresql.crt": Permission denied, and on a server that requires SSL with FATAL: SSL required. If the file does not exist, libpq skips the client certificate. /nonexistent is the home directory of the nobody user and never exists; only root could create it, so the Nextcloud user cannot place a file there.

Your own extraEnv entries (from the profile or helm.values) are kept, with these rules for the libpq variables:

  • PGSSLMODE: kept only if it is verify-ca or verify-full (for example together with your own PGSSLROOTCERT); then the operator adds none. Any other value is replaced by require.
  • PGSSLCERT, PGSSLKEY, PGSSLROOTCERT: kept if you set them (for example for client certificates); the operator then does not add its own.
  • No variable appears twice in the rendered list.

The install check and the self-heal install (below) always use require and the nonexistent client certificate paths.

<instance>-nextcloud-db stores the sslmode actually used (keys db-sslmode and sslmode, always require) and the provider's own value (key db-provider-sslmode) when it sends one. The status timer adds these keys to Secrets written by v0.25.1.

First install and the install self-heal

If a first install fails part-way, the operator repairs it only if the database is provably empty (see Troubleshooting). A ManagedExternal instance has no PostgreSQL pod, so the operator checks from the Nextcloud container with PHP (pdo_pgsql, included in the Nextcloud image). It runs the same table count as for Managed instances.

  • The database password is sent on stdin. It never appears in the command line or in the script.
  • Host, port, database name, user and sslmode are validated (the same rules as the provider's Ready answer) and passed as separate arguments.
  • The check fails closed. Only a count of exactly 0 permits the install. Any error, non-zero exit or unreadable output blocks it, as for Managed instances.
  • The install command sets the three variables above itself. An install therefore works before the pod has picked up the new environment, and a missing setting cannot use up the heal attempts.

Upgrading an existing ManagedExternal instance to v0.25.2

The egress policy and SSL variables are added when the operator next renders the HelmRelease values: on create, on a spec change, or on a manual reconcile. To apply them now:

kubectl -n <namespace> annotate nci <instance> k8s.bnerd.com/reconcile="$(date +%s)" --overwrite

The install self-heal and the sslmode Secret backfill run on the status timer and need no action.

Not installed yet? The operator waits for the rollout (v0.25.3 and later)

The annotation re-renders the HelmRelease, and the Nextcloud Deployment then rolls. From v0.25.3 the install self-heal waits for that rollout itself: while the Deployment or the HelmRelease has not settled, the instance shows Installed=False, reason WaitingForRollout, and the operator neither probes the database nor installs. This is expected and clears on its own. Check the condition message if it lasts longer than the rollout (kubectl -n <namespace> rollout status deploy/<instance>-nextcloud).

The operator checks the rollout twice, once before the database probe and once right before occ maintenance:install, and runs both in the one pod it validated. Two limits remain. A rollout that starts while the install is already running (1-3 minutes) can still kill it and leave WedgedWithData; the repair below applies. And a rollout that never completes keeps the instance at WaitingForRollout without an alert, so check instances that stay there.

On v0.25.2 the self-heal did not wait (#8788). If you annotated an instance that was not installed yet, the status timer could start occ maintenance:install in the old pod, and the rollout then killed it part-way. The database is left with tables, and the instance stops at Installed=False, reason WedgedWithData. The operator correctly refuses to install over existing tables, so you must reset the database yourself. Upgrading to v0.25.3 does not repair such an instance.

To repair an instance that is WedgedWithData after this race: it never completed an install, so it holds no user data. Either ask the provider operator to empty its database, or delete the instance and create a new one.

Instances that are already installed are not affected. Neither are instances created on v0.25.2 or later: their first render already includes the egress policy and SSL variables, so no rollout follows the first install.

3. Switch NEW instances through a pool or profile

A NextcloudPool template or a NextcloudProfile that no existing instance uses takes the plain block:

spec:
  database:
    mode: ManagedExternal
    type: postgresql
    sizeClass: small

For a NextcloudProfile that existing instances already use, add mode (and sizeClass) to the existing database block and keep every Managed setting in place:

spec:
  defaults:
    database:
      mode: ManagedExternal      # added
      sizeClass: small           # added (optional)
      managed: true              # keep: existing tenants still read it
      type: postgresql
      deleteOnCleanup: true      # keep
      postgres:                  # keep: pgBouncer, resources, backups of existing tenants
        proxy:
          enabled: true
        backup:
          retention:
            full: 4

deleteOnCleanup in this block applies to every tenant on the profile: existing Managed tenants keep reading it for their Percona cluster, and a NEW ManagedExternal tenant reads it for its provider database (true sends the provider a soft-delete at teardown, see §5).

A profile without a database block (its tenants use SQLite) takes only mode (and sizeClass); existing SQLite tenants ignore the profile's database block entirely, so their Helm values stay exactly as before.

A profile's database mode applies only to instances without a database

Since v0.25.1 a database mode that comes only from the profile is create-time only:

  • Instances that do not have a database yet (new tenants, a first create) follow the profile and get a provider database. The profile's Managed-only keys (managed, postgres, connection fields) are ignored for them, so the block above does not trigger the "conflicts with managed: true" rejection. The same applies to a new instance whose own spec (for example a NextcloudPool template) sets mode: ManagedExternal while it uses this profile.
  • A new instance whose own spec declares a Managed database (managed: true + type: postgresql, for example from a Managed NextcloudPool template) is created as Managed with the profile's Managed settings: an own declaration always wins over a profile-only mode. DatabaseProfileModeIgnored=True says so (informational).
  • Instances that already have a database keep it. The operator reads the database in use from status.database (the Percona cluster, the provider externalId, an external DB, or an installed SQLite instance) and pins the mode to it. Upkeep (pgBouncer, resources, backup schedule and retention), the Helm values and the delete/retain decision read the kept Managed settings exactly as before the edit. The informational condition DatabaseProfileModeIgnored=True names the profile mode and the mode in use. There is no DatabaseModeChangeRejected, and the rest of every update (for example a version upgrade) is applied.
  • The same holds the other way round: a provider-backed instance whose profile drops mode: ManagedExternal keeps its provider database.

Moving an existing instance to another database mode is a data migration and is not supported yet (a future, explicit migration task).

Do not remove the Managed settings from a profile that is still in use

Existing Managed tenants keep reading managed: true, postgres.proxy, postgres.backup and deleteOnCleanup from the profile. Once the profile carries mode: ManagedExternal, the operator distinguishes a Managed setting the tenant never used (it runs exactly as before) from one that was removed from the profile (it is not touched):

Not in the profile Never used (runs as before) Removed (skipped and flagged)
managed: true (cannot be told apart) No pgBouncer, resources or backup upkeep; teardown does not delete the Percona cluster itself; a create retry is refused (retryably) and nothing is written.
postgres.proxy The live cluster runs no pgBouncer (replicas: 0 or no pgBouncer block). The live cluster runs pgBouncer (replicas > 0), or the cluster cannot be read: pgBouncer is left as it is (no scale change). A create retry keeps the live pgBouncer route in the DB Secret.
postgres.backup The backup config last applied (status.backupConfigLastAppliedSignature) is empty apart from an operator-central S3 target: either the one configured now, or one recorded as the operator default (source: operatorDefault, mode: alongside, the operator-rendered <name>-pgbackrest-s3 credentials, a cipher key outside the instance's namespace, no pathPrefix/retention). A later move of the central target therefore still reaches these tenants. Anything else, or no record: schedule and retention are left as they are (no reset to defaults) and the repo2 bootstrap is skipped. The <name>-pgbackrest-s3 credentials Secret is refreshed (so a key rotation arrives) only when the S3 target resolved now equals the target recorded in that signature. If they differ, for example because the profile removed its own postgres.backup.s3, the Secret is not touched either, because its keys must match the repo config that is left in place. The same applies under mode: replace (repo1).
deleteOnCleanup (cannot be told apart) Teardown keeps the Percona cluster (audit line reclaim=retained). If the instance's namespace is owned by it, the namespace is deleted at teardown and removes the cluster with it (audit line reclaim=namespace-deleted).

Two own overrides cannot be told apart from the operator default, because the recorded target looks the same: own access keys on the central bucket (credentialsFrom, which is not recorded), and a BYO credentialsSecret named exactly <name>-pgbackrest-s3. Such a tenant counts as "never used": the step runs and moves it to the central keys on the central bucket. A recorded usePathStyle: true counts as the default only while the central target sets it too.

Each "removed" case sets DatabaseProfileSettingsMissing=True, whose message names the settings, and posts one Warning event per change of that set (not per reconcile). Nothing is changed on the database. Add the settings back to the profile to clear the condition. A profile without mode is never checked this way: absent settings keep their v0.25.0 defaults.

When the conditions update. The operator evaluates both conditions only where it already reads the profile. That happens on create, and in the backup-config step of every on_update, every k8s.bnerd.com/reconcile force-reconcile and every status-timer tick (default every 30 s, TIMER_INSTANCE_STATUS_INTERVAL). The timer reaches that step only while the instance is not being deleted, its phase is not Failed and its HelmRelease status is readable. If the profile cannot be read, the conditions keep their last value. A mode set in the instance's own spec.database decides the database itself, and the next evaluation then clears DatabaseProfileModeIgnored.

Do not set managed: true on an instance's own spec or a pool template

mode: ManagedExternal together with managed: true (or host, port, name, credentialsSecret, user, password) on an instance's own spec.database, or in a NextcloudPool template (copied into the instance's own spec), is rejected at create, permanently (see above). Only a profile may carry both, for the reason above.

mode and sizeClass exist on NextcloudInstance, NextcloudPool (template) and NextcloudProfile. They are not on the logical Nextcloud resource: mode is a property of the pool and instance, and a value set there is pruned by the API server. This is a known limit.

Existing instances are untouched

Changing a profile or pool does not move existing instances. An instance that already has a database is never migrated. This includes an installed SQLite instance, whose data lives in SQLite. A mode that comes only from the profile is ignored for all of them (see DatabaseProfileModeIgnored above). Editing the instance's own spec.database so that its mode changes (for example Managed to ManagedExternal, or back) is refused, and the operator touches nothing. See DatabaseModeChangeRejected below. A mode in the instance's own spec.database counts as its own. That includes a mode the operator copied from the profile or pool template into the spec at create (every instance that is not GitOps-managed).

The refusal works in both directions. If an instance whose database comes from the provider is edited to another mode (by hand, or by a pool assignment that copies the logical Nextcloud resource's database block onto the instance), the operator keeps using the provider database. Reconciles and the status timer keep rendering from the provider's Secret, and DatabaseModeChangeRejected=True stays set until the edit is reverted.

A refused mode change drops the WHOLE edit

When a mode change is refused, the operator ignores the entire edit, including unrelated fields in the same change (for example spec.version). kopf still records the edit as handled. To proceed, revert the database mode (and related database fields) to the original, then check that your other changes took effect. If they did not, trigger a reconcile with the k8s.bnerd.com/reconcile annotation:

kubectl -n <namespace> annotate nci <instance> k8s.bnerd.com/reconcile="$(date +%s)" --overwrite

4. Conditions

Read them with:

kubectl -n <namespace> get nci <instance> -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'
kubectl -n <namespace> get nci <instance> -o jsonpath='{.status.database.provider}' | jq

status.database.provider records externalId (always the id the operator asked for), shard, phase, host, sizeClass (as created) and, during teardown, deleteRequested.

Condition Meaning What to do
DatabaseProvisioning=True The provider accepted the request but the database is not Ready yet (reason = provider phase). The operator retries every 15 s and writes no DB Secret yet. Wait. If it persists, ask the provider operator why the database is stuck.
DatabaseProviderUnavailable=True The provider is unreachable, not configured (or not https), the token/CA file is unreadable, it answered with a malformed response (for example invalid connection details) or with a response for a different database, or (after setup) it no longer knows the database. Retries every 30 s; the existing DB Secret is left alone. Check databaseProvider values, the two Secrets, network path and provider health. "malformed provider response" and "different database" are provider-side bugs. Clears automatically (Resolved).
DatabaseProviderRejected=True The provider answered with an error. 401/403/408/429 and a too-old provider are retried (fix the token, CA or provider). Any other rejection during create is final: phase Failed. Outside create it is retried every 5 min. Read the message (it carries the HTTP status and provider code). For a final create failure fix the cause and recreate the instance.
DatabaseProviderNotReady=True A previously ready database is reported in another phase by the provider (reason = phase). The DB Secret is left untouched. Treat as a provider-side incident; clears when the provider reports Ready.
DatabaseModeChangeRejected=True spec.database requests a different mode than the one the instance's database was set up with. The edit was ignored (all of it, see above); a provider-backed instance keeps using its provider database. Revert spec.database.mode (and related fields) to the original.
DatabaseProfileModeIgnored=True Informational: the instance's profile sets a database mode (reason ProfileModeIgnored; the message names the profile mode and the mode in use) that differs from the database this instance already has, or that its own spec overrides with a Managed declaration. The profile mode is ignored for this instance and nothing was changed; the rest of every update is applied. Updated as described under "When the conditions update". Nothing. Existing instances keep their database. Switching one is a future migration task. Clears (False) when the profile and the database in use agree again, or the instance's own spec sets the mode.
DatabaseProfileSettingsMissing=True The instance has a Managed (Percona) database and its profile sets mode: ManagedExternal, but the profile does not declare some Managed settings (reason ManagedSettingsMissing; the message names them: managed, postgres.proxy, postgres.backup, deleteOnCleanup). What they control is not touched (see the table in §3); one Warning event per change of the missing set. Nothing was changed on the database. Add the named settings to the profile next to mode (declare a never-used setting with its default). Clears (False) on the next evaluation.
DatabaseEgressNotRendered=True The provider's database host is not an IPv4 literal (reason HostNotIPv4), so the operator did not add the egress NetworkPolicy (it does not resolve DNS). Reason HostNotAllowed: the host is a loopback, unspecified, link-local, multicast, reserved or broadcast address (a provider error). Reason PortInvalid or ExtraManifestsUnsupported means the port in the DB Secret is invalid, or helm.values.extraManifests is neither a list nor a map. See "Network egress to the provider database". If the namespace denies egress by default, allow egress to the host and port named in the message. Clears (False) when a render includes the policy.
DatabaseSizeClassChangeIgnored=True Informational: spec.database.sizeClass differs from the class the ready database was created with. No provider call was made; the rest of the update was applied. Revert sizeClass, or ask the provider operator to resize. Clears when the values match again.

5. Deletion and teardown

Teardown follows the same rules as the managed PostgreSQL cluster:

Situation Provider database
Reclaim policy Retain Kept; an audit line is logged for manual reclamation.
spec.database.deleteOnCleanup: true DELETE is sent to the provider.
Namespace owned by the operator (will be deleted) DELETE is sent.
Otherwise (deleteOnCleanup: false, namespace preserved) Kept; the same audit line is logged.

The audit line has the same format as for a managed PostgreSQL cluster, with the provider id: PG reclaim audit: instance=<ns>/<name> provider-database=<externalId> reclaim=retained released-for-manual-reclamation (...). A kept provider database stays allocated on the provider and counts against its capacity.

The provider soft-deletes: a 202 means deletion was accepted and the provider keeps the data for its own grace period. The operator records status.database.provider.deleteRequested: true and does not send the request again. If the provider is unavailable or rejects the request, the instance's finalizer stays and the delete is retried (30 s unavailable, 60 s rejected); the instance is never released while the outcome is unknown. A 404 counts as "already gone".

Alert on stalled deletions

A ManagedExternal deletion that cannot reach the provider (provider down, wrong token, CA mismatch) holds the instance's finalizer and retries indefinitely. Nothing else reports it. Alert on any NextcloudInstance that has metadata.deletionTimestamp set and DatabaseProviderUnavailable=True or DatabaseProviderRejected=True for longer than, for example, 15 minutes. To find them by hand:

kubectl get nci -A -o json | jq -r '.items[] | select(.metadata.deletionTimestamp != null)
  | select(any(.status.conditions[]?; (.type == "DatabaseProviderUnavailable" or .type == "DatabaseProviderRejected") and .status == "True"))
  | "\(.metadata.namespace)/\(.metadata.name)"'

Runbook: deletion stuck because the provider is not configured

If the instance has no provider database recorded (status.database.provider.externalId is empty) and the operator has no provider configured, no request can ever have reached a provider. Teardown skips the provider step with a warning and an audit line (reclaim=skipped provider-not-configured) and completes.

If a provider database is recorded but the operator has no provider configured (empty databaseProvider.url, for example after a values rollback), teardown reports DatabaseProviderUnavailable ("not configured") and retries forever, because that database may still hold data.

  1. Preferred: restore the databaseProvider configuration; the next retry completes.
  2. If the provider is permanently gone, confirm no provider database exists for the instance. The id is the instance UID:
    kubectl -n <namespace> get nci <instance> -o jsonpath='{.metadata.uid}{"\n"}{.status.database.provider}{"\n"}'
    
    Ask the provider operator (or query the provider API with the same bearer token) whether a database with that id exists. A 404 means there is nothing to clean up.
  3. Only then release the finalizer manually:
    kubectl -n <namespace> patch nci <instance> --type=merge -p '{"metadata":{"finalizers":null}}'
    
    Do this only after step 2: removing the finalizer while a provider database exists orphans it.

6. Rollout order

  1. Apply the CRDs first, then roll the operator image. With the old CRD schema the API server prunes status.database.provider, and the operator then loses the marker that tells it which database belongs to an instance.
  2. Set databaseProvider and create its two Secrets.
  3. Switch a profile or pool template for NEW instances.
  4. After upgrading to v0.25.2, trigger a reconcile on existing ManagedExternal instances (k8s.bnerd.com/reconcile annotation) so their HelmRelease gets the egress policy and SSL variables. On v0.25.2 an instance that is not installed yet must finish the Deployment rollout before the install runs; from v0.25.3 the operator waits for it itself (see the note in Upgrading an existing ManagedExternal instance to v0.25.2).

See also