이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Operator Guide


Red Hat build of Keycloak 26.2

Red Hat Customer Content Services

Abstract

This guide consists of information for administrators to configure and use the Red Hat build of Keycloak 26.2 Operator.

Chapter 1. Red Hat build of Keycloak Operator installation

How to install the Operator on OpenShift.

Use this procedure to install the Red Hat build of Keycloak Operator in an OpenShift cluster.

  1. Open the OpenShift Container Platform web console.
  2. In the left column, click Home, Operators, OperatorHub.
  3. Search for "Keycloak" on the search input box.
  4. Select the Operator from the list of results.
  5. Follow the instructions on the screen.

For general instructions on installing Operators by using either the CLI or web console, see Installing Operators in your namespace. In the default Catalog, the Operator is named rhbk-operator. Make sure to use the channel corresponding with your desired Red Hat build of Keycloak version.

1.1. Configuring Manual Approval for OLM Upgrades

Warning

Important: Automatic OLM Upgrades

By default, OLM automatically updates the Red Hat build of Keycloak Operator when a new version is released. This can cause several significant issues:

  • When using the default Red Hat build of Keycloak image, the Operator uses a matching image of the corresponding Red Hat build of Keycloak version, resulting in unintended Red Hat build of Keycloak upgrades when the Operator is upgraded
  • Even when using custom images, major Operator upgrades can introduce significant compatibility issues with your existing Keycloak CR configuration, potentially requiring manual intervention
  • New fields in Keycloak CR or behavioral changes could impact existing deployments
  • No option to downgrade to the previous Red Hat build of Keycloak version due to changes related to database migration

Recommendation:

We strongly recommend using manual approval mode for the Red Hat build of Keycloak Operator. This ensures you can:

  1. Review release notes and follow migration changes before approving upgrades
  2. Schedule maintenance windows for upgrades
  3. Test upgrades in a non-production environment first
  4. Back up the database to allow downgrading to the previous Red Hat build of Keycloak in case of issues

To prevent automatic upgrades by OLM, set the approval strategy to Manual when installing the Operator:

1.1.1. Using the OpenShift web console

When installing the Operator, select Manual approval in the update approval strategy section:

1.1.2. Using the CLI

For command-line installation, create a Subscription with installPlanApproval: Manual:

apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  name: rhbk-operator
  namespace: <target-namespace>
spec:
  channel: <desired-channel>
  name: rhbk-operator
  source: redhat-operators
  sourceNamespace: openshift-marketplace
  installPlanApproval: Manual
Copy to Clipboard Toggle word wrap

After installation, any upgrade will require manual approval through the OLM interface or via the CLI.

1.2. Installing Multiple Operators

It is not fully supported for the operator to watch multiple or all namespaces. To watch multiple namespaces, you install multiple operators.

In this situation, consider the following:

  • All Operators share the Custom Resource Definitions (CRDs) as they are installed cluster wide.
  • CRD revisions from newer Operator versions will not introduce breaking changes except for the eventual removal of fields that have been deprecated for some time. Thus newer CRDs are generally backward compatible.
  • The last installed CRDs become the ones that are used. This rule also applies to OLM installations; the last installed Operator version also installs and overrides the CRDs if they already exist in the cluster.
  • Older CRDs may not be forward compatible with new fields used by newer operators. When using OLM it will check if your custom resources are compatible with the CRDs being installed, so the usage of new fields can prevent the simultaneous installation of older operator versions.
  • Fields introduced by newer CRDs are not supported by older Operators. Older Operators fail to handle CRs that use such new fields with a deserialization error for an unrecognized field.

Therefore, in a multiple Operator installation scenario, the recommended approach is to keep versions aligned as closely as possible to minimize the potential problems with different versions.

Chapter 2. Basic Red Hat build of Keycloak deployment

Install Red Hat build of Keycloak using the Operator.

2.1. Performing a basic Red Hat build of Keycloak deployment

This chapter describes how to perform a basic Red Hat build of Keycloak Deployment on OpenShift using the Operator.

2.1.1. Preparing for deployment

Once the Red Hat build of Keycloak Operator is installed and running in the cluster namespace, you can set up the other deployment prerequisites.

  • Database
  • Hostname
  • TLS Certificate and associated keys
2.1.1.1. Database

A database should be available and accessible from the cluster namespace where Red Hat build of Keycloak is installed. For a list of supported databases, see Configuring the database. The Red Hat build of Keycloak Operator does not manage the database and you need to provision it yourself. Consider verifying your cloud provider offering or using a database operator.

For development purposes, you can use an ephemeral PostgreSQL pod installation. To provision it, follow the approach below:

