> For the complete documentation index, see [llms.txt](https://docs.cennso.com/cennso/cennso-db/latest/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/cennso/cennso-db/latest/operation-guides/cennso-postgresql-certificates.md).

# Manage TLS certificates

Each PostgreSQL cluster uses TLS certificates managed by the Cennso PostgreSQL Operator by default. The database operator creates a [Certificate](https://cert-manager.io/docs/usage/certificate/) Custom Resource managed by [cert-manager](https://cert-manager.io/) for:

- CA
- PostgreSQL server and every PostgreSQL Pod
- Replication user 
- PgBouncer Pods 

These certificates are valid for one year by default, and cert-manager renews them `30` days before they expire. When the certificates are renewed, the PostgreSQL and PgBouncer Pods are not restarted.

This document describes everything you need to know about TLS certificates when operating your PostgreSQL cluster:

- [How to check the TLS certificates](#check-the-tls-certificates) of an existing PostgreSQL cluster
- [How to change validity of the TLS certificates](#change-the-validity-of-the-tls-certificates)
- [How to use your own TLS certificates on a fresh PostgreSQL cluster](#use-your-own-tls-certificates) instead of the certificates managed by the database operator
- [How to switch a running PostgreSQL cluster](#switch-a-running-postgresql-cluster-to-your-own-tls-certificates) to your own TLS certificates
- [How to renew your own TLS certificates](#renew-your-own-tls-certificates)

For more information about the configuration options, see the [TLS certificates configuration](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-instance.md#tls-certificates-configuration) section of the Cennso PostgreSQL Instance document.

## Check the TLS certificates

To check the TLS certificates of your PostgreSQL cluster:

1. List the `Certificate` Custom Resources in the namespace of the PostgreSQL cluster:

   ```bash
   kubectl get certificates -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} \
     -o custom-columns='NAME:.metadata.name,DURATION:.spec.duration,READY:.status.conditions[?(@.type=="Ready")].status,NOT_AFTER:.status.notAfter,RENEWAL:.status.renewalTime'
   ```

   The fields have the following meaining:

   - `DURATION` column shows the configured validity
   - `NOT_AFTER` column shows when the issued certificate expires
   - `RENEWAL` column shows when cert-manager renews it

2. Check the issued certificate in the Kubernetes Secret. For example, for the PostgreSQL server certificate:

   ```bash
   kubectl get secret {POSTGRESQL-INSTANCE-NAME}-cluster-cert -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} \
     -o jsonpath='{.data.tls\.crt}' | base64 -d | openssl x509 -noout -subject -dates
   ```

The database operator stores the certificates in the following Kubernetes Secrets, where `{POSTGRESQL-INSTANCE-NAME}` is the value of the **metadata.name** from the `PostgreSQLInstance`:

| Kubernetes Secret | Certificate |
|---|---|
| `{POSTGRESQL-INSTANCE-NAME}-cluster-ca-cert` | CA |
| `{POSTGRESQL-INSTANCE-NAME}-cluster-cert` | PostgreSQL server |
| `{POSTGRESQL-INSTANCE-NAME}-replication-cert` | Client certificate of the replication user |
| `{POSTGRESQL-INSTANCE-NAME}-pgbouncer-frontend-tls` | PgBouncer |
| `{POSTGRESQL-INSTANCE-NAME}-{INSTANCE-SET-NAME}-{SUFFIX}-certs` | One per PostgreSQL Pod |

## Change the validity of the TLS certificates

> [!NOTE]
> The Kubernetes Secrets with the certificates are not deleted together with the `PostgreSQLInstance`. If you delete the `PostgreSQLInstance` and deploy it again with the same **metadata.name** in the same namespace, the database operator reuses the existing certificates with their original validity. Delete the Kubernetes Secrets listed above before the new deployment to get new certificates.

To change the validity of the TLS certificates managed by the database operator:

1. Open the manifest (for example `cennso-postgresql-instance.yaml`) with the `PostgreSQLInstance` Custom Resource which you used to deploy the PostgreSQL cluster.

2. Set the validity of the certificates using the **spec.tls** configuration options. For example:

   ```yaml
   spec:
     tls:
       certValidityDuration: 2160h # 90 days
       caValidityDuration: 17520h # 2 years
   ```

   The **spec.tls.certValidityDuration** configuration option defines the validity of the PostgreSQL server, replication, PgBouncer, and PostgreSQL Pod certificates. The **spec.tls.caValidityDuration** configuration option defines the validity of the CA certificate.
   Both values must be longer than `720h`, because cert-manager renews the certificates `30` days before they expire.

3. Apply the manifest to the Kubernetes cluster where your database cluster is deployed using the following command:

   ```bash
   kubectl apply -f cennso-postgresql-instance.yaml -n {NAMESPACE}
   ```

4. Check that the `Certificate` Custom Resources in the target cluster have the new validity:

   ```bash
   kubectl get certificates -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} -o custom-columns='NAME:.metadata.name,DURATION:.spec.duration'
   ```

> [!IMPORTANT]
> cert-manager does not reissue the certificates that are still valid. The new validity applies when a certificate is renewed or issued for the first time, so the `NOT_AFTER` column of the existing certificates does not change.

If you want to apply the new validity immediately, delete the Kubernetes Secrets with the certificates. cert-manager issues the new certificates within seconds. To do this, perform the following steps:

1. Delete the Kubernetes Secrets of all the certificates together using the commands:

   ```bash
   kubectl delete secret -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} \
     {POSTGRESQL-INSTANCE-NAME}-cluster-ca-cert                 \
     {POSTGRESQL-INSTANCE-NAME}-cluster-cert                    \
     {POSTGRESQL-INSTANCE-NAME}-replication-cert                \
     {POSTGRESQL-INSTANCE-NAME}-pgbouncer-frontend-tls

   kubectl delete secret -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} \
     $(kubectl get secrets -n {NAMESPACE-WITH-POSTGRESQL-CLUSTER} -o name | grep "^secret/{POSTGRESQL-INSTANCE-NAME}-.*-certs$" | cut -d/ -f2)
   ```

2. Check that the certificates are issued again with the new validity, as described in the [Check the TLS certificates](#check-the-tls-certificates) section.

## Use your own TLS certificates

> [!NOTE]
> This section describes how to deploy a new PostgreSQL cluster with your own TLS certificates. To switch a PostgreSQL cluster that already runs with the certificates managed by the database operator, read the [Switch a running PostgreSQL cluster to your own TLS certificates](#switch-a-running-postgresql-cluster-to-your-own-tls-certificates) section.
>
> After you switch to your own TLS certificates, the clients that verify the server certificate must trust your CA instead of the CA managed by the database operator. The `ca.crt` key of the server secret contains the CA certificate.
>
>
> With your own TLS certificates, the database operator still creates the `{POSTGRESQL-INSTANCE-NAME}-cluster-ca-cert` Kubernetes Secret with its own CA and the `{POSTGRESQL-INSTANCE-NAME}-{INSTANCE-SET-NAME}-{SUFFIX}-certs` Kubernetes Secret for every PostgreSQL Pod. These Kubernetes Secrets contain the certificates of the Patroni REST API and pgBackRest, which are used only between the Pods of the PostgreSQL cluster. The client connections to PostgreSQL and PgBouncer use your certificates.

The certificates managed by the database operator are issued by a self-signed CA created for each PostgreSQL cluster. They contain only the DNS names of the Services within the Kubernetes cluster. Use your own TLS certificates instead when you need one of the following:

- Certificates issued by your own CA, for example a company CA, so that the clients already trust the PostgreSQL cluster.
- Certificates with additional DNS names, for example when PgBouncer is exposed through a LoadBalancer and the clients connect to it with the [`verify-full`](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBQ-SSL-CERTIFICATES) SSL mode under an external DNS name.

You provide your own TLS certificates in two Kubernetes Secrets in the namespace of the PostgreSQL cluster. Both certificates must be issued by the same CA, and each Kubernetes Secret must contain the `ca.crt`, `tls.crt`, and `tls.key` keys:

- The server secret with the certificate used by the PostgreSQL server and PgBouncer. PgBouncer connects to the PostgreSQL server with the `verify-full` SSL mode, so the certificate must contain the DNS names of the primary Service in its Subject Alternative Names. Clients that use the `verify-full` SSL mode also need the DNS names of the Service they connect to. Use the following Subject Alternative Names, where `{NAMESPACE-WITH-POSTGRESQL-CLUSTER}` is the namespace of the PostgreSQL cluster:

  - `{POSTGRESQL-INSTANCE-NAME}-primary`
  - `{POSTGRESQL-INSTANCE-NAME}-primary.{NAMESPACE-WITH-POSTGRESQL-CLUSTER}`
  - `{POSTGRESQL-INSTANCE-NAME}-primary.{NAMESPACE-WITH-POSTGRESQL-CLUSTER}.svc`
  - `{POSTGRESQL-INSTANCE-NAME}-primary.{NAMESPACE-WITH-POSTGRESQL-CLUSTER}.svc.cluster.local`
  - The same four names for the `{POSTGRESQL-INSTANCE-NAME}-replicas` Service
  - The same four names for the `{POSTGRESQL-INSTANCE-NAME}-pgbouncer` Service
  - Any external DNS name under which the clients connect to the PostgreSQL cluster

- The replication secret with the client certificate of the replication user. The common name of this certificate must be `_crunchyrepl`.

The following steps show you how to create the certificates with [OpenSSL](https://www.openssl.org/) `3.0` or later. If a company CA signs your certificates, skip the first step and send the signing requests from the second and third steps to the CA instead of signing them yourself.

The commands use the name and the namespace of the PostgreSQL cluster from the following shell variables. Set them before you start:

```bash
export POSTGRESQL_INSTANCE_NAME={POSTGRESQL-INSTANCE-NAME}
export NAMESPACE_WITH_POSTGRESQL_CLUSTER={NAMESPACE-WITH-POSTGRESQL-CLUSTER}
```

To deploy a new PostgreSQL cluster with your own TLS certificates:

1. Create the CA key and the self-signed CA certificate:

   ```bash
   openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
     -subj "/CN=${POSTGRESQL_INSTANCE_NAME}-custom-ca" -days 3650            \
     -keyout ca.key -out ca.crt
   ```

2. Create the server key, the signing request with the Subject Alternative Names, and sign it with the CA:

   ```bash
   SANS=""
   for service in primary replicas pgbouncer; do
     host="${POSTGRESQL_INSTANCE_NAME}-${service}"
     SANS="${SANS}DNS:${host},DNS:${host}.${NAMESPACE_WITH_POSTGRESQL_CLUSTER},DNS:${host}.${NAMESPACE_WITH_POSTGRESQL_CLUSTER}.svc,DNS:${host}.${NAMESPACE_WITH_POSTGRESQL_CLUSTER}.svc.cluster.local,"
   done

   SANS="${SANS%,}"
   openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes  \
     -subj "/CN=${POSTGRESQL_INSTANCE_NAME}-primary"                         \
     -addext "keyUsage=digitalSignature,keyEncipherment"                     \
     -addext "extendedKeyUsage=serverAuth,clientAuth"                        \
     -addext "subjectAltName=${SANS}"                                        \
     -keyout server.key -out server.csr

   openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
     -days 1095 -copy_extensions copy -out server.crt
   ```

   To add an external DNS name, append `,DNS:{EXTERNAL-DNS-NAME}` to the `SANS` variable before you create the signing request.

3. Create the replication key, the signing request with the `_crunchyrepl` common name, and sign it with the CA:

   ```bash
   openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
     -subj "/CN=_crunchyrepl"                                               \
     -addext "keyUsage=digitalSignature,keyEncipherment"                    \
     -addext "extendedKeyUsage=clientAuth"                                  \
     -keyout replication.key -out replication.csr

   openssl x509 -req -in replication.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
     -days 1095 -copy_extensions copy -out replication.crt
   ```

4. Check the certificates:

   ```bash
   openssl verify -CAfile ca.crt server.crt replication.crt
   openssl x509 -in server.crt -noout -subject -ext subjectAltName
   openssl x509 -in replication.crt -noout -subject
   ```

5. Create the Kubernetes Secrets from the certificates in the target cluster:

   ```bash
   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca.crt --from-file=tls.crt=server.crt --from-file=tls.key=server.key

   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-replication-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca.crt --from-file=tls.crt=replication.crt --from-file=tls.key=replication.key
   ```

6. Set the references to the Kubernetes Secrets in the manifest (for example `cennso-postgresql-instance.yaml`) with the `PostgreSQLInstance` Custom Resource. Do not set the **spec.tls** configuration options, because they cannot be combined with **spec.tlsSecretName**:

   ```yaml
   spec:
     tlsSecretName: {POSTGRESQL-INSTANCE-NAME}-custom-tls
     replicationTLSSecretName: {POSTGRESQL-INSTANCE-NAME}-custom-replication-tls
   ```

7. Deploy the PostgreSQL cluster as described in the [Deploy Cennso PostgreSQL Instance](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql.md#deploy-cennso-postgresql-instance) section of the deployment guide.

8. Check that the PostgreSQL server uses your certificate. The following commands forward a local port to the primary PostgreSQL Pod, print the certificate of the PostgreSQL server, and stop the port forwarding:

   ```bash
   PRIMARY_POD=$(kubectl get pods -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"                                                    \
     -l "postgres-operator.crunchydata.com/cluster=${POSTGRESQL_INSTANCE_NAME},postgres-operator.crunchydata.com/role=primary" \
     -o jsonpath='{.items[0].metadata.name}')
   kubectl port-forward -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" "pod/${PRIMARY_POD}" 15432:5432 >/dev/null &
   PORT_FORWARD_PID=$!
   sleep 2
   timeout 10 openssl s_client -starttls postgres -connect localhost:15432 </dev/null 2>/dev/null \
     | openssl x509 -noout -subject -issuer -dates
   kill "${PORT_FORWARD_PID}"
   ```

   The `issuer` line shows your CA, and the `notBefore` and `notAfter` lines show the validity of your server certificate.

> [!NOTE]
> When you create a `PostgreSQLBackup` for this PostgreSQL cluster, set its **spec.replicationSecretName** to `{POSTGRESQL-INSTANCE-NAME}-custom-replication-tls`. Without it, the backup job fails, because the Kubernetes Secret with the replication certificate managed by the database operator does not exist.

## Switch a running PostgreSQL cluster to your own TLS certificates

When you set **spec.tlsSecretName** on a running PostgreSQL cluster, the database operator recreates the PostgreSQL and PgBouncer Pods one by one and performs a switchover of the primary. The connections to the PostgreSQL cluster are interrupted for a few seconds during the switchover.

During this update, the Pods with the certificates managed by the database operator and the Pods with your own certificates must trust each other, otherwise the replication between them fails and the update stops. Therefore, you sign the first server and replication certificates with the CA of the database operator and put both CAs into the `ca.crt` key of your Kubernetes Secrets. After the update, you replace the certificates with the certificates signed by your own CA.

The commands use the shell variables from the [Use your own TLS certificates](#use-your-own-tls-certificates) section. Make sure you set them before you start.

To switch a running PostgreSQL cluster to your own TLS certificates:

1. Create your CA key and the self-signed CA certificate, save the CA certificate and key of the database operator, and combine both CA certificates into one file:

   ```bash
   openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
     -subj "/CN=${POSTGRESQL_INSTANCE_NAME}-custom-ca" -days 3650            \
     -keyout ca.key -out ca.crt

   kubectl get secret "${POSTGRESQL_INSTANCE_NAME}-cluster-ca-cert" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     -o jsonpath='{.data.tls\.crt}' | base64 -d > operator-ca.crt

   kubectl get secret "${POSTGRESQL_INSTANCE_NAME}-cluster-ca-cert" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     -o jsonpath='{.data.tls\.key}' | base64 -d > operator-ca.key

   cat operator-ca.crt ca.crt > ca-bundle.crt
   ```

2. Create the server and replication keys and signing requests, as described in steps 2 and 3 of the [Use your own TLS certificates](#use-your-own-tls-certificates) section, but sign them with the CA of the database operator:

   ```bash
   openssl x509 -req -in server.csr -CA operator-ca.crt -CAkey operator-ca.key -CAcreateserial \
     -days 1095 -copy_extensions copy -out server.crt

   openssl x509 -req -in replication.csr -CA operator-ca.crt -CAkey operator-ca.key -CAcreateserial \
     -days 1095 -copy_extensions copy -out replication.crt
   ```

3. Check that both certificates verify against the CA of the database operator:

   ```bash
   openssl verify -CAfile operator-ca.crt server.crt replication.crt
   ```

4. Create the Kubernetes Secrets with both CAs in the `ca.crt` key:

   ```bash
   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca-bundle.crt --from-file=tls.crt=server.crt --from-file=tls.key=server.key                 \
     --dry-run=client -o yaml | kubectl apply -f -

   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-replication-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca-bundle.crt --from-file=tls.crt=replication.crt --from-file=tls.key=replication.key                   \
     --dry-run=client -o yaml | kubectl apply -f -
   ```

5. Open the manifest (for example `cennso-postgresql-instance.yaml`) with the `PostgreSQLInstance` Custom Resource which you used to deploy the PostgreSQL cluster, and set the references to the Kubernetes Secrets. Remove the **spec.tls** configuration options if you set them, because they cannot be combined with **spec.tlsSecretName**:

   ```yaml
   spec:
     tlsSecretName: {POSTGRESQL-INSTANCE-NAME}-custom-tls
     replicationTLSSecretName: {POSTGRESQL-INSTANCE-NAME}-custom-replication-tls
   ```

   Apply the manifest to the Kubernetes cluster where your database cluster is deployed:

   ```bash
   kubectl apply -f cennso-postgresql-instance.yaml -n {NAMESPACE}
   ```

6. Delete the `Certificate` Custom Resource and the Kubernetes Secret of every PostgreSQL Pod. Without this step, the database operator cannot update the PostgreSQL Pods. The database operator creates the Kubernetes Secrets again within seconds, and the PostgreSQL Pods keep running:

   ```bash
   for instance in $(kubectl get statefulsets -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"                                           \
       -l "postgres-operator.crunchydata.com/cluster=${POSTGRESQL_INSTANCE_NAME},postgres-operator.crunchydata.com/data=postgres" \
       -o jsonpath='{.items[*].metadata.name}'); do
     kubectl delete certificate "${instance}-cert" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"
     kubectl delete secret "${instance}-certs" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"
   done
   ```

7. Wait until the database operator has recreated all the PostgreSQL and PgBouncer Pods. The update is finished when every PostgreSQL Pod mounts your Kubernetes Secrets:

   ```bash
   kubectl get pods -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"                                                                              \
     -l "postgres-operator.crunchydata.com/cluster=${POSTGRESQL_INSTANCE_NAME},postgres-operator.crunchydata.com/data=postgres"            \
     -o jsonpath='{range .items[*]}{.metadata.name}: {.spec.volumes[?(@.name=="cert-volume")].projected.sources[*].secret.name}{"\n"}{end}'
   ```

   For example, for the `postgresql-instance` cluster:

   ```text
   postgresql-instance-instance1-8pr6-0: postgresql-instance-custom-tls postgresql-instance-custom-replication-tls
   postgresql-instance-instance1-qtww-0: postgresql-instance-custom-tls postgresql-instance-custom-replication-tls
   ```

8. If a `PostgreSQLBackup` exists for this PostgreSQL cluster, set its **spec.replicationSecretName** to the name of your replication secret and apply it. The backup job connects to the read replica with the replication certificate, and after the next step, the Kubernetes Secret it uses by default no longer exists:

   ```yaml
   spec:
     replicationSecretName: {POSTGRESQL-INSTANCE-NAME}-custom-replication-tls
   ```

9. Delete the `Certificate` Custom Resources and the Kubernetes Secrets of the certificates managed by the database operator, which are no longer used. Do not delete the `{POSTGRESQL-INSTANCE-NAME}-cluster-ca-cert` Kubernetes Secret, because the database operator still uses it:

   ```bash
   kubectl delete certificate -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     "${POSTGRESQL_INSTANCE_NAME}-cluster-cert"                         \
     "${POSTGRESQL_INSTANCE_NAME}-replication-cert"                     \
     "${POSTGRESQL_INSTANCE_NAME}-pgbouncer-cert"
   kubectl delete secret -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"      \
     "${POSTGRESQL_INSTANCE_NAME}-cluster-cert"                         \
     "${POSTGRESQL_INSTANCE_NAME}-replication-cert"                     \
     "${POSTGRESQL_INSTANCE_NAME}-pgbouncer-frontend-tls"
   ```

10. Check that the PostgreSQL server uses your server certificate, as described in step 8 of the [Use your own TLS certificates](#use-your-own-tls-certificates) section. The `subject` line shows `CN={POSTGRESQL-INSTANCE-NAME}-primary`, and the `issuer` line still shows the CA of the database operator.

11. Replace the certificates with the certificates signed by your own CA, as described in steps 4 to 7 of the [Renew the certificates with a new CA](#renew-the-certificates-with-a-new-ca) section. The `ca.crt` and `ca.key` files are your CA, and the `ca-bundle.crt` file is already in the Kubernetes Secrets. After the last step, the PostgreSQL cluster uses only your CA.

## Renew your own TLS certificates

The database operator does not renew your own TLS certificates. Before they expire, create new certificates and replace the data of the Kubernetes Secrets. The PostgreSQL and PgBouncer Pods load the new certificates within about two minutes without a restart.

How you renew the certificates depends on whether you still have the key of the CA that signed them. Keep the CA key in a safe place, or let your company CA sign the certificates, so that every renewal uses the same CA.

### Renew the certificates with the same CA

To renew the certificates with the CA that signed them:

1. Create the new server and replication certificates with the same `ca.crt` and `ca.key` files, as described in steps 2 to 4 of the [Use your own TLS certificates](#use-your-own-tls-certificates) section.

2. Replace the data of the Kubernetes Secrets:

   ```bash
   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca.crt --from-file=tls.crt=server.crt --from-file=tls.key=server.key                        \
     --dry-run=client -o yaml | kubectl apply -f -
   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-replication-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca.crt --from-file=tls.crt=replication.crt --from-file=tls.key=replication.key                          \
     --dry-run=client -o yaml | kubectl apply -f -
   ```

3. After about two minutes, check that the PostgreSQL server uses the new certificate, as described in step 8 of the [Use your own TLS certificates](#use-your-own-tls-certificates) section. The `notAfter` date shows the expiry of the new certificate.

### Renew the certificates with a new CA

If you no longer have the CA key, or you want to replace the CA, sign the new certificates with a new CA. The PostgreSQL Pods load the two Kubernetes Secrets at slightly different times, so for a short time some connections use certificates from the old CA and others from the new CA. To keep the replication and the client connections working, the PostgreSQL cluster trusts both CAs while you replace the certificates, and you remove the old CA at the end.

To renew the certificates with a new CA:

1. Save the current CA certificate from the server secret. You need only the certificate, not its key:

   ```bash
   kubectl get secret "${POSTGRESQL_INSTANCE_NAME}-custom-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     -o jsonpath='{.data.ca\.crt}' | base64 -d > old-ca.crt
   ```

2. Create the new CA. Give it a different common name than the current CA, so that you can tell the certificates apart. Then combine both CA certificates into one file:

   ```bash
   openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
     -subj "/CN=${POSTGRESQL_INSTANCE_NAME}-ca-$(date +%Y%m%d)" -days 3650   \
     -keyout ca.key -out ca.crt
   cat old-ca.crt ca.crt > ca-bundle.crt
   ```

3. Add the new CA to the trusted CAs of the PostgreSQL cluster. This command changes only the `ca.crt` key of both Kubernetes Secrets, the certificates stay the same:

   ```bash
   for secret in custom-tls custom-replication-tls; do
     kubectl patch secret "${POSTGRESQL_INSTANCE_NAME}-${secret}" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
       --type merge -p "{\"data\":{\"ca.crt\":\"$(base64 < ca-bundle.crt | tr -d '\n')\"}}"
   done
   ```

   After about two minutes, check that the PostgreSQL Pods trust both CAs. The command prints `2` for each Pod:

   ```bash
   for pod in $(kubectl get pods -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"                                                        \
       -l "postgres-operator.crunchydata.com/cluster=${POSTGRESQL_INSTANCE_NAME},postgres-operator.crunchydata.com/data=postgres" \
       -o jsonpath='{.items[*].metadata.name}'); do
     kubectl exec -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" "${pod}" -c database -- grep -c BEGIN /pgconf/tls/ca.crt
   done
   ```

4. Create the new server and replication certificates signed by the new CA, as described in steps 2 to 4 of the [Use your own TLS certificates](#use-your-own-tls-certificates) section.

5. Replace the certificates in the Kubernetes Secrets. Both Kubernetes Secrets keep both CAs in the `ca.crt` key:

   ```bash
   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca-bundle.crt --from-file=tls.crt=server.crt --from-file=tls.key=server.key                 \
     --dry-run=client -o yaml | kubectl apply -f -

   kubectl create secret generic "${POSTGRESQL_INSTANCE_NAME}-custom-replication-tls" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
     --from-file=ca.crt=ca-bundle.crt --from-file=tls.crt=replication.crt --from-file=tls.key=replication.key                   \
     --dry-run=client -o yaml | kubectl apply -f -
   ```

   After about two minutes, check that the PostgreSQL server uses the new certificate, as described in step 8 of the [Use your own TLS certificates](#use-your-own-tls-certificates) section. The issuer is the new CA.

6. Check that the replicas connect with the new replication certificate. A running replication connection keeps the certificate it started with, so first close it on the primary. The replica connects again within a few seconds and does not lose any data:

   ```bash
   PRIMARY_POD=$(kubectl get pods -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}"                                                    \
     -l "postgres-operator.crunchydata.com/cluster=${POSTGRESQL_INSTANCE_NAME},postgres-operator.crunchydata.com/role=primary" \
     -o jsonpath='{.items[0].metadata.name}')

   kubectl exec -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" "${PRIMARY_POD}" -c database -- \
     psql -Atc "select pg_terminate_backend(pid) from pg_stat_replication"

   sleep 10

   kubectl exec -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" "${PRIMARY_POD}" -c database -- \
     psql -Atc "select r.state, s.client_dn, s.issuer_dn from pg_stat_replication r join pg_stat_ssl s using (pid)"
   ```

   Each replica shows the `streaming` state, the `/CN=_crunchyrepl` client, and the new CA as the issuer. Do not continue if the issuer is still the old CA, because the replicas cannot connect after you remove it.

7. Remove the old CA from both Kubernetes Secrets:

   ```bash
   for secret in custom-tls custom-replication-tls; do
     kubectl patch secret "${POSTGRESQL_INSTANCE_NAME}-${secret}" -n "${NAMESPACE_WITH_POSTGRESQL_CLUSTER}" \
       --type merge -p "{\"data\":{\"ca.crt\":\"$(base64 < ca.crt | tr -d '\n')\"}}"
   done
   ```

   After about two minutes, the command from step 3 prints `1` for each Pod. Repeat step 6 to check that the replicas still connect.

> [!IMPORTANT]
> Before you remove the old CA, the clients that verify the server certificate with the `verify-ca` or `verify-full` SSL mode must trust the new CA. Otherwise, they cannot connect to the PostgreSQL cluster.
