The module lifecycle stage: Preview

The module has requirements for installation

Connecting to a database

This example uses Postgres test, database testdb and Secret test-test-rw-creds from the quick start. Connecting requires psql with network access to the in-cluster service.

Read connection settings from the Secret and open a connection:

PGHOST=$(d8 k -n postgres get secret test-test-rw-creds -o jsonpath='{.data.host}' | base64 --decode)
export PGHOST="${PGHOST}.postgres.svc"
export PGUSER=$(d8 k -n postgres get secret test-test-rw-creds -o jsonpath='{.data.username}' | base64 --decode)
export PGPASSWORD=$(d8 k -n postgres get secret test-test-rw-creds -o jsonpath='{.data.password}' | base64 --decode)
psql \
  -d testdb \
  -v ON_ERROR_STOP=1 \
  -c 'SELECT current_database(), current_user;'
unset PGPASSWORD

A successful connection returns database testdb and user test-rw. An application in the same namespace can consume Secret values through its container’s env field:

env:
  - name: PGHOST
    valueFrom:
      secretKeyRef:
        name: test-test-rw-creds
        key: host
  - name: PGUSER
    valueFrom:
      secretKeyRef:
        name: test-test-rw-creds
        key: username
  - name: PGPASSWORD
    valueFrom:
      secretKeyRef:
        name: test-test-rw-creds
        key: password
  - name: PGDATABASE
    value: testdb

Specify the database separately; a generated Secret does not contain a connection string for each database.

Creating a database and user through SQL

To create SQL objects through a client, create a user with Admin privileges on PostgreSQL 16 or later. Use an existing Postgres test in namespace postgres. Save the manifest as user-admin.yaml:

User manifest with Admin privileges

apiVersion: managed-services.deckhouse.io/v1alpha2
kind: PostgresUser
metadata:
  name: test-admin
  namespace: postgres
spec:
  postgres: test
  userName: business_admin
  privileges: Admin
  storeCredsToSecret: test-admin-creds

Apply the manifest and wait for reconciliation:

d8 k apply -f user-admin.yaml
d8 k wait postgresuser/test-admin \
  --namespace postgres \
  --for=condition=Synced \
  --timeout=5m

Admin has CREATEDB and CREATEROLE, but is not a superuser. Omit inRoles entirely for Admin, including an empty list. Connect using the generated credentials:

PGHOST=$(d8 k -n postgres get secret test-admin-creds -o jsonpath='{.data.host}' | base64 --decode)
export PGHOST="${PGHOST}.postgres.svc"
export PGUSER=$(d8 k -n postgres get secret test-admin-creds -o jsonpath='{.data.username}' | base64 --decode)
export PGPASSWORD=$(d8 k -n postgres get secret test-admin-creds -o jsonpath='{.data.password}' | base64 --decode)
psql \
  -d postgres \
  -v ON_ERROR_STOP=1 \
  -c 'CREATE DATABASE native_db;'
psql \
  -d postgres \
  -v ON_ERROR_STOP=1 \
  -c 'CREATE USER native_user LOGIN;'
unset PGPASSWORD

native_user has no password yet; adoption below supplies its password source. Inventory publishes both SQL objects as Unmanaged. The database belongs to the SQL role that ran CREATE DATABASE. Admin does not automatically gain access to all existing databases or control over other users’ roles.

Adopting a database

This example limits connections to the existing native_db database in service test. Create it through SQL as in the previous example, then find its inventory object:

d8 k -n postgres get postgresdatabases -o custom-columns='RESOURCE:.metadata.name,POSTGRES:.status.postgres,DATABASE:.status.databaseName,PHASE:.status.phase'

Replace <DATABASE_RESOURCE_NAME> with its resource name. This patch declares a connection limit and deletion policy; the webhook fills the immutable postgres and databaseName from status:

DB_RESOURCE='<DATABASE_RESOURCE_NAME>'
d8 k patch postgresdatabase "$DB_RESOURCE" \
  --namespace postgres \
  --type=merge \
  --patch '{"spec":{"connectionLimit":100,"retentionPolicy":"Retain"}}'
d8 k wait "postgresdatabase/$DB_RESOURCE" \
  --namespace postgres \
  --for=condition=Synced \
  --timeout=5m
d8 k -n postgres get postgresdatabase "$DB_RESOURCE" -o yaml

This example leaves the owner and extensions unmanaged. A native SQL change to CONNECTION LIMIT is reverted to 100. To stop managing that field, remove it from spec ("connectionLimit":null in a merge patch); its last applied value remains in PostgreSQL.

For GitOps (managing declarations from Git), save a manifest with the same metadata.name, namespace and desired spec. Do not copy status, uid, resourceVersion or managedFields into Git. After Retain or deletion of an unmanaged resource, inspect inventory again before adoption.