Create YAML file example-postgres.yaml:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgresql-db
spec:
  serviceName: postgresql-db-service
  selector:
    matchLabels:
      app: postgresql-db
  replicas: 1
  template:
    metadata:
      labels:
        app: postgresql-db
    spec:
      containers:
        - name: postgresql-db
          image: postgres:15
          volumeMounts:
            - mountPath: /data
              name: cache-volume
          env:
            - name: POSTGRES_USER
              value: testuser
            - name: POSTGRES_PASSWORD
              value: testpassword
            - name: PGDATA
              value: /data/pgdata
            - name: POSTGRES_DB
              value: keycloak
      volumes:
        - name: cache-volume
          emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: postgres-db
spec:
  selector:
    app: postgresql-db
  type: LoadBalancer
  ports:
  - port: 5432
    targetPort: 5432
Copy to Clipboard Toggle word wrap

Apply the changes:

oc apply -f example-postgres.yaml
Copy to Clipboard Toggle word wrap
2.1.1.2. Hostname

For a production ready installation, you need a hostname that can be used to contact Red Hat build of Keycloak. See Configuring the hostname (v2) for the available configurations.

For development purposes, this chapter will use test.keycloak.org.

When running on OpenShift, with ingress enabled, and with the spec.ingress.classname set to openshift-default, you may leave the spec.hostname.hostname unpopulated in the Keycloak CR. The operator will assign a default hostname to the stored version of the CR similar to what would be created by an OpenShift Route without an explicit host - that is ingress-namespace.appsDomain If the appsDomain changes, or should you need a different hostname for any reason, then update the Keycloak CR.

Note

If you set the hostname-admin, or the deprecated hostname-admin-url, even if you enable ingress, no ingress will be created specifically for admin access. Admin access via a separate hostname is generally expected to have access restrictions, which are not currently expressible via the Keycloak CR. Also the default ingress does not prevent accessing admin endpoints, so you may not want to enable ingress handling via the Keycloak CR at all when you have a separate hostname for admin endpoints.

2.1.1.3. TLS Certificate and key

See your Certification Authority to obtain the certificate and the key.

For development purposes, you can enter this command to obtain a self-signed certificate:

openssl req -subj '/CN=test.keycloak.org/O=Test Keycloak./C=US' -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem
Copy to Clipboard Toggle word wrap

You should install it in the cluster namespace as a Secret by entering this command:

oc create secret tls example-tls-secret --cert certificate.pem --key key.pem
Copy to Clipboard Toggle word wrap

2.1.2. Deploying Red Hat build of Keycloak

To deploy Red Hat build of Keycloak, you create a Custom Resource (CR) based on the Keycloak Custom Resource Definition (CRD).

Consider storing the Database credentials in a separate Secret. Enter the following commands:

oc create secret generic keycloak-db-secret \
  --from-literal=username=[your_database_username] \
  --from-literal=password=[your_database_password]
Copy to Clipboard Toggle word wrap

You can customize several fields using the Keycloak CRD. For a basic deployment, you can stick to the following approach:

Create YAML file example-kc.yaml:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  instances: 1
  db:
    vendor: postgres
    host: postgres-db
    usernameSecret:
      name: keycloak-db-secret
      key: username
    passwordSecret:
      name: keycloak-db-secret
      key: password
  http:
    tlsSecret: example-tls-secret
  hostname:
    hostname: test.keycloak.org
  proxy:
    headers: xforwarded # double check your reverse proxy sets and overwrites the X-Forwarded-* headers
Copy to Clipboard Toggle word wrap

Apply the changes:

oc apply -f example-kc.yaml
Copy to Clipboard Toggle word wrap

To check that the Red Hat build of Keycloak instance has been provisioned in the cluster, check the status of the created CR by entering the following command:

oc get keycloaks/example-kc -o go-template='{{range .status.conditions}}CONDITION: {{.type}}{{"\n"}}  STATUS: {{.status}}{{"\n"}}  MESSAGE: {{.message}}{{"\n"}}{{end}}'
Copy to Clipboard Toggle word wrap

When the deployment is ready, look for output similar to the following:

CONDITION: Ready
  STATUS: true
  MESSAGE:
CONDITION: HasErrors
  STATUS: false
  MESSAGE:
CONDITION: RollingUpdate
  STATUS: false
  MESSAGE:
Copy to Clipboard Toggle word wrap

2.1.3. Accessing the Red Hat build of Keycloak deployment

The Red Hat build of Keycloak deployment can be exposed through a basic Ingress accessible through the provided hostname.

On installations with multiple default IngressClass instances or when running on OpenShift 4.12+ you should provide an ingressClassName by setting ingress spec with className property to the desired class name:

Edit YAML file example-kc.yaml:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
    ...
    ingress:
      className: openshift-default
Copy to Clipboard Toggle word wrap

If the default ingress does not fit your use case, disable it by setting ingress spec with enabled property to false value:

Edit YAML file example-kc.yaml:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
    ...
    ingress:
      enabled: false
Copy to Clipboard Toggle word wrap

Apply the changes:

oc apply -f example-kc.yaml
Copy to Clipboard Toggle word wrap

You can then provide an alternative ingress resource pointing to the service <keycloak-cr-name>-service. For example, on OpenShift you are not allowed to use wildcard certificates on passthrough Routes with HTTP/2 enabled. A Keycloak CR on OpenShift with TLS enabled using a wildcard certificate with the default IngressClass creates such a Route. In this case, you must disable the built-in ingress with .spec.ingress.enabled: false. Access may then be provided by creating a reencrypt Route instead:

$ oc create route reencrypt --service=<keycloak-cr-name>-service --cert=<configured-certificate> --key=<certificate-key> --dest-ca-cert=<ca-certificate> --ca-cert=<ca-certificate> --hostname=<hostname>
Copy to Clipboard Toggle word wrap

For debugging and development purposes, consider directly connecting to the Red Hat build of Keycloak service using a port forward. For example, enter this command:

oc port-forward service/example-kc-service 8443:8443
Copy to Clipboard Toggle word wrap
2.1.3.1. Configuring the reverse proxy settings matching your Ingress Controller

The Operator supports configuring which of the reverse proxy headers should be accepted by server, which includes Forwarded and X-Forwarded-* headers.

If you Ingress implementation sets and overwrites either Forwarded or X-Forwarded-* headers, you can reflect that in the Keycloak CR as follows:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  proxy:
    headers: forwarded|xforwarded
Copy to Clipboard Toggle word wrap
Note

If the proxy.headers field is not specified, the Operator falls back to legacy behaviour by implicitly setting proxy=passthrough by default. This results in deprecation warnings in the server log. This fallback will be removed in a future release.

Warning

When using the proxy.headers field, make sure your Ingress properly sets and overwrites the Forwarded or X-Forwarded-* headers respectively. To set these headers, consult the documentation for your Ingress Controller. Consider configuring it for either reencrypt or edge TLS termination as passthrough TLS doesn’t allow the Ingress to modify the requests headers. Misconfiguration will leave Red Hat build of Keycloak exposed to security vulnerabilities.

For more details refer to the Configuring a reverse proxy guide.

2.1.4. Accessing the Admin Console

When deploying Red Hat build of Keycloak, the operator generates an arbitrary initial admin username and password and stores those credentials as a basic-auth Secret object in the same namespace as the CR.

Warning

Change the default admin credentials and enable MFA in Red Hat build of Keycloak before going to production.

To fetch the initial admin credentials, you have to read and decode the Secret. The Secret name is derived from the Keycloak CR name plus the fixed suffix -initial-admin. To get the username and password for the example-kc CR, enter the following commands:

oc get secret example-kc-initial-admin -o jsonpath='{.data.username}' | base64 --decode
oc get secret example-kc-initial-admin -o jsonpath='{.data.password}' | base64 --decode
Copy to Clipboard Toggle word wrap

You can use those credentials to access the Admin Console or the Admin REST API.

2.1.5. Security Considerations

Warning

Anyone with the ability to create or edit Keycloak or KeycloakRealmImport CRs should be a namespace level admin.

Setting the Keycloak CR image requires a high degree of trust as whatever image is running will at least have access to any Secrets used for environment variables.

Similarly the unsupported podTemplate gives the ability to deploy alternative workloads which may be granted the same permissions as the operator itself - which includes the ability to access Secrets in the namespace.

Chapter 3. Automating a realm import

Automate a realm import using the operator.

3.1. Importing a Red Hat build of Keycloak Realm

Using the Red Hat build of Keycloak Operator, you can perform a realm import for the Keycloak Deployment.

Note
  • If a Realm with the same name already exists in Red Hat build of Keycloak, it will not be overwritten.
  • The Realm Import CR only supports creation of new realms and does not update or delete those. Changes to the realm performed directly on Red Hat build of Keycloak are not synced back in the CR.

3.1.1. Creating a Realm Import Custom Resource

The following is an example of a Realm Import Custom Resource (CR):

apiVersion: k8s.keycloak.org/v2alpha1
kind: KeycloakRealmImport
metadata:
  name: my-realm-kc