<DATABASE_RESOURCE_NAME> is the discovered PostgresDatabase name.

Adopting a user

This example binds the existing SQL user native_user in service test to a Secret password source. Create the user through SQL as in the Admin example, or use an existing name.

Create native-user-password in the postgres namespace through your normal secret management process. It must contain a plaintext password under the password key. For example, create it from a local password file (replace the path; the file must contain the exact password without a trailing newline):

d8 k -n postgres create secret generic native-user-password --from-file=password="<PASSWORD_FILE>"

To preserve an existing user’s password, supply that same password. A different password will be applied to PostgreSQL.

Find the user in inventory:

d8 k -n postgres get postgresusers -o custom-columns='RESOURCE:.metadata.name,POSTGRES:.status.postgres,USER:.status.userName,PHASE:.status.phase'

Find test/native_user and substitute the inventory resource name:

USER_RESOURCE='<USER_RESOURCE_NAME>'
d8 k patch postgresuser "$USER_RESOURCE" \
  --namespace postgres \
  --type=merge \
  --patch '{"spec":{"passwordSecretRef":{"name":"native-user-password","key":"password"},"privileges":"Standard","inRoles":["rw"]}}'
d8 k wait "postgresuser/$USER_RESOURCE" \
  --namespace postgres \
  --for=condition=Synced \
  --timeout=5m

This example applies the Secret’s password, removes CREATEDB/CREATEROLE and enforces direct memberships of [rw]. Omit inRoles to leave memberships unmanaged. The rw role currently has global PostgreSQL privileges, not privileges limited to native_db.

Instead of an external Secret, choose storeCredsToSecret with a new, unused Secret name or hashedPassword with a ready PostgreSQL verifier. Exactly one source is required. When switching sources, remove the old field and set the new one in a single update; set the matching passwordEncryption for a verifier. hashedPassword is not a plaintext application password and does not produce a Secret.

<USER_RESOURCE_NAME> is the discovered PostgresUser name; <PASSWORD_FILE> is the password file path.

Configuring database extensions

Create database extension_demo with pgcrypto in the public schema in an existing Postgres test. Save the manifest as database-extensions.yaml:

Database manifest with pgcrypto

apiVersion: managed-services.deckhouse.io/v1alpha2
kind: PostgresDatabase
metadata:
  name: test-extension-demo
  namespace: postgres
spec:
  postgres: test
  databaseName: extension_demo
  retentionPolicy: Retain
  connectionLimit: 100
  extensions:
  - name: pgcrypto
    schema: public

Apply the manifest and check the state:

d8 k apply -f database-extensions.yaml
d8 k wait postgresdatabase/test-extension-demo \
  --namespace postgres \
  --for=condition=Synced \
  --timeout=5m
d8 k -n postgres get postgresdatabase test-extension-demo -o yaml

Removing an entry drops the extension with CASCADE, including dependent objects. extensions: [] removes all unprotected extensions; omitting the field stops managing the list. Missing plpgsql, pg_stat_statements and pgaudit entries do not trigger removal. Schemas are not created automatically; extension versions are observed only in status.

On success, the database has Synced=True and status.observedState.extensions includes pgcrypto with its schema and version.

Rotating a password

To change the password of test-test-rw from the quick start, delete its generated Secret:

d8 k -n postgres delete secret test-test-rw-creds
d8 k -n postgres get postgresuser test-test-rw -o yaml
d8 k -n postgres get secret test-test-rw-creds -o custom-columns='NAME:.metadata.name,UID:.metadata.uid,VERSION:.metadata.resourceVersion'

The Secret is recreated asynchronously. Wait until the user’s status.appliedPassword.secretUID and secretResourceVersion match the new Secret and Synced is True for the current resource generation. Immediately after deletion, the previous Synced=True can still reflect the old state. Status never exposes the password value.

The application must reload the password and establish new connections. If the Secret is injected as environment variables, restart the application Pod; a running process does not receive updated values automatically. Rotation does not terminate existing SQL sessions.

Releasing management

To preserve a managed database and user in namespace postgres and return control to SQL clients, clear their declarations:

DB_RESOURCE='<DATABASE_RESOURCE_NAME>'
USER_RESOURCE='<USER_RESOURCE_NAME>'
d8 k patch postgresdatabase "$DB_RESOURCE" \
  --namespace postgres \
  --type=merge \
  --patch '{"spec":null}'
d8 k patch postgresuser "$USER_RESOURCE" \
  --namespace postgres \
  --type=merge \
  --patch '{"spec":null}'

Wait for Unmanaged. This example preserves the user’s external Secret. A generated Secret owned by PostgresUser would be removed. With GitOps, also clear the managed spec in your declaration source, otherwise its next sync will enable management again.

Replace <DATABASE_RESOURCE_NAME> and <USER_RESOURCE_NAME> with managed object names in namespace postgres.