spec:
  keycloakCRName: <name of the keycloak CR>
  realm:
    ...
Copy to Clipboard Toggle word wrap

This CR should be created in the same namespace as the Keycloak Deployment CR, defined in the field keycloakCRName. The realm field accepts a full RealmRepresentation.

The recommended way to obtain a RealmRepresentation is by leveraging the export functionality Importing and exporting realms.

  1. Export the Realm to a single file.
  2. Convert the JSON file to YAML.
  3. Copy and paste the obtained YAML file as body for the realm key, making sure the indentation is correct.

3.1.2. Applying the Realm Import CR

Use oc to create the CR in the correct cluster namespace:

Create YAML file example-realm-import.yaml:

apiVersion: k8s.keycloak.org/v2alpha1
kind: KeycloakRealmImport
metadata:
  name: my-realm-kc
spec:
  keycloakCRName: <name of the keycloak CR>
  realm:
    id: example-realm
    realm: example-realm
    displayName: ExampleRealm
    enabled: true
Copy to Clipboard Toggle word wrap

Apply the changes:

oc apply -f example-realm-import.yaml
Copy to Clipboard Toggle word wrap

To check the status of the running import, enter the following command:

oc get keycloakrealmimports/my-realm-kc -o go-template='{{range .status.conditions}}CONDITION: {{.type}}{{"\n"}}  STATUS: {{.status}}{{"\n"}}  MESSAGE: {{.message}}{{"\n"}}{{end}}'
Copy to Clipboard Toggle word wrap

When the import has successfully completed, the output will look like the following example:

CONDITION: Done
  STATUS: true
  MESSAGE:
CONDITION: Started
  STATUS: false
  MESSAGE:
CONDITION: HasErrors
  STATUS: false
  MESSAGE:
Copy to Clipboard Toggle word wrap

3.1.3. Placeholders

Imports support placeholders referencing environment variables, see Importing and exporting realms for more. The KeycloakRealmImport CR allows you to leverage this functionality via the spec.placeholders stanza, for example:

apiVersion: k8s.keycloak.org/v2alpha1
kind: KeycloakRealmImport
metadata:
  name: my-realm-kc
spec:
  keycloakCRName: <name of the keycloak CR>
  placeholders:
    ENV_KEY:
      secret:
        name: SECRET_NAME
        key: SECRET_KEY
    ...
Copy to Clipboard Toggle word wrap

In the above example placeholder replacement will be enabled and an environment variable with key ENV_KEY will be created from the Secret SECRET_NAME’s value for key `SECRET_KEY. Currently only Secrets are supported and they must be in the same namespace as the Keycloak CR.

3.1.4. Security Considerations

Warning

Anyone with the ability to create or edit KeycloakRealmImport CRs should be a namespace level admin.

Placeholder replacement gives access to all environment variables even sensitive ones.

Chapter 4. Advanced configuration

Tune advanced aspects of the Keycloak CR.

4.1. Advanced configuration

This chapter describes how to use Custom Resources (CRs) for advanced configuration of your Red Hat build of Keycloak deployment.

4.1.1. Server configuration details

Many server options are exposed as first-class citizen fields in the Keycloak CR. The structure of the CR is based on the configuration structure of Red Hat build of Keycloak. For example, to configure the https-port of the server, follow a similar pattern in the CR and use the httpsPort field. The following example is a complex server configuration; however, it illustrates the relationship between server options and the Keycloak CR:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  db:
    vendor: postgres
    usernameSecret:
      name: usernameSecret
      key: usernameSecretKey
    passwordSecret:
      name: passwordSecret
      key: passwordSecretKey
    host: host
    database: database
    port: 123
    schema: schema
    poolInitialSize: 1
    poolMinSize: 2
    poolMaxSize: 3
  http:
    httpEnabled: true
    httpPort: 8180
    httpsPort: 8543
    tlsSecret: my-tls-secret
  hostname:
    hostname: https://my-hostname.tld
    admin: https://my-hostname.tld/admin
    strict: false
    backchannelDynamic: true
  features:
    enabled:
      - docker
      - authorization
    disabled:
      - admin
      - step-up-authentication
  transaction:
    xaEnabled: false
Copy to Clipboard Toggle word wrap

For a list of options, see the Keycloak CRD. For details on configuring options, see All configuration.

4.1.1.1. Additional options

Some expert server options are unavailable as dedicated fields in the Keycloak CR. The following are examples of omitted fields:

  • Fields that require deep understanding of the underlying Red Hat build of Keycloak implementation
  • Fields that are not relevant to an OpenShift environment
  • Fields for provider configuration because they are dynamic based on the used provider implementation

The additionalOptions field of the Keycloak CR enables Red Hat build of Keycloak to accept any available configuration in the form of key-value pairs. You can use this field to include any option that is omitted in the Keycloak CR. For details on configuring options, see All configuration.

The values can be expressed as plain text strings or Secret object references as shown in this example:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  additionalOptions:
    - name: spi-connections-http-client-default-connection-pool-size
      secret: # Secret reference
        name: http-client-secret # name of the Secret
        key: poolSize # name of the Key in the Secret
    - name: spi-email-template-mycustomprovider-enabled
      value: true # plain text value
Copy to Clipboard Toggle word wrap
Note

The name format of options defined in this way is identical to the key format of options specified in the configuration file. For details on various configuration formats, see Configuring Red Hat build of Keycloak.

4.1.2. Secret References

Secret References are used by some dedicated options in the Keycloak CR, such as tlsSecret, or as a value in additionalOptions.

Similarly ConfigMap References are used by options such as the configMapFile.

When specifying a Secret or ConfigMap Reference, make sure that a Secret or ConfigMap containing the referenced keys is present in the same namespace as the CR referencing it.

The operator will poll approximately every minute for changes to referenced Secrets or ConfigMaps. When a meaningful change is detected, the Operator performs a rolling restart of the Red Hat build of Keycloak Deployment to pick up the changes.

4.1.3. Unsupported features

The unsupported field of the CR contains highly experimental configuration options that are not completely tested and are Tech Preview.

4.1.3.1. Pod Template

The Pod Template is a raw API representation that is used for the Deployment Template. This field is a temporary workaround in case no supported field exists at the top level of the CR for your use case.

The Operator merges the fields of the provided template with the values generated by the Operator for the specific Deployment. With this feature, you have access to a high level of customizations. However, no guarantee exists that the Deployment will work as expected.

The following example illustrates injecting labels, annotations, volumes, and volume mounts:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  unsupported:
    podTemplate:
      metadata:
        labels:
          my-label: "keycloak"
      spec:
        containers:
          - volumeMounts:
              - name: test-volume
                mountPath: /mnt/test
        volumes:
          - name: test-volume
            secret:
              secretName: keycloak-additional-secret
Copy to Clipboard Toggle word wrap
4.1.3.1.1. Probe Timeouts

The unsupported podTemplate may be used to override the default probes.

In particular the default startup probe timeout of 10 minutes may be too short in scenarios where there is a long-running migration.

If your instances encounter this startup failure or if you wish to proactively prevent such a startup failure from occurring, then the startup probe timeout should be increased.

With otherwise default settings, something like the following increases the timeout to 20 minutes:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  unsupported:
    podTemplate:
      spec:
        containers:
          startupProbe:
            httpGet:
              path: "/health/started"
            port: 9000
            scheme: "HTTPS"
            failureThreshold: 1200
            periodSeconds: 1
Copy to Clipboard Toggle word wrap

Note that the usage of a relative HTTP path, or an alternative management port, requires changes to the probe configuration.

4.1.4. Disabling required options

Red Hat build of Keycloak and the Red Hat build of Keycloak Operator provide the best production-ready experience with security in mind. However, during the development phase, you can disable key security features.

Specifically, you can disable the hostname and TLS as shown in the following example:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  http:
    httpEnabled: true
  hostname:
    strict: false
Copy to Clipboard Toggle word wrap

4.1.5. Resource requirements

The Keycloak CR allows specifying the resources options for managing compute resources for the Red Hat build of Keycloak container. It provides the ability to request and limit resources independently for the main Keycloak deployment via the Keycloak CR, and for the realm import Job via the Realm Import CR.

When no values are specified, the default requests memory is set to 1700MiB, and the limits memory is set to 2GiB. These values were chosen based on a deeper analysis of Red Hat build of Keycloak memory management.

If no values are specified in the Realm Import CR, it falls back to the values specified in the Keycloak CR, or to the defaults as defined above.

You can specify your custom values based on your requirements as follows:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  resources:
    requests:
      cpu: 1200m
      memory: 896Mi
    limits:
      cpu: 6
      memory: 3Gi
Copy to Clipboard Toggle word wrap

Moreover, the Red Hat build of Keycloak container manages the heap size more effectively by providing relative values for the heap size. It is achieved by providing certain JVM options.

For more details, see Running Red Hat build of Keycloak in a container.

4.1.6. Scheduling

You may control several aspects of the server Pod scheduling via the Keycloak CR. The scheduling stanza exposes optional standard Kubernetes affinity, tolerations, topology spread constraints, and the priority class name to fine tune the scheduling and placement of your server Pods.

An example utilizing all scheduling fields:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  scheduling:
    priorityClassName: custom-high
    affinity:
      podAffinity:
        preferredDuringSchedulingIgnoredDuringExecution:
        - podAffinityTerm:
            labelSelector:
              matchLabels:
                app: keycloak
                app.kubernetes.io/managed-by: keycloak-operator
                app.kubernetes.io/component: server
                topologyKey: topology.kubernetes.io/zone
              weight: 10
    tolerations:
    - key: "some-taint"
      operator: "Exists"
      effect: "NoSchedule"
    topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: kubernetes.io/hostname
      whenUnsatisfiable: DoNotSchedule
      ...
  ...
Copy to Clipboard Toggle word wrap

Please see the kubernetes docs for more on scheduling concepts.

If you do not specify a custom affinity, your Pods will have an affinity for the same zone and an anti-affinity for the same node to improve availability. Scheduling to the same zone if possible helps prevent stretch clusters where cross zone cache cluster traffic may have too high of a latency.

4.1.7. Management Interface

To change the port of the management interface, use the first-class citizen field httpManagement.port in the Keycloak CR. To change the properties of the management interface, you can do it by providing additionalOptions field.

You can specify the port and the additionalOptions as follows:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  httpManagement:
    port: 9001
  additionalOptions:
    - name: http-management-relative-path
      value: /management
Copy to Clipboard Toggle word wrap
Note

If you are using a custom image, the Operator is unaware of any configuration options that might’ve been specified there. For instance, it may cause that the management interface uses the https schema, but the Operator accesses it via http when the TLS settings is specified in the custom image. To ensure proper TLS configuration, use the tlsSecret and truststores fields in the Keycloak CR so that the Operator can reflect that.

For more details, see Configuring the Management Interface.

4.1.8. Truststores

If you need to provide trusted certificates, the Keycloak CR provides a top level feature for configuring the server’s truststore as discussed in Configuring trusted certificates.

Use the truststores stanza of the Keycloak spec to specify Secrets containing PEM encoded files, or PKCS12 files with extension .p12, .pfx, or .pkcs12, for example:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ...
  truststores:
    my-truststore:
      secret:
        name: my-secret
Copy to Clipboard Toggle word wrap

Where the contents of my-secret could be a PEM file, for example:

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
stringData:
  cert.pem: |
    -----BEGIN CERTIFICATE-----
    ...
Copy to Clipboard Toggle word wrap

When running on a Kubernetes or OpenShift environment well-known locations of trusted certificates are included automatically. This includes /var/run/secrets/kubernetes.io/serviceaccount/ca.crt and the /var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt when present.

4.1.9. Admin Bootstrapping

When you create a new instance the Keycloak CR spec.bootstrapAdmin stanza may be used to configure the bootstrap user and/or service account. If you do not specify anything for the spec.bootstrapAdmin, the operator will create a Secret named "metadata.name"-initial-admin with a username temp-admin and a generated password. If you specify a Secret name for the bootstrap admin user, then the Secret will need to contain username and password key value pairs. If you specify a Secret name for bootstrap admin service account, then the Secret will need to contain client-id and client-secret key value pairs.

If a master realm has already been created for your cluster, then the spec.boostrapAdmin is effectively ignored. If you need to create a recovery admin account, then you’ll need to run the CLI command against a Pod directly.

For more information on how to bootstrap a temporary admin user or service account and recover lost admin access, refer to the Bootstrapping and recovering an admin account guide.

4.1.10. Tracing (OpenTelemetry)

Tracing allows for detailed monitoring of each request’s lifecycle, which helps quickly identify and diagnose issues, leading to more efficient debugging and maintenance.

You can change tracing configuration via Keycloak CR fields as follows:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  tracing:
    enabled: true                             # default 'false'
    endpoint: http://my-tracing:4317          # default 'http://localhost:4317'
    samplerType: parentbased_traceidratio     # default 'traceidratio'
    samplerRatio: 0.01                        # default '1'
    resourceAttributes:
      some.attribute: something
  additionalOptions:
    - name: tracing-jdbc-enabled
      value: false                            # default 'true'
Copy to Clipboard Toggle word wrap

These fields should reflect 1:1 association with tracing-* options that contain more information.

Note

The tracing-jdbc-enabled is not promoted as a first-class citizen as it might not be well managed in the future, so it needs to be set via the additionalOptions field.

For more details about tracing, see Root cause analysis with tracing.

4.1.11. Network Policies

NetworkPolicies allow you to specify rules for traffic flow within your cluster, and also between Pods and the outside world. Your cluster must use a network plugin that supports NetworkPolicy enforcement to restrict the network traffic.

The operator automatically creates a NetworkPolicy to deny access to the clustering port of your Red Hat build of Keycloak Pods. The HTTP(S) endpoint is open to traffic from any namespace and the outside world.

To disable the NetworkPolicy, set spec.networkPolicy.enabled in your Keycloak CR, as shown in the example below.

Keycloak CR with Network Policies enabled

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  networkPolicy:
    enabled: false
Copy to Clipboard Toggle word wrap

By default, traffic to the HTTP endpoints and the management endpoint is allowed from all sources. The Keycloak CR can be extended to include a list of rules for each of the endpoints exposed by Red Hat build of Keycloak. These rules specify from where (the source) the traffic is allowed, and it is possible to communicate with the Red Hat build of Keycloak Pods.

Extended Network Policy configuration

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  networkPolicy:
    enabled: true
    http: <list of rules> 
1

    https: <list of rules> 
2

    management: <list of rules> 
3
Copy to Clipboard Toggle word wrap

1
It defines the rules for HTTP endpoint (port 8080 by default). Due to security reasons, the HTTP endpoint is disabled by default.
2
It defines the access rules for HTTPS endpoint (port 8443 by default.
3
It defines the access rules for management endpoint (port 9000 by default). The management endpoint is used by the Kubernetes Probes and to expose the Red Hat build of Keycloak metrics.

The rule syntax is the same as the one used by the Kubernetes Network Policy. It makes it easy to migrate your existing rules into your Keycloak CP. For more information, check the rule syntax.

4.1.11.1. Example with OpenShift

For a concrete example, let’s imagine we have a Red Hat build of Keycloak deployment running in a OpenShift cluster. Users have to access Red Hat build of Keycloak to login, so Red Hat build of Keycloak must be accessible from the Internet.

To make this example more interesting, let’s assume the Red Hat build of Keycloak is monitored too. The monitoring is enabled as described in this OpenShift documentation page: enabling Monitoring for user defined projects.

Based on those requirements, the Keycloak CR would be like this (most parts are omitted, like DB connection and security):

Keycloak CR

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  ingress:
    enabled: true 
1

  networkPolicy:
    enabled: true
    https:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: openshift-ingress 
2

    management:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: openshift-user-workload-monitoring 
3
Copy to Clipboard Toggle word wrap

1
Enables Ingress for outside access.
2
The default OpenShift Ingress class pods are running in openshift-ingress namespace. We allow traffic from these pods to access the Red Hat build of Keycloak HTTPS endpoint. The traffic from outside the OpenShift cluster goes through these pods.
3
Prometheus pods are running in openshift-user-workload-monitoring. They need to access Red Hat build of Keycloak to scrape the available metrics.

Check the Kubernetes Network Policies documentation for more information about NetworkPolicies.

Chapter 5. Avoiding downtime with rolling updates

Avoid downtime when changing themes, providers, or configurations in optimized images.

By default, the Red Hat build of Keycloak Operator will perform rolling updates on configuration changes without downtime, and recreate updates with downtime when the image name or tag changes.

This chapter describes how to minimize downtimes by configuring the Red Hat build of Keycloak Operator to perform rolling updates of Red Hat build of Keycloak automatically where possible, and how to override automatic detection for rolling updates.

Use it, for example, to avoid downtimes when rolling out an update to a theme, provider or build time configuration in a custom or optimized image.

5.1. Supported Update Strategies

The Operator supports the following update strategies:

Rolling Updates
Update the StatefulSet in a rolling fashion, avoiding a downtime when at least two replicas are running.
Recreate Updates
Scale down the StatefulSet before applying updates, causing temporary downtime.

5.2. Configuring the Update Strategy

Specify the update strategy within the spec section of the Keycloak CR YAML definition:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  update:
    strategy: RecreateOnImageChange|Auto|Explicit 
1

    revision: "abc" 
2
Copy to Clipboard Toggle word wrap
1
Set the desired update strategy here.
2
Revision value for Explicit strategy. Ignored by the other strategies.
Expand
Table 5.1. Possible field values
ValueDowntime?Description

RecreateOnImageChange (default)

On image name or tag change

Mimics Red Hat build of Keycloak 26.1 or older behavior. When the image field changes, the Operator scales down the StatefulSet before applying the new image.

Auto

On incompatible changes

The Red Hat build of Keycloak Operator detects if a rolling or recreate update is possible.

In the current version, Red Hat build of Keycloak performs a rolling update if the Red Hat build of Keycloak version is the same for the old and the new image. Future versions of Red Hat build of Keycloak will change that behavior and use additional information from the configuration, the image and the version to determine if a rolling update is possible to reduce downtimes.

Explicit

Only the revision field changes

The Red Hat build of Keycloak Operator checks the spec.update.revision value. If it matches the previous deployment, it performs a rolling update.

5.2.1. Understanding Auto and Explicit Update Strategies

When using the Auto update strategy, the Red Hat build of Keycloak Operator automatically starts a Job to assess the feasibility of a rolling update. Read more about the process in the Checking if rolling updates are possible chapter. This process consumes cluster resources for the time of the check and introduces a slight delay before the StatefulSet update begins.

Warning

If the Keycloak CR configured a podTemplate as part of the unsupported configuration parameters, the Keycloak Operator will do its best to use those settings for the started Job. Still it might miss some settings due to the flexibility of the podTemplate feature and its unsupported nature.

As a consequence, the Operator might draw the wrong conclusions if a rolling update is possible from changes to the podTemplate or information pulled in from Secrets, ConfigMaps or Volumes in the podTemplate.

Therefore, if you are using the unsupported podTemplate, you may need to use one of the other update strategies.

The Explicit update strategy delegates the update decision to the user. The revision field acts as a user-controlled trigger. While the Red Hat build of Keycloak Operator does not interpret the revision value itself, any change to the Custom Resource (CR) while the revision remains unchanged will prompt a rolling update.

Exercise caution when using this with automatic Operator upgrades. The Operator Lifecycle Manager (OLM) may upgrade the Red Hat build of Keycloak Operator, and if the Explicit update strategy is in use, this could lead to unexpected behavior or deployment failures as the Operator would attempt a rolling update when this is actually not supported. If you are using the Explicit update strategy, thorough testing in a non-production environment is highly recommended before upgrading.

5.2.2. CR Statuses

The Keycloak CR status of RecreateUpdateUsed indicates the update strategy employed during the last update operation. The lastTransitionTime field indicates when the last update occurred. Use this information to observe actions and decisions taken by the Operator.

Expand
Table 5.2. Condition statuses
StatusDescription

Unknown

The initial state. It means no update has taken place.

False

The Operator applied the rolling update strategy in the last update.

True

The Operator applied the recreate update strategy in the last update. The message field explains why this strategy was chosen.

Chapter 6. Using custom Red Hat build of Keycloak images

Customize and optimize the Red Hat build of Keycloak container.

6.1. Red Hat build of Keycloak custom image with the Operator

With the Keycloak Custom Resource (CR), you can specify a custom container image for the Red Hat build of Keycloak server.

Note

To ensure full compatibility of Operator and Operand, make sure that the version of Red Hat build of Keycloak release used in the custom image is aligned with the version of the operator.

6.1.1. Best practice

When using the default Red Hat build of Keycloak image, the server will perform a costly re-augmentation every time a Pod starts. To avoid this delay, you can provide a custom image with the augmentation built-in from the build time of the image.

With a custom image, you can also specify the Keycloak build-time configurations and extensions during the build of the container.

Warning

When using the optimized custom image, health-enabled and metrics-enabled options need to be explicitly set in the Containerfile.

For instructions on how to build such an image, see Running Red Hat build of Keycloak in a container.

6.1.2. Providing a custom Red Hat build of Keycloak image

To provide a custom image, you define the image field in the Keycloak CR as shown in this example:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  instances: 1
  image: quay.io/my-company/my-keycloak:latest
  http:
    tlsSecret: example-tls-secret
  hostname:
    hostname: test.keycloak.org
Copy to Clipboard Toggle word wrap
Note

With custom images, every build time option passed either through a dedicated field or the additionalOptions is ignored.

Note

The Operator is unaware of any configuration options that are specified in a custom image. Use the Keycloak CR for any configuration that requires Operator awareness, namely the TLS and HTTP(S) settings reflected when configuring services and probes.

6.1.3. Non-optimized custom image

While it is considered a best practice to use a pre-augmented image, if you want to use a non-optimized custom image or build time properties with an augmented image that is still possible. You just need set the startOptimized field to false as shown in this example:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: example-kc
spec:
  instances: 1
  image: quay.io/my-company/my-keycloak:latest
  startOptimized: false
  http:
    tlsSecret: example-tls-secret
  hostname:
    hostname: test.keycloak.org
Copy to Clipboard Toggle word wrap

Keep in mind this will incur the re-augmentation cost on every start.

Legal Notice

Copyright © 2025 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat