Configuring Strimzi (In Development)

Configuring Strimzi (In Development)

Table of Contents

1. Configuration overview

Strimzi simplifies the process of running Apache Kafka in a Kubernetes cluster.

This guide describes how to configure and manage a Strimzi deployment.

1.1. Configuring custom resources

Use custom resources to configure your Strimzi deployment.

You can use custom resources to configure and create instances of the following components:

  • Kafka clusters

  • Kafka Connect clusters

  • Kafka MirrorMaker

  • Kafka Bridge

  • Cruise Control

You can also use custom resource configuration to manage your instances or modify your deployment to introduce additional features. This might include configuration that supports the following:

  • Securing client access to Kafka brokers

  • Accessing Kafka brokers from outside the cluster

  • Creating topics

  • Creating users (clients)

  • Controlling feature gates

  • Changing logging frequency

  • Allocating resource limits and requests

  • Introducing features, such as Strimzi Drain Cleaner, Cruise Control, or distributed tracing.

The Custom resource API reference describes the properties you can use in your configuration.

1.2. Using ConfigMaps to add configuration

Use ConfigMap resources to add specific configuration to your Strimzi deployment. ConfigMaps use key-value pairs to store non-confidential data. Configuration data added to ConfigMaps is maintained in one place and can be reused amongst components.

ConfigMaps can only store configuration data related to the following:

  • Logging configuration

  • Metrics configuration

  • External configuration for Kafka Connect connectors

You can’t use ConfigMaps for other areas of configuration.

When you configure a component, you can add a reference to a ConfigMap using the configMapKeyRef property.

For example, you can use configMapKeyRef to reference a ConfigMap that provides configuration for logging. You might use a ConfigMap to pass a Log4j configuration file. You add the reference to the logging configuration.

Example ConfigMap for logging
spec:
  # ...
  logging:
    type: external
    valueFrom:
      configMapKeyRef:
        name: my-config-map
        key: my-config-map-key

To use a ConfigMap for metrics configuration, you add a reference to the metricsConfig configuration of the component in the same way.

ExternalConfiguration properties make data from a ConfigMap (or Secret) mounted to a pod available as environment variables or volumes. You can use external configuration data for the connectors used by Kafka Connect. The data might be related to an external data source, providing the values needed for the connector to communicate with that data source.

For example, you can use the configMapKeyRef property to pass configuration data from a ConfigMap as an environment variable.

Example ConfigMap providing environment variable values
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
  name: my-connect
spec:
  # ...
  externalConfiguration:
    env:
      - name: MY_ENVIRONMENT_VARIABLE
        valueFrom:
          configMapKeyRef:
            name: my-config-map
            key: my-key

If you are using ConfigMaps that are managed externally, use configuration providers to load the data in the ConfigMaps. For more information on using configuration providers, see Loading configuration values from external sources.

1.2.1. Naming custom ConfigMaps

Strimzi creates its own ConfigMaps and other resources when it is deployed to Kubernetes. The ConfigMaps contain data necessary for running components. The ConfigMaps created by Strimzi must not be edited.

Make sure that any custom ConfigMaps you create do not have the same name as these default ConfigMaps. If they have the same name, they will be overwritten. For example, if your ConfigMap has the same name as the ConfigMap for the Kafka cluster, it will be overwritten when there is an update to the Kafka cluster.

1.3. Document Conventions

User-replaced values

User-replaced values, also known as replaceables, are shown in italics with angle brackets (< >). Underscores ( _ ) are used for multi-word values. If the value refers to code or commands, monospace is also used.

For example, in the following code, you will want to replace <my_namespace> with the name of your namespace:

sed -i 's/namespace: .*/namespace: <my_namespace>/' install/cluster-operator/*RoleBinding*.yaml

2. Configuring a Strimzi deployment

Configure your Strimzi deployment using custom resources. Strimzi provides example configuration files, which can serve as a starting point when building your own Kafka component configuration for deployment.

Note
Labels applied to a custom resource are also applied to the Kubernetes resources making up its cluster. This provides a convenient mechanism for resources to be labeled as required.
Monitoring a Strimzi deployment

You can use Prometheus and Grafana to monitor your Strimzi deployment. For more information, see Introducing metrics to Kafka.

2.1. Kafka cluster configuration

Configure a Kafka deployment using the Kafka resource. A Kafka cluster is deployed with a ZooKeeper cluster, so configuration options are also available for ZooKeeper within the Kafka resource. The Entity Operator comprises the Topic Operator and User Operator. You can also configure entityOperator properties in the Kafka resource to include the Topic Operator and User Operator in the deployment.

Kafka schema reference describes the full schema of the Kafka resource.

For more information about Apache Kafka, see the Apache Kafka documentation.

Listener configuration

You configure listeners for connecting clients to Kafka brokers. For more information on configuring listeners, see GenericKafkaListener schema reference.

Managing TLS certificates

When deploying Kafka, the Cluster Operator automatically sets up and renews TLS certificates to enable encryption and authentication within your cluster. If required, you can manually renew the cluster and clients CA certificates before their renewal period starts. You can also replace the keys used by the cluster and clients CA certificates. For more information, see Renewing CA certificates manually and Replacing private keys.

2.1.1. Configuring Kafka

Use the properties of the Kafka resource to configure your Kafka deployment.

As well as configuring Kafka, you can add configuration for ZooKeeper and the Strimzi Operators. Common configuration properties, such as logging and healthchecks, are configured independently for each component.

This procedure shows only some of the possible configuration options, but those that are particularly important include:

  • Resource requests (CPU / Memory)

  • JVM options for maximum and minimum memory allocation

  • Listeners (and authentication of clients)

  • Authentication

  • Storage

  • Rack awareness

  • Metrics

  • Cruise Control for cluster rebalancing

Kafka versions

The inter.broker.protocol.version property for the Kafka config must be the version supported by the specified Kafka version (spec.kafka.version). The property represents the version of Kafka protocol used in a Kafka cluster.

From Kafka 3.0.0, when the inter.broker.protocol.version is set to 3.0 or higher, the log.message.format.version option is ignored and doesn’t need to be set.

An update to the inter.broker.protocol.version is required when upgrading your Kafka version. For more information, see Upgrading Kafka.

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

See the Deploying and Upgrading Strimzi guide for instructions on deploying a:

Procedure
  1. Edit the spec properties for the Kafka resource.

    The properties you can configure are shown in this example configuration:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        replicas: 3 (1)
        version: 3.3.2 (2)
        logging: (3)
          type: inline
          loggers:
            kafka.root.logger.level: "INFO"
        resources: (4)
          requests:
            memory: 64Gi
            cpu: "8"
          limits:
            memory: 64Gi
            cpu: "12"
        readinessProbe: (5)
          initialDelaySeconds: 15
          timeoutSeconds: 5
        livenessProbe:
          initialDelaySeconds: 15
          timeoutSeconds: 5
        jvmOptions: (6)
          -Xms: 8192m
          -Xmx: 8192m
        image: my-org/my-image:latest (7)
        listeners: (8)
          - name: plain (9)
            port: 9092 (10)
            type: internal (11)
            tls: false (12)
            configuration:
              useServiceDnsDomain: true (13)
          - name: tls
            port: 9093
            type: internal
            tls: true
            authentication: (14)
              type: tls
          - name: external (15)
            port: 9094
            type: route
            tls: true
            configuration:
              brokerCertChainAndKey: (16)
                secretName: my-secret
                certificate: my-certificate.crt
                key: my-key.key
        authorization: (17)
          type: simple
        config: (18)
          auto.create.topics.enable: "false"
          offsets.topic.replication.factor: 3
          transaction.state.log.replication.factor: 3
          transaction.state.log.min.isr: 2
          default.replication.factor: 3
          min.insync.replicas: 2
          inter.broker.protocol.version: "3.3"
          ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" (19)
          ssl.enabled.protocols: "TLSv1.2"
          ssl.protocol: "TLSv1.2"
        storage: (20)
          type: persistent-claim (21)
          size: 10000Gi (22)
        rack: (23)
          topologyKey: topology.kubernetes.io/zone
        metricsConfig: (24)
          type: jmxPrometheusExporter
          valueFrom:
            configMapKeyRef: (25)
              name: my-config-map
              key: my-key
        # ...
      zookeeper: (26)
        replicas: 3 (27)
        logging: (28)
          type: inline
          loggers:
            zookeeper.root.logger: "INFO"
        resources:
          requests:
            memory: 8Gi
            cpu: "2"
          limits:
            memory: 8Gi
            cpu: "2"
        jvmOptions:
          -Xms: 4096m
          -Xmx: 4096m
        storage:
          type: persistent-claim
          size: 1000Gi
        metricsConfig:
          # ...
      entityOperator: (29)
        tlsSidecar: (30)
          resources:
            requests:
              cpu: 200m
              memory: 64Mi
            limits:
              cpu: 500m
              memory: 128Mi
        topicOperator:
          watchedNamespace: my-topic-namespace
          reconciliationIntervalSeconds: 60
          logging: (31)
            type: inline
            loggers:
              rootLogger.level: "INFO"
          resources:
            requests:
              memory: 512Mi
              cpu: "1"
            limits:
              memory: 512Mi
              cpu: "1"
        userOperator:
          watchedNamespace: my-topic-namespace
          reconciliationIntervalSeconds: 60
          logging: (32)
            type: inline
            loggers:
              rootLogger.level: INFO
          resources:
            requests:
              memory: 512Mi
              cpu: "1"
            limits:
              memory: 512Mi
              cpu: "1"
      kafkaExporter: (33)
        # ...
      cruiseControl: (34)
        # ...
    1. The number of replica nodes. If your cluster already has topics defined, you can scale clusters.

    2. Kafka version, which can be changed to a supported version by following the upgrade procedure.

    3. Kafka loggers and log levels added directly (inline) or indirectly (external) through a ConfigMap. A custom ConfigMap must be placed under the log4j.properties key. For the Kafka kafka.root.logger.level logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.

    4. Requests for reservation of supported resources, currently cpu and memory, and limits to specify the maximum resources that can be consumed.

    5. Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).

    6. JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka.

    7. ADVANCED OPTION: Container image configuration, which is recommended only in special situations.

    8. Listeners configure how clients connect to the Kafka cluster via bootstrap addresses. Listeners are configured as internal or external listeners for connection from inside or outside the Kubernetes cluster.

    9. Name to identify the listener. Must be unique within the Kafka cluster.

    10. Port number used by the listener inside Kafka. The port number has to be unique within a given Kafka cluster. Allowed port numbers are 9092 and higher with the exception of ports 9404 and 9999, which are already used for Prometheus and JMX. Depending on the listener type, the port number might not be the same as the port number that connects Kafka clients.

    11. Listener type specified as internal or cluster-ip (to expose Kafka using per-broker ClusterIP services), or for external listeners, as route, loadbalancer, nodeport or ingress.

    12. Enables TLS encryption for each listener. Default is false. TLS encryption is not required for route listeners.

    13. Defines whether the fully-qualified DNS names including the cluster service suffix (usually .cluster.local) are assigned.

    14. Listener authentication mechanism specified as mTLS, SCRAM-SHA-512, or token-based OAuth 2.0.

    15. External listener configuration specifies how the Kafka cluster is exposed outside Kubernetes, such as through a route, loadbalancer or nodeport.

    16. Optional configuration for a Kafka listener certificate managed by an external CA (certificate authority). The brokerCertChainAndKey specifies a Secret that contains a server certificate and a private key. You can configure Kafka listener certificates on any listener with enabled TLS encryption.

    17. Authorization enables simple, OAUTH 2.0, or OPA authorization on the Kafka broker. Simple authorization uses the AclAuthorizer Kafka plugin.

    18. Broker configuration. Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.

    19. SSL properties for listeners with TLS encryption enabled to enable a specific cipher suite or TLS version.

    20. Storage is configured as ephemeral, persistent-claim or jbod.

    21. Storage size for persistent volumes may be increased and additional volumes may be added to JBOD storage.

    22. Persistent storage has additional configuration options, such as a storage id and class for dynamic volume provisioning.

    23. Rack awareness configuration to spread replicas across different racks, data centers, or availability zones. The topologyKey must match a node label containing the rack ID. The example used in this configuration specifies a zone using the standard topology.kubernetes.io/zone label.

    24. Prometheus metrics enabled. In this example, metrics are configured for the Prometheus JMX Exporter (the default metrics exporter).

    25. Prometheus rules for exporting metrics to a Grafana dashboard through the Prometheus JMX Exporter, which are enabled by referencing a ConfigMap containing configuration for the Prometheus JMX exporter. You can enable metrics without further configuration using a reference to a ConfigMap containing an empty file under metricsConfig.valueFrom.configMapKeyRef.key.

    26. ZooKeeper-specific configuration, which contains properties similar to the Kafka configuration.

    27. The number of ZooKeeper nodes. ZooKeeper clusters or ensembles usually run with an odd number of nodes, typically three, five, or seven. The majority of nodes must be available in order to maintain an effective quorum. If the ZooKeeper cluster loses its quorum, it will stop responding to clients and the Kafka brokers will stop working. Having a stable and highly available ZooKeeper cluster is crucial for Strimzi.

    28. Specified ZooKeeper loggers and log levels.

    29. Entity Operator configuration, which specifies the configuration for the Topic Operator and User Operator.

    30. Entity Operator TLS sidecar configuration. Entity Operator uses the TLS sidecar for secure communication with ZooKeeper.

    31. Specified Topic Operator loggers and log levels. This example uses inline logging.

    32. Specified User Operator loggers and log levels.

    33. Kafka Exporter configuration. Kafka Exporter is an optional component for extracting metrics data from Kafka brokers, in particular consumer lag data. For Kafka Exporter to be able to work properly, consumer groups need to be in use.

    34. Optional configuration for Cruise Control, which is used to rebalance the Kafka cluster.

  2. Create or update the resource:

    kubectl apply -f <kafka_configuration_file>

2.1.2. Configuring the Entity Operator

The Entity Operator is responsible for managing Kafka-related entities in a running Kafka cluster.

The Entity Operator comprises the:

  • Topic Operator to manage Kafka topics

  • User Operator to manage Kafka users

Through Kafka resource configuration, the Cluster Operator can deploy the Entity Operator, including one or both operators, when deploying a Kafka cluster.

The operators are automatically configured to manage the topics and users of the Kafka cluster. The Topic Operator and User Operator can only watch a single namespace. For more information, see Watching namespaces with Strimzi operators.

Note
When deployed, the Entity Operator pod contains the operators according to the deployment configuration.
Entity Operator configuration properties

Use the entityOperator property in Kafka.spec to configure the Entity Operator.

The entityOperator property supports several sub-properties:

  • tlsSidecar

  • topicOperator

  • userOperator

  • template

The tlsSidecar property contains the configuration of the TLS sidecar container, which is used to communicate with ZooKeeper.

The template property contains the configuration of the Entity Operator pod, such as labels, annotations, affinity, and tolerations. For more information on configuring templates, see Customizing Kubernetes resources.

The topicOperator property contains the configuration of the Topic Operator. When this option is missing, the Entity Operator is deployed without the Topic Operator.

The userOperator property contains the configuration of the User Operator. When this option is missing, the Entity Operator is deployed without the User Operator.

For more information on the properties used to configure the Entity Operator, see the EntityUserOperatorSpec schema reference.

Example of basic configuration enabling both operators
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
  zookeeper:
    # ...
  entityOperator:
    topicOperator: {}
    userOperator: {}

If an empty object ({}) is used for the topicOperator and userOperator, all properties use their default values.

When both topicOperator and userOperator properties are missing, the Entity Operator is not deployed.

Topic Operator configuration properties

Topic Operator deployment can be configured using additional options inside the topicOperator object. The following properties are supported:

watchedNamespace

The Kubernetes namespace in which the Topic Operator watches for KafkaTopic resources. Default is the namespace where the Kafka cluster is deployed.

reconciliationIntervalSeconds

The interval between periodic reconciliations in seconds. Default 120.

zookeeperSessionTimeoutSeconds

The ZooKeeper session timeout in seconds. Default 18.

topicMetadataMaxAttempts

The number of attempts at getting topic metadata from Kafka. The time between each attempt is defined as an exponential back-off. Consider increasing this value when topic creation might take more time due to the number of partitions or replicas. Default 6.

image

The image property can be used to configure the container image which will be used. For more details about configuring custom container images, see image.

resources

The resources property configures the amount of resources allocated to the Topic Operator. For more details about resource request and limit configuration, see resources.

logging

The logging property configures the logging of the Topic Operator. For more details, see logging.

Example Topic Operator configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
  zookeeper:
    # ...
  entityOperator:
    # ...
    topicOperator:
      watchedNamespace: my-topic-namespace
      reconciliationIntervalSeconds: 60
    # ...
User Operator configuration properties

User Operator deployment can be configured using additional options inside the userOperator object. The following properties are supported:

watchedNamespace

The Kubernetes namespace in which the User Operator watches for KafkaUser resources. Default is the namespace where the Kafka cluster is deployed.

reconciliationIntervalSeconds

The interval between periodic reconciliations in seconds. Default 120.

image

The image property can be used to configure the container image which will be used. For more details about configuring custom container images, see image.

resources

The resources property configures the amount of resources allocated to the User Operator. For more details about resource request and limit configuration, see resources.

logging

The logging property configures the logging of the User Operator. For more details, see logging.

secretPrefix

The secretPrefix property adds a prefix to the name of all Secrets created from the KafkaUser resource. For example, secretPrefix: kafka- would prefix all Secret names with kafka-. So a KafkaUser named my-user would create a Secret named kafka-my-user.

Example User Operator configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
  zookeeper:
    # ...
  entityOperator:
    # ...
    userOperator:
      watchedNamespace: my-user-namespace
      reconciliationIntervalSeconds: 60
    # ...

2.1.3. Configuring Kafka and ZooKeeper storage

As stateful applications, Kafka and ZooKeeper store data on disk. Strimzi supports three storage types for this data:

  • Ephemeral (Recommended for development only)

  • Persistent

  • JBOD (Kafka only not ZooKeeper)

When configuring a Kafka resource, you can specify the type of storage used by the Kafka broker and its corresponding ZooKeeper node. You configure the storage type using the storage property in the following resources:

  • Kafka.spec.kafka

  • Kafka.spec.zookeeper

The storage type is configured in the type field.

Refer to the schema reference for more information on storage configuration properties:

Warning
The storage type cannot be changed after a Kafka cluster is deployed.
Data storage considerations

For Strimzi to work well, an efficient data storage infrastructure is essential. We strongly recommend using block storage. Strimzi is only tested for use with block storage. File storage, such as NFS, is not tested and there is no guarantee it will work.

Choose one of the following options for your block storage:

Note
Strimzi does not require Kubernetes raw block volumes.
File systems

Kafka uses a file system for storing messages. Strimzi is compatible with the XFS and ext4 file systems, which are commonly used with Kafka. Consider the underlying architecture and requirements of your deployment when choosing and setting up your file system.

For more information, refer to Filesystem Selection in the Kafka documentation.

Disk usage

Use separate disks for Apache Kafka and ZooKeeper.

Solid-state drives (SSDs), though not essential, can improve the performance of Kafka in large clusters where data is sent to and received from multiple topics asynchronously. SSDs are particularly effective with ZooKeeper, which requires fast, low latency data access.

Note
You do not need to provision replicated storage because Kafka and ZooKeeper both have built-in data replication.
Ephemeral storage

Ephemeral data storage is transient. All pods on a node share a local ephemeral storage space. Data is retained for as long as the pod that uses it is running. The data is lost when a pod is deleted. Although a pod can recover data in a highly available environment.

Because of its transient nature, ephemeral storage is only recommended for development and testing.

Ephemeral storage uses emptyDir volumes to store data. An emptyDir volume is created when a pod is assigned to a node. You can set the total amount of storage for the emptyDir using the sizeLimit property .

Important
Ephemeral storage is not suitable for single-node ZooKeeper clusters or Kafka topics with a replication factor of 1.

To use ephemeral storage, you set the storage type configuration in the Kafka or ZooKeeper resource to ephemeral.

Example ephemeral storage configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    storage:
      type: ephemeral
    # ...
  zookeeper:
    # ...
    storage:
      type: ephemeral
    # ...
Mount path of Kafka log directories

The ephemeral volume is used by Kafka brokers as log directories mounted into the following path:

/var/lib/kafka/data/kafka-logIDX

Where IDX is the Kafka broker pod index. For example /var/lib/kafka/data/kafka-log0.

Persistent storage

Persistent data storage retains data in the event of system disruption. For pods that use persistent data storage, data is persisted across pod failures and restarts.

A dynamic provisioning framework enables clusters to be created with persistent storage. Pod configuration uses Persistent Volume Claims (PVCs) to make storage requests on persistent volumes (PVs). PVs are storage resources that represent a storage volume. PVs are independent of the pods that use them. The PVC requests the amount of storage required when a pod is being created. The underlying storage infrastructure of the PV does not need to be understood. If a PV matches the storage criteria, the PVC is bound to the PV.

Because of its permanent nature, persistent storage is recommended for production.

PVCs can request different types of persistent storage by specifying a StorageClass. Storage classes define storage profiles and dynamically provision PVs. If a storage class is not specified, the default storage class is used. Persistent storage options might include SAN storage types or local persistent volumes.

To use persistent storage, you set the storage type configuration in the Kafka or ZooKeeper resource to persistent-claim.

In the production environment, the following configuration is recommended:

  • For Kafka, configure type: jbod with one or more type: persistent-claim volumes

  • For ZooKeeper, configure type: persistent-claim

Persistent storage also has the following configuration options:

id (optional)

A storage identification number. This option is mandatory for storage volumes defined in a JBOD storage declaration. Default is 0.

size (required)

The size of the persistent volume claim, for example, "1000Gi".

class (optional)

The Kubernetes StorageClass to use for dynamic volume provisioning. Storage class configuration includes parameters that describe the profile of a volume in detail.

selector (optional)

Configuration to specify a specific PV. Provides key:value pairs representing the labels of the volume selected.

deleteClaim (optional)

Boolean value to specify whether the PVC is deleted when the cluster is uninstalled. Default is false.

Warning
Increasing the size of persistent volumes in an existing Strimzi cluster is only supported in Kubernetes versions that support persistent volume resizing. The persistent volume to be resized must use a storage class that supports volume expansion. For other versions of Kubernetes and storage classes that do not support volume expansion, you must decide the necessary storage size before deploying the cluster. Decreasing the size of existing persistent volumes is not possible.
Example persistent storage configuration for Kafka and ZooKeeper
# ...
spec:
  kafka:
    # ...
    storage:
      type: jbod
      volumes:
      - id: 0
        type: persistent-claim
        size: 100Gi
        deleteClaim: false
      - id: 1
        type: persistent-claim
        size: 100Gi
        deleteClaim: false
      - id: 2
        type: persistent-claim
        size: 100Gi
        deleteClaim: false
    # ...
  zookeeper:
    storage:
      type: persistent-claim
      size: 1000Gi
# ...

If you do not specify a storage class, the default is used. The following example specifies a storage class.

Example persistent storage configuration with specific storage class
# ...
storage:
  type: persistent-claim
  size: 1Gi
  class: my-storage-class
# ...

Use a selector to specify a labeled persistent volume that provides certain features, such as an SSD.

Example persistent storage configuration with selector
# ...
storage:
  type: persistent-claim
  size: 1Gi
  selector:
    hdd-type: ssd
  deleteClaim: true
# ...
Storage class overrides

Instead of using the default storage class, you can specify a different storage class for one or more Kafka brokers or ZooKeeper nodes. This is useful, for example, when storage classes are restricted to different availability zones or data centers. You can use the overrides field for this purpose.

In this example, the default storage class is named my-storage-class:

Example Strimzi cluster using storage class overrides
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  labels:
    app: my-cluster
  name: my-cluster
  namespace: myproject
spec:
  # ...
  kafka:
    replicas: 3
    storage:
      type: jbod
      volumes:
      - id: 0
        type: persistent-claim
        size: 100Gi
        deleteClaim: false
        class: my-storage-class
        overrides:
        - broker: 0
          class: my-storage-class-zone-1a
        - broker: 1
          class: my-storage-class-zone-1b
        - broker: 2
          class: my-storage-class-zone-1c
      # ...
  # ...
  zookeeper:
    replicas: 3
    storage:
      deleteClaim: true
      size: 100Gi
      type: persistent-claim
      class: my-storage-class
      overrides:
        - broker: 0
          class: my-storage-class-zone-1a
        - broker: 1
          class: my-storage-class-zone-1b
        - broker: 2
          class: my-storage-class-zone-1c
  # ...

As a result of the configured overrides property, the volumes use the following storage classes:

  • The persistent volumes of ZooKeeper node 0 use my-storage-class-zone-1a.

  • The persistent volumes of ZooKeeper node 1 use my-storage-class-zone-1b.

  • The persistent volumes of ZooKeeepr node 2 use my-storage-class-zone-1c.

  • The persistent volumes of Kafka broker 0 use my-storage-class-zone-1a.

  • The persistent volumes of Kafka broker 1 use my-storage-class-zone-1b.

  • The persistent volumes of Kafka broker 2 use my-storage-class-zone-1c.

The overrides property is currently used only to override storage class configurations. Overrides for other storage configuration properties is not currently supported. Other storage configuration properties are currently not supported.

PVC resources for persistent storage

When persistent storage is used, it creates PVCs with the following names:

data-cluster-name-kafka-idx

PVC for the volume used for storing data for the Kafka broker pod idx.

data-cluster-name-zookeeper-idx

PVC for the volume used for storing data for the ZooKeeper node pod idx.

Mount path of Kafka log directories

The persistent volume is used by the Kafka brokers as log directories mounted into the following path:

/var/lib/kafka/data/kafka-logIDX

Where IDX is the Kafka broker pod index. For example /var/lib/kafka/data/kafka-log0.

Resizing persistent volumes

You can provision increased storage capacity by increasing the size of the persistent volumes used by an existing Strimzi cluster. Resizing persistent volumes is supported in clusters that use either a single persistent volume or multiple persistent volumes in a JBOD storage configuration.

Note
You can increase but not decrease the size of persistent volumes. Decreasing the size of persistent volumes is not currently supported in Kubernetes.
Prerequisites
  • A Kubernetes cluster with support for volume resizing.

  • The Cluster Operator is running.

  • A Kafka cluster using persistent volumes created using a storage class that supports volume expansion.

Procedure
  1. Edit the Kafka resource for your cluster.

    Change the size property to increase the size of the persistent volume allocated to a Kafka cluster, a ZooKeeper cluster, or both.

    • For Kafka clusters, update the size property under spec.kafka.storage.

    • For ZooKeeper clusters, update the size property under spec.zookeeper.storage.

    Kafka configuration to increase the volume size to 2000Gi
    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        # ...
        storage:
          type: persistent-claim
          size: 2000Gi
          class: my-storage-class
        # ...
      zookeeper:
        # ...
  2. Create or update the resource:

    kubectl apply -f <kafka_configuration_file>

    Kubernetes increases the capacity of the selected persistent volumes in response to a request from the Cluster Operator. When the resizing is complete, the Cluster Operator restarts all pods that use the resized persistent volumes. This happens automatically.

  3. Verify that the storage capacity has increased for the relevant pods on the cluster:

    kubectl get pv
    Kafka broker pods with increased storage
    NAME               CAPACITY   CLAIM
    pvc-0ca459ce-...   2000Gi     my-project/data-my-cluster-kafka-2
    pvc-6e1810be-...   2000Gi     my-project/data-my-cluster-kafka-0
    pvc-82dc78c9-...   2000Gi     my-project/data-my-cluster-kafka-1

    The output shows the names of each PVC associated with a broker pod.

Additional resources
JBOD storage

You can configure Strimzi to use JBOD, a data storage configuration of multiple disks or volumes. JBOD is one approach to providing increased data storage for Kafka brokers. It can also improve performance.

Note
JBOD storage is supported for Kafka only not ZooKeeper.

A JBOD configuration is described by one or more volumes, each of which can be either ephemeral or persistent. The rules and constraints for JBOD volume declarations are the same as those for ephemeral and persistent storage. For example, you cannot decrease the size of a persistent storage volume after it has been provisioned, or you cannot change the value of sizeLimit when the type is ephemeral.

To use JBOD storage, you set the storage type configuration in the Kafka resource to jbod. The volumes property allows you to describe the disks that make up your JBOD storage array or configuration.

Example JBOD storage configuration
# ...
storage:
  type: jbod
  volumes:
  - id: 0
    type: persistent-claim
    size: 100Gi
    deleteClaim: false
  - id: 1
    type: persistent-claim
    size: 100Gi
    deleteClaim: false
# ...

The IDs cannot be changed once the JBOD volumes are created. You can add or remove volumes from the JBOD configuration.

PVC resource for JBOD storage

When persistent storage is used to declare JBOD volumes, it creates a PVC with the following name:

data-id-cluster-name-kafka-idx

PVC for the volume used for storing data for the Kafka broker pod idx. The id is the ID of the volume used for storing data for Kafka broker pod.

Mount path of Kafka log directories

The JBOD volumes are used by Kafka brokers as log directories mounted into the following path:

/var/lib/kafka/data-id/kafka-logidx

Where id is the ID of the volume used for storing data for Kafka broker pod idx. For example /var/lib/kafka/data-0/kafka-log0.

Adding volumes to JBOD storage

This procedure describes how to add volumes to a Kafka cluster configured to use JBOD storage. It cannot be applied to Kafka clusters configured to use any other storage type.

Note
When adding a new volume under an id which was already used in the past and removed, you have to make sure that the previously used PersistentVolumeClaims have been deleted.
Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

  • A Kafka cluster with JBOD storage

Procedure
  1. Edit the spec.kafka.storage.volumes property in the Kafka resource. Add the new volumes to the volumes array. For example, add the new volume with id 2:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        # ...
        storage:
          type: jbod
          volumes:
          - id: 0
            type: persistent-claim
            size: 100Gi
            deleteClaim: false
          - id: 1
            type: persistent-claim
            size: 100Gi
            deleteClaim: false
          - id: 2
            type: persistent-claim
            size: 100Gi
            deleteClaim: false
        # ...
      zookeeper:
        # ...
  2. Create or update the resource:

    kubectl apply -f <kafka_configuration_file>
  3. Create new topics or reassign existing partitions to the new disks.

Additional resources

For more information about reassigning topics, see Partition reassignment tool.

Removing volumes from JBOD storage

This procedure describes how to remove volumes from Kafka cluster configured to use JBOD storage. It cannot be applied to Kafka clusters configured to use any other storage type. The JBOD storage always has to contain at least one volume.

Important
To avoid data loss, you have to move all partitions before removing the volumes.
Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

  • A Kafka cluster with JBOD storage with two or more volumes

Procedure
  1. Reassign all partitions from the disks which are you going to remove. Any data in partitions still assigned to the disks which are going to be removed might be lost.

  2. Edit the spec.kafka.storage.volumes property in the Kafka resource. Remove one or more volumes from the volumes array. For example, remove the volumes with ids 1 and 2:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        # ...
        storage:
          type: jbod
          volumes:
          - id: 0
            type: persistent-claim
            size: 100Gi
            deleteClaim: false
        # ...
      zookeeper:
        # ...
  3. Create or update the resource:

    kubectl apply -f <kafka_configuration_file>
Additional resources

For more information about reassigning topics, see Partition reassignment tool.

2.1.4. Scaling clusters

Scale Kafka clusters by adding or removing brokers. If a cluster already has topics defined, you also have to reassign partitions.

Use the kafka-reassign-partitions.sh tool to reassign partitions. The tool uses a reassignment JSON file that specifies the topics to reassign.

You can generate a reassignment JSON file or create a file manually if you want to move specific partitions.

Broker scaling configuration

You configure the Kafka.spec.kafka.replicas configuration to add or reduce the number of brokers.

Broker addition

The primary way of increasing throughput for a topic is to increase the number of partitions for that topic. That works because the extra partitions allow the load of the topic to be shared between the different brokers in the cluster. However, in situations where every broker is constrained by a particular resource (typically I/O) using more partitions will not result in increased throughput. Instead, you need to add brokers to the cluster.

When you add an extra broker to the cluster, Kafka does not assign any partitions to it automatically. You must decide which partitions to reassign from the existing brokers to the new broker.

Once the partitions have been redistributed between all the brokers, the resource utilization of each broker is reduced.

Broker removal

If you are using StatefulSets to manage broker pods, you cannot remove any pod from the cluster. You can only remove one or more of the highest numbered pods from the cluster. For example, in a cluster of 12 brokers the pods are named cluster-name-kafka-0 up to cluster-name-kafka-11. If you decide to scale down by one broker, the cluster-name-kafka-11 will be removed.

Before you remove a broker from a cluster, ensure that it is not assigned to any partitions. You should also decide which of the remaining brokers will be responsible for each of the partitions on the broker being decommissioned. Once the broker has no assigned partitions, you can scale the cluster down safely.

Partition reassignment tool

The Topic Operator does not currently support reassigning replicas to different brokers, so it is necessary to connect directly to broker pods to reassign replicas to brokers.

Within a broker pod, the kafka-reassign-partitions.sh tool allows you to reassign partitions to different brokers.

It has three different modes:

--generate

Takes a set of topics and brokers and generates a reassignment JSON file which will result in the partitions of those topics being assigned to those brokers. Because this operates on whole topics, it cannot be used when you only want to reassign some partitions of some topics.

--execute

Takes a reassignment JSON file and applies it to the partitions and brokers in the cluster. Brokers that gain partitions as a result become followers of the partition leader. For a given partition, once the new broker has caught up and joined the ISR (in-sync replicas) the old broker will stop being a follower and will delete its replica.

--verify

Using the same reassignment JSON file as the --execute step, --verify checks whether all the partitions in the file have been moved to their intended brokers. If the reassignment is complete, --verify also removes any traffic throttles (--throttle) that are in effect. Unless removed, throttles will continue to affect the cluster even after the reassignment has finished.

It is only possible to have one reassignment running in a cluster at any given time, and it is not possible to cancel a running reassignment. If you need to cancel a reassignment, wait for it to complete and then perform another reassignment to revert the effects of the first reassignment. The kafka-reassign-partitions.sh will print the reassignment JSON for this reversion as part of its output. Very large reassignments should be broken down into a number of smaller reassignments in case there is a need to stop in-progress reassignment.

Partition reassignment JSON file

The reassignment JSON file has a specific structure:

{
  "version": 1,
  "partitions": [
    <PartitionObjects>
  ]
}

Where <PartitionObjects> is a comma-separated list of objects like:

{
  "topic": <TopicName>,
  "partition": <Partition>,
  "replicas": [ <AssignedBrokerIds> ]
}
Note
Although Kafka also supports a "log_dirs" property this should not be used in Strimzi.

The following is an example reassignment JSON file that assigns partition 4 of topic topic-a to brokers 2, 4 and 7, and partition 2 of topic topic-b to brokers 1, 5 and 7:

Example partition reassignment file
{
  "version": 1,
  "partitions": [
    {
      "topic": "topic-a",
      "partition": 4,
      "replicas": [2,4,7]
    },
    {
      "topic": "topic-b",
      "partition": 2,
      "replicas": [1,5,7]
    }
  ]
}

Partitions not included in the JSON are not changed.

Partition reassignment between JBOD volumes

When using JBOD storage in your Kafka cluster, you can choose to reassign the partitions between specific volumes and their log directories (each volume has a single log directory). To reassign a partition to a specific volume, add the log_dirs option to <PartitionObjects> in the reassignment JSON file.

{
  "topic": <TopicName>,
  "partition": <Partition>,
  "replicas": [ <AssignedBrokerIds> ],
  "log_dirs": [ <AssignedLogDirs> ]
}

The log_dirs object should contain the same number of log directories as the number of replicas specified in the replicas object. The value should be either an absolute path to the log directory, or the any keyword.

Example partition reassignment file specifying log directories
{
      "topic": "topic-a",
      "partition": 4,
      "replicas": [2,4,7].
      "log_dirs": [ "/var/lib/kafka/data-0/kafka-log2", "/var/lib/kafka/data-0/kafka-log4", "/var/lib/kafka/data-0/kafka-log7" ]
}
Partition reassignment throttles

Partition reassignment can be a slow process because it involves transferring large amounts of data between brokers. To avoid a detrimental impact on clients, you can throttle the reassignment process. Use the --throttle parameter with the kafka-reassign-partitions.sh tool to throttle a reassignment. You specify a maximum threshold in bytes per second for the movement of partitions between brokers. For example, --throttle 5000000 sets a maximum threshold for moving partitions of 50 MBps.

Throttling might cause the reassignment to take longer to complete.

  • If the throttle is too low, the newly assigned brokers will not be able to keep up with records being published and the reassignment will never complete.

  • If the throttle is too high, clients will be impacted.

For example, for producers, this could manifest as higher than normal latency waiting for acknowledgment. For consumers, this could manifest as a drop in throughput caused by higher latency between polls.

Generating reassignment JSON files

This procedure describes how to generate a reassignment JSON file. Use the reassignment file with the kafka-reassign-partitions.sh tool to reassign partitions after scaling a Kafka cluster.

You run the tool from an interactive pod container connected to the Kafka cluster.

The steps describe a secure reassignment process that uses mTLS. You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.

You’ll need the following to establish a connection:

  • The cluster CA certificate and password generated by the Cluster Operator when the Kafka cluster is created

  • The user CA certificate and password generated by the User Operator when a user is created for client access to the Kafka cluster

In this procedure, the CA certificates and corresponding passwords are extracted from the cluster and user secrets that contain them in PKCS #12 (.p12 and .password) format. The passwords allow access to the .p12 stores that contain the certificates. You use the .p12 stores to specify a truststore and keystore to authenticate connection to the Kafka cluster.

Prerequisites
  • You have a running Cluster Operator.

  • You have a running Kafka cluster based on a Kafka resource configured with internal TLS encryption and mTLS authentication.

    Kafka configuration with TLS encryption and mTLS authentication
    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        # ...
        listeners:
          # ...
          - name: tls
            port: 9093
            type: internal
            tls: true (1)
            authentication:
              type: tls (2)
        # ...
    1. Enables TLS encryption for the internal listener.

    2. Listener authentication mechanism specified as mutual tls.

  • The running Kafka cluster contains a set of topics and partitions to reassign.

    Example topic configuration for my-topic
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaTopic
    metadata:
      name: my-topic
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      partitions: 10
      replicas: 3
      config:
        retention.ms: 7200000
        segment.bytes: 1073741824
        # ...
  • You have a KafkaUser configured with ACL rules that specify permission to produce and consume topics from the Kafka brokers.

    Example Kafka user configuration with ACL rules to allow operations on my-topic and my-cluster
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaUser
    metadata:
      name: my-user
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      authentication: (1)
        type: tls
      authorization:
        type: simple (2)
        acls:
          # access to the topic
          - resource:
              type: topic
              name: my-topic
            operations:
              - Create
              - Describe
              - Read
              - AlterConfigs
            host: "*"
          # access to the cluster
          - resource:
              type: cluster
            operations:
              - Alter
              - AlterConfigs
            host: "*"
          # ...
      # ...
    1. User authentication mechanism defined as mutual tls.

    2. Simple authorization and accompanying list of ACL rules.

Procedure
  1. Extract the cluster CA certificate and password from the <cluster_name>-cluster-ca-cert secret of the Kafka cluster.

    kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.p12}' | base64 -d > ca.p12
    kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.password}' | base64 -d > ca.password

    Replace <cluster_name> with the name of the Kafka cluster. When you deploy Kafka using the Kafka resource, a secret with the cluster CA certificate is created with the Kafka cluster name (<cluster_name>-cluster-ca-cert). For example, my-cluster-cluster-ca-cert.

  2. Run a new interactive pod container using the Strimzi Kafka image to connect to a running Kafka broker.

    kubectl run --restart=Never --image=quay.io/strimzi/kafka:latest-kafka-3.3.2 <interactive_pod_name> -- /bin/sh -c "sleep 3600"

    Replace <interactive_pod_name> with the name of the pod.

  3. Copy the cluster CA certificate to the interactive pod container.

    kubectl cp ca.p12 <interactive_pod_name>:/tmp
  4. Extract the user CA certificate and password from the secret of the Kafka user that has permission to access the Kafka brokers.

    kubectl get secret <kafka_user> -o jsonpath='{.data.user\.p12}' | base64 -d > user.p12
    kubectl get secret <kafka_user> -o jsonpath='{.data.user\.password}' | base64 -d > user.password

    Replace <kafka_user> with the name of the Kafka user. When you create a Kafka user using the KafkaUser resource, a secret with the user CA certificate is created with the Kafka user name. For example, my-user.

  5. Copy the user CA certificate to the interactive pod container.

    kubectl cp user.p12 <interactive_pod_name>:/tmp

    The CA certificates allow the interactive pod container to connect to the Kafka broker using TLS.

  6. Create a config.properties file to specify the truststore and keystore used to authenticate connection to the Kafka cluster.

    Use the certificates and passwords you extracted in the previous steps.

    bootstrap.servers=<kafka_cluster_name>-kafka-bootstrap:9093 (1)
    security.protocol=SSL (2)
    ssl.truststore.location=/tmp/ca.p12 (3)
    ssl.truststore.password=<truststore_password> (4)
    ssl.keystore.location=/tmp/user.p12 (5)
    ssl.keystore.password=<keystore_password> (6)
    1. The bootstrap server address to connect to the Kafka cluster. Use your own Kafka cluster name to replace <kafka_cluster_name>.

    2. The security protocol option when using TLS for encryption.

    3. The truststore location contains the public key certificate (ca.p12) for the Kafka cluster.

    4. The password (ca.password) for accessing the truststore.

    5. The keystore location contains the public key certificate (user.p12) for the Kafka user.

    6. The password (user.password) for accessing the keystore.

  7. Copy the config.properties file to the interactive pod container.

    kubectl cp config.properties <interactive_pod_name>:/tmp/config.properties
  8. Prepare a JSON file named topics.json that specifies the topics to move.

    Specify topic names as a comma-separated list.

    Example JSON file to reassign all the partitions of topic-a and topic-b
    {
      "version": 1,
      "topics": [
        { "topic": "topic-a"},
        { "topic": "topic-b"}
      ]
    }
  9. Copy the topics.json file to the interactive pod container.

    kubectl cp topics.json <interactive_pod_name>:/tmp/topics.json
  10. Start a shell process in the interactive pod container.

    kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash

    Replace <namespace> with the Kubernetes namespace where the pod is running.

  11. Use the kafka-reassign-partitions.sh command to generate the reassignment JSON.

    Example command to move all the partitions of topic-a and topic-b to brokers 0, 1 and 2
    bin/kafka-reassign-partitions.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --topics-to-move-json-file /tmp/topics.json \
      --broker-list 0,1,2 \
      --generate
Scaling up a Kafka cluster

Use a reassignment file to increase the number of brokers in a Kafka cluster.

The reassignment file should describe how partitions are reassigned to brokers in the enlarged Kafka cluster.

This procedure describes a secure scaling process that uses TLS. You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.

Prerequisites
  • You have a running Kafka cluster based on a Kafka resource configured with internal TLS encryption and mTLS authentication.

  • You have generated a reassignment JSON file named reassignment.json.

  • You are running an interactive pod container that is connected to the running Kafka broker.

  • You are connected as a KafkaUser configured with ACL rules that specify permission to manage the Kafka cluster and its topics.

Procedure
  1. Add as many new brokers as you need by increasing the Kafka.spec.kafka.replicas configuration option.

  2. Verify that the new broker pods have started.

  3. If you haven’t done so, run an interactive pod container to generate a reassignment JSON file named reassignment.json.

  4. Copy the reassignment.json file to the interactive pod container.

    kubectl cp reassignment.json <interactive_pod_name>:/tmp/reassignment.json

    Replace <interactive_pod_name> with the name of the pod.

  5. Start a shell process in the interactive pod container.

    kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash

    Replace <namespace> with the Kubernetes namespace where the pod is running.

  6. Run the partition reassignment using the kafka-reassign-partitions.sh script from the interactive pod container.

    bin/kafka-reassign-partitions.sh --bootstrap-server
     <cluster_name>-kafka-bootstrap:9093 \
     --command-config /tmp/config.properties \
     --reassignment-json-file /tmp/reassignment.json \
     --execute

    Replace <cluster_name> with the name of your Kafka cluster. For example, my-cluster-kafka-bootstrap:9093

    If you are going to throttle replication, you can also pass the --throttle option with an inter-broker throttled rate in bytes per second. For example:

    bin/kafka-reassign-partitions.sh --bootstrap-server
      <cluster_name>-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --reassignment-json-file /tmp/reassignment.json \
      --throttle 5000000 \
      --execute

    This command will print out two reassignment JSON objects. The first records the current assignment for the partitions being moved. You should save this to a local file (not a file in the pod) in case you need to revert the reassignment later on. The second JSON object is the target reassignment you have passed in your reassignment JSON file.

    If you need to change the throttle during reassignment, you can use the same command with a different throttled rate. For example:

    bin/kafka-reassign-partitions.sh --bootstrap-server
      <cluster_name>-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --reassignment-json-file /tmp/reassignment.json \
      --throttle 10000000 \
      --execute
  7. Verify that the reassignment has completed using the kafka-reassign-partitions.sh command line tool from any of the broker pods. This is the same command as the previous step, but with the --verify option instead of the --execute option.

    bin/kafka-reassign-partitions.sh --bootstrap-server
      <cluster_name>-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --reassignment-json-file /tmp/reassignment.json \
      --verify

    The reassignment has finished when the --verify command reports that each of the partitions being moved has completed successfully. This final --verify will also have the effect of removing any reassignment throttles.

  8. You can now delete the revert file if you saved the JSON for reverting the assignment to their original brokers.

Scaling down a Kafka cluster

Use a reassignment file to decrease the number of brokers in a Kafka cluster.

The reassignment file must describe how partitions are reassigned to the remaining brokers in the Kafka cluster. Brokers in the highest numbered pods are removed first.

This procedure describes a secure scaling process that uses TLS. You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.

Prerequisites
  • You have a running Kafka cluster based on a Kafka resource configured with internal TLS encryption and mTLS authentication.

  • You have generated a reassignment JSON file named reassignment.json.

  • You are running an interactive pod container that is connected to the running Kafka broker.

  • You are connected as a KafkaUser configured with ACL rules that specify permission to manage the Kafka cluster and its topics.

Procedure
  1. If you haven’t done so, run an interactive pod container to generate a reassignment JSON file named reassignment.json.

  2. Copy the reassignment.json file to the interactive pod container.

    kubectl cp reassignment.json <interactive_pod_name>:/tmp/reassignment.json

    Replace <interactive_pod_name> with the name of the pod.

  3. Start a shell process in the interactive pod container.

    kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash

    Replace <namespace> with the Kubernetes namespace where the pod is running.

  4. Run the partition reassignment using the kafka-reassign-partitions.sh script from the interactive pod container.

    bin/kafka-reassign-partitions.sh --bootstrap-server
     <cluster_name>-kafka-bootstrap:9093 \
     --command-config /tmp/config.properties \
     --reassignment-json-file /tmp/reassignment.json \
     --execute

    Replace <cluster_name> with the name of your Kafka cluster. For example, my-cluster-kafka-bootstrap:9093

    If you are going to throttle replication, you can also pass the --throttle option with an inter-broker throttled rate in bytes per second. For example:

    bin/kafka-reassign-partitions.sh --bootstrap-server
      <cluster_name>-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --reassignment-json-file /tmp/reassignment.json \
      --throttle 5000000 \
      --execute

    This command will print out two reassignment JSON objects. The first records the current assignment for the partitions being moved. You should save this to a local file (not a file in the pod) in case you need to revert the reassignment later on. The second JSON object is the target reassignment you have passed in your reassignment JSON file.

    If you need to change the throttle during reassignment, you can use the same command with a different throttled rate. For example:

    bin/kafka-reassign-partitions.sh --bootstrap-server
      <cluster_name>-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --reassignment-json-file /tmp/reassignment.json \
      --throttle 10000000 \
      --execute
  5. Verify that the reassignment has completed using the kafka-reassign-partitions.sh command line tool from any of the broker pods. This is the same command as the previous step, but with the --verify option instead of the --execute option.

    bin/kafka-reassign-partitions.sh --bootstrap-server
      <cluster_name>-kafka-bootstrap:9093 \
      --command-config /tmp/config.properties \
      --reassignment-json-file /tmp/reassignment.json \
      --verify

    The reassignment has finished when the --verify command reports that each of the partitions being moved has completed successfully. This final --verify will also have the effect of removing any reassignment throttles.

  6. You can now delete the revert file if you saved the JSON for reverting the assignment to their original brokers.

  7. When all the partition reassignments have finished, the brokers being removed should not have responsibility for any of the partitions in the cluster. You can verify this by checking that the broker’s data log directory does not contain any live partition logs. If the log directory on the broker contains a directory that does not match the extended regular expression [a-zA-Z0-9.-]+\.[a-z0-9]+-delete$, the broker still has live partitions and should not be stopped.

    You can check this by executing the command:

    kubectl exec my-cluster-kafka-0 -c kafka -it -- \
      /bin/bash -c \
      "ls -l /var/lib/kafka/kafka-log_<n>_ | grep -E '^d' | grep -vE '[a-zA-Z0-9.-]+\.[a-z0-9]+-delete$'"

    where n is the number of the pods being deleted.

    If the above command prints any output then the broker still has live partitions. In this case, either the reassignment has not finished or the reassignment JSON file was incorrect.

  8. When you have confirmed that the broker has no live partitions, you can edit the Kafka.spec.kafka.replicas property of your Kafka resource to reduce the number of brokers.

2.1.5. Retrieving JMX metrics with JmxTrans

JmxTrans is a tool for retrieving JMX metrics data from Java processes and pushing that data, in various formats, to remote sinks inside or outside the cluster. JmxTrans can communicate with a secure JMX port.

Important
Support for JmxTrans in Strimzi is deprecated. It is currently planned to be removed in Strimzi 0.35.0.

JmxTrans reads JMX metrics data from secure or insecure Kafka brokers and pushes the data to remote sinks in various data formats. For example, JmxTrans can obtain JMX metrics about the request rate of each Kafka broker’s network and then push the data to a Logstash database outside the Kubernetes cluster.

For more information about JmxTrans, see the JmxTrans GitHub.

Configuring a JmxTrans deployment
Prerequisites
  • A running Kubernetes cluster

You can configure a JmxTrans deployment by using the Kafka.spec.jmxTrans property. A JmxTrans deployment can read from a secure or insecure Kafka broker. To configure a JmxTrans deployment, define the following properties:

  • Kafka.spec.jmxTrans.outputDefinitions

  • Kafka.spec.jmxTrans.kafkaQueries

For more information on these properties, see the JmxTransSpec schema reference.

Configuring JmxTrans output definitions

Output definitions specify where JMX metrics are pushed to, and in which data format. For information about supported data formats, see Data formats. How many seconds JmxTrans agent waits for before pushing new data can be configured through the flushDelay property. The host and port properties define the target host address and target port the data is pushed to. The name property is a required property that is referenced by the Kafka.spec.jmxTrans.kafkaQueries property.

Here is an example configuration pushing JMX data in the Graphite format every 5 seconds to a Logstash database on http://myLogstash:9999, and another pushing to standardOut (standard output):

apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  jmxTrans:
    outputDefinitions:
      - outputType: "com.googlecode.jmxtrans.model.output.GraphiteWriter"
        host: "http://myLogstash"
        port: 9999
        flushDelay: 5
        name: "logstash"
      - outputType: "com.googlecode.jmxtrans.model.output.StdOutWriter"
        name: "standardOut"
        # ...
    # ...
  zookeeper:
    # ...
Configuring JmxTrans queries

JmxTrans queries specify what JMX metrics are read from the Kafka brokers. Currently JmxTrans queries can only be sent to the Kafka Brokers. Configure the targetMBean property to specify which target MBean on the Kafka broker is addressed. Configuring the attributes property specifies which MBean attribute is read as JMX metrics from the target MBean. JmxTrans supports wildcards to read from target MBeans, and filter by specifying the typenames. The outputs property defines where the metrics are pushed to by specifying the name of the output definitions.

The following JmxTrans deployment reads from all MBeans that match the pattern kafka.server:type=BrokerTopicMetrics,name=* and have name in the target MBean’s name. From those Mbeans, it obtains JMX metrics about the Count attribute and pushes the metrics to standard output as defined by outputs.

apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  # ...
  jmxTrans:
    kafkaQueries:
      - targetMBean: "kafka.server:type=BrokerTopicMetrics,*"
        typeNames: ["name"]
        attributes:  ["Count"]
        outputs: ["standardOut"]
  zookeeper:
    # ...

2.1.6. Maintenance time windows for rolling updates

Maintenance time windows allow you to schedule certain rolling updates of your Kafka and ZooKeeper clusters to start at a convenient time.

Maintenance time windows overview

In most cases, the Cluster Operator only updates your Kafka or ZooKeeper clusters in response to changes to the corresponding Kafka resource. This enables you to plan when to apply changes to a Kafka resource to minimize the impact on Kafka client applications.

However, some updates to your Kafka and ZooKeeper clusters can happen without any corresponding change to the Kafka resource. For example, the Cluster Operator will need to perform a rolling restart if a CA (certificate authority) certificate that it manages is close to expiry.

While a rolling restart of the pods should not affect availability of the service (assuming correct broker and topic configurations), it could affect performance of the Kafka client applications. Maintenance time windows allow you to schedule such spontaneous rolling updates of your Kafka and ZooKeeper clusters to start at a convenient time. If maintenance time windows are not configured for a cluster then it is possible that such spontaneous rolling updates will happen at an inconvenient time, such as during a predictable period of high load.

Maintenance time window definition

You configure maintenance time windows by entering an array of strings in the Kafka.spec.maintenanceTimeWindows property. Each string is a cron expression interpreted as being in UTC (Coordinated Universal Time, which for practical purposes is the same as Greenwich Mean Time).

The following example configures a single maintenance time window that starts at midnight and ends at 01:59am (UTC), on Sundays, Mondays, Tuesdays, Wednesdays, and Thursdays:

# ...
maintenanceTimeWindows:
  - "* * 0-1 ? * SUN,MON,TUE,WED,THU *"
# ...

In practice, maintenance windows should be set in conjunction with the Kafka.spec.clusterCa.renewalDays and Kafka.spec.clientsCa.renewalDays properties of the Kafka resource, to ensure that the necessary CA certificate renewal can be completed in the configured maintenance time windows.

Note
Strimzi does not schedule maintenance operations exactly according to the given windows. Instead, for each reconciliation, it checks whether a maintenance window is currently "open". This means that the start of maintenance operations within a given time window can be delayed by up to the Cluster Operator reconciliation interval. Maintenance time windows must therefore be at least this long.
Additional resources
Configuring a maintenance time window

You can configure a maintenance time window for rolling updates triggered by supported processes.

Prerequisites
  • A Kubernetes cluster.

  • The Cluster Operator is running.

Procedure
  1. Add or edit the maintenanceTimeWindows property in the Kafka resource. For example to allow maintenance between 0800 and 1059 and between 1400 and 1559 you would set the maintenanceTimeWindows as shown below:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        # ...
      zookeeper:
        # ...
      maintenanceTimeWindows:
        - "* * 8-10 * * ?"
        - "* * 14-15 * * ?"
  2. Create or update the resource:

    kubectl apply -f <kafka_configuration_file>
Additional resources

Performing rolling updates:

2.1.7. Connecting to ZooKeeper from a terminal

Most Kafka CLI tools can connect directly to Kafka, so under normal circumstances you should not need to connect to ZooKeeper. ZooKeeper services are secured with encryption and authentication and are not intended to be used by external applications that are not part of Strimzi.

However, if you want to use Kafka CLI tools that require a connection to ZooKeeper, you can use a terminal inside a ZooKeeper container and connect to localhost:12181 as the ZooKeeper address.

Prerequisites
  • A Kubernetes cluster is available.

  • A Kafka cluster is running.

  • The Cluster Operator is running.

Procedure
  1. Open the terminal using the Kubernetes console or run the exec command from your CLI.

    For example:

    kubectl exec -ti my-cluster-zookeeper-0 -- bin/kafka-topics.sh --list --zookeeper localhost:12181

    Be sure to use localhost:12181.

    You can now run Kafka commands to ZooKeeper.

2.1.8. Deleting Kafka nodes manually

This procedure describes how to delete an existing Kafka node by using a Kubernetes annotation. Deleting a Kafka node consists of deleting both the Pod on which the Kafka broker is running and the related PersistentVolumeClaim (if the cluster was deployed with persistent storage). After deletion, the Pod and its related PersistentVolumeClaim are recreated automatically.

Warning
Deleting a PersistentVolumeClaim can cause permanent data loss. The following procedure should only be performed if you have encountered storage issues.
Prerequisites

See the Deploying and Upgrading Strimzi guide for instructions on running a:

Procedure
  1. Find the name of the Pod that you want to delete.

    Kafka broker pods are named <cluster-name>-kafka-<index>, where <index> starts at zero and ends at the total number of replicas minus one. For example, my-cluster-kafka-0.

  2. Annotate the Pod resource in Kubernetes.

    Use kubectl annotate:

    kubectl annotate pod cluster-name-kafka-index strimzi.io/delete-pod-and-pvc=true
  3. Wait for the next reconciliation, when the annotated pod with the underlying persistent volume claim will be deleted and then recreated.

2.1.9. Deleting ZooKeeper nodes manually

This procedure describes how to delete an existing ZooKeeper node by using a Kubernetes annotation. Deleting a ZooKeeper node consists of deleting both the Pod on which ZooKeeper is running and the related PersistentVolumeClaim (if the cluster was deployed with persistent storage). After deletion, the Pod and its related PersistentVolumeClaim are recreated automatically.

Warning
Deleting a PersistentVolumeClaim can cause permanent data loss. The following procedure should only be performed if you have encountered storage issues.
Prerequisites

See the Deploying and Upgrading Strimzi guide for instructions on running a:

Procedure
  1. Find the name of the Pod that you want to delete.

    ZooKeeper pods are named <cluster-name>-zookeeper-<index>, where <index> starts at zero and ends at the total number of replicas minus one. For example, my-cluster-zookeeper-0.

  2. Annotate the Pod resource in Kubernetes.

    Use kubectl annotate:

    kubectl annotate pod cluster-name-zookeeper-index strimzi.io/delete-pod-and-pvc=true
  3. Wait for the next reconciliation, when the annotated pod with the underlying persistent volume claim will be deleted and then recreated.

2.1.10. List of Kafka cluster resources

The following resources are created by the Cluster Operator in the Kubernetes cluster:

Shared resources
cluster-name-cluster-ca

Secret with the Cluster CA private key used to encrypt the cluster communication.

cluster-name-cluster-ca-cert

Secret with the Cluster CA public key. This key can be used to verify the identity of the Kafka brokers.

cluster-name-clients-ca

Secret with the Clients CA private key used to sign user certificates

cluster-name-clients-ca-cert

Secret with the Clients CA public key. This key can be used to verify the identity of the Kafka users.

cluster-name-cluster-operator-certs

Secret with Cluster operators keys for communication with Kafka and ZooKeeper.

ZooKeeper nodes
cluster-name-zookeeper

Name given to the following ZooKeeper resources:

  • StatefulSet or StrimziPodSet (if the UseStrimziPodSets feature gate is enabled) for managing the ZooKeeper node pods.

  • Service account used by the ZooKeeper nodes.

  • PodDisruptionBudget configured for the ZooKeeper nodes.

cluster-name-zookeeper-idx

Pods created by the ZooKeeper StatefulSet or StrimziPodSet.

cluster-name-zookeeper-nodes

Headless Service needed to have DNS resolve the ZooKeeper pods IP addresses directly.

cluster-name-zookeeper-client

Service used by Kafka brokers to connect to ZooKeeper nodes as clients.

cluster-name-zookeeper-config

ConfigMap that contains the ZooKeeper ancillary configuration, and is mounted as a volume by the ZooKeeper node pods.

cluster-name-zookeeper-nodes

Secret with ZooKeeper node keys.

cluster-name-network-policy-zookeeper

Network policy managing access to the ZooKeeper services.

data-cluster-name-zookeeper-idx

Persistent Volume Claim for the volume used for storing data for the ZooKeeper node pod idx. This resource will be created only if persistent storage is selected for provisioning persistent volumes to store data.

Kafka brokers
cluster-name-kafka

Name given to the following Kafka resources:

  • StatefulSet or StrimziPodSet (if the UseStrimziPodSets feature gate is enabled) for managing the Kafka broker pods.

  • Service account used by the Kafka pods.

  • PodDisruptionBudget configured for the Kafka brokers.

cluster-name-kafka-idx

Name given to the following Kafka resources:

  • Pods created by the Kafka StatefulSet or StrimziPodSet.

  • ConfigMap with Kafka broker configuration (if the UseStrimziPodSets feature gate is enabled).

cluster-name-kafka-brokers

Service needed to have DNS resolve the Kafka broker pods IP addresses directly.

cluster-name-kafka-bootstrap

Service can be used as bootstrap servers for Kafka clients connecting from within the Kubernetes cluster.

cluster-name-kafka-external-bootstrap

Bootstrap service for clients connecting from outside the Kubernetes cluster. This resource is created only when an external listener is enabled. The old service name will be used for backwards compatibility when the listener name is external and port is 9094.

cluster-name-kafka-pod-id

Service used to route traffic from outside the Kubernetes cluster to individual pods. This resource is created only when an external listener is enabled. The old service name will be used for backwards compatibility when the listener name is external and port is 9094.

cluster-name-kafka-external-bootstrap

Bootstrap route for clients connecting from outside the Kubernetes cluster. This resource is created only when an external listener is enabled and set to type route. The old route name will be used for backwards compatibility when the listener name is external and port is 9094.

cluster-name-kafka-pod-id

Route for traffic from outside the Kubernetes cluster to individual pods. This resource is created only when an external listener is enabled and set to type route. The old route name will be used for backwards compatibility when the listener name is external and port is 9094.

cluster-name-kafka-listener-name-bootstrap

Bootstrap service for clients connecting from outside the Kubernetes cluster. This resource is created only when an external listener is enabled. The new service name will be used for all other external listeners.

cluster-name-kafka-listener-name-pod-id

Service used to route traffic from outside the Kubernetes cluster to individual pods. This resource is created only when an external listener is enabled. The new service name will be used for all other external listeners.

cluster-name-kafka-listener-name-bootstrap

Bootstrap route for clients connecting from outside the Kubernetes cluster. This resource is created only when an external listener is enabled and set to type route. The new route name will be used for all other external listeners.

cluster-name-kafka-listener-name-pod-id

Route for traffic from outside the Kubernetes cluster to individual pods. This resource is created only when an external listener is enabled and set to type route. The new route name will be used for all other external listeners.

cluster-name-kafka-config

ConfigMap which contains the Kafka ancillary configuration and is mounted as a volume by the Kafka broker pods.

cluster-name-kafka-brokers

Secret with Kafka broker keys.

cluster-name-network-policy-kafka

Network policy managing access to the Kafka services.

strimzi-namespace-name-cluster-name-kafka-init

Cluster role binding used by the Kafka brokers.

cluster-name-jmx

Secret with JMX username and password used to secure the Kafka broker port. This resource is created only when JMX is enabled in Kafka.

data-cluster-name-kafka-idx

Persistent Volume Claim for the volume used for storing data for the Kafka broker pod idx. This resource is created only if persistent storage is selected for provisioning persistent volumes to store data.

data-id-cluster-name-kafka-idx

Persistent Volume Claim for the volume id used for storing data for the Kafka broker pod idx. This resource is created only if persistent storage is selected for JBOD volumes when provisioning persistent volumes to store data.

Entity Operator

These resources are only created if the Entity Operator is deployed using the Cluster Operator.

cluster-name-entity-operator

Name given to the following Entity Operator resources:

  • Deployment with Topic and User Operators.

  • Service account used by the Entity Operator.

cluster-name-entity-operator-random-string

Pod created by the Entity Operator deployment.

cluster-name-entity-topic-operator-config

ConfigMap with ancillary configuration for Topic Operators.

cluster-name-entity-user-operator-config

ConfigMap with ancillary configuration for User Operators.

cluster-name-entity-topic-operator-certs

Secret with Topic Operator keys for communication with Kafka and ZooKeeper.

cluster-name-entity-user-operator-certs

Secret with User Operator keys for communication with Kafka and ZooKeeper.

strimzi-cluster-name-entity-topic-operator

Role binding used by the Entity Topic Operator.

strimzi-cluster-name-entity-user-operator

Role binding used by the Entity User Operator.

Kafka Exporter

These resources are only created if the Kafka Exporter is deployed using the Cluster Operator.

cluster-name-kafka-exporter

Name given to the following Kafka Exporter resources:

  • Deployment with Kafka Exporter.

  • Service used to collect consumer lag metrics.

  • Service account used by the Kafka Exporter.

cluster-name-kafka-exporter-random-string

Pod created by the Kafka Exporter deployment.

Cruise Control

These resources are only created if Cruise Control was deployed using the Cluster Operator.

cluster-name-cruise-control

Name given to the following Cruise Control resources:

  • Deployment with Cruise Control.

  • Service used to communicate with Cruise Control.

  • Service account used by the Cruise Control.

cluster-name-cruise-control-random-string

Pod created by the Cruise Control deployment.

cluster-name-cruise-control-config

ConfigMap that contains the Cruise Control ancillary configuration, and is mounted as a volume by the Cruise Control pods.

cluster-name-cruise-control-certs

Secret with Cruise Control keys for communication with Kafka and ZooKeeper.

cluster-name-network-policy-cruise-control

Network policy managing access to the Cruise Control service.

JMXTrans

These resources are only created if JMXTrans is deployed using the Cluster Operator.

cluster-name-jmxtrans

Name given to the following JMXTrans resources:

  • Deployment with JMXTrans.

  • Service account used by the JMXTrans.

cluster-name-jmxtrans-random-string

Pod created by the JMXTrans deployment.

cluster-name-jmxtrans-config

ConfigMap that contains the JMXTrans ancillary configuration, and is mounted as a volume by the JMXTrans pods.

2.2. Kafka Connect cluster configuration

Configure a Kafka Connect deployment using the KafkaConnect resource. Kafka Connect is an integration toolkit for streaming data between Kafka brokers and other systems using connector plugins. Kafka Connect provides a framework for integrating Kafka with an external data source or target, such as a database, for import or export of data using connectors. Connectors are plugins that provide the connection configuration needed.

KafkaConnect schema reference describes the full schema of the KafkaConnect resource.

For more information on deploying connector plugins, see Extending Kafka Connect with connector plugins.

2.2.1. Configuring Kafka Connect

Use Kafka Connect to set up external data connections to your Kafka cluster. Use the properties of the KafkaConnect resource to configure your Kafka Connect deployment.

KafkaConnector configuration

KafkaConnector resources allow you to create and manage connector instances for Kafka Connect in a Kubernetes-native way.

In your Kafka Connect configuration, you enable KafkaConnectors for a Kafka Connect cluster by adding the strimzi.io/use-connector-resources annotation. You can also add a build configuration so that Strimzi automatically builds a container image with the connector plugins you require for your data connections. External configuration for Kafka Connect connectors is specified through the externalConfiguration property.

To manage connectors, you can use use KafkaConnector custom resources or the Kafka Connect REST API. KafkaConnector resources must be deployed to the same namespace as the Kafka Connect cluster they link to. For more information on using these methods to create, reconfigure, or delete connectors, see Adding connectors.

Connector configuration is passed to Kafka Connect as part of an HTTP request and stored within Kafka itself. ConfigMaps and Secrets are standard Kubernetes resources used for storing configurations and confidential data. You can use ConfigMaps and Secrets to configure certain elements of a connector. You can then reference the configuration values in HTTP REST commands, which keeps the configuration separate and more secure, if needed. This method applies especially to confidential data, such as usernames, passwords, or certificates.

Handling high volumes of messages

You can tune the configuration to handle high volumes of messages. For more information, see Handling high volumes of messages.

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

See the Deploying and Upgrading Strimzi guide for instructions on running a:

Procedure
  1. Edit the spec properties of the KafkaConnect resource.

    The properties you can configure are shown in this example configuration:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaConnect (1)
    metadata:
      name: my-connect-cluster
      annotations:
        strimzi.io/use-connector-resources: "true" (2)
    spec:
      replicas: 3 (3)
      authentication: (4)
        type: tls
        certificateAndKey:
          certificate: source.crt
          key: source.key
          secretName: my-user-source
      bootstrapServers: my-cluster-kafka-bootstrap:9092 (5)
      tls: (6)
        trustedCertificates:
          - secretName: my-cluster-cluster-cert
            certificate: ca.crt
          - secretName: my-cluster-cluster-cert
            certificate: ca2.crt
      config: (7)
        group.id: my-connect-cluster
        offset.storage.topic: my-connect-cluster-offsets
        config.storage.topic: my-connect-cluster-configs
        status.storage.topic: my-connect-cluster-status
        key.converter: org.apache.kafka.connect.json.JsonConverter
        value.converter: org.apache.kafka.connect.json.JsonConverter
        key.converter.schemas.enable: true
        value.converter.schemas.enable: true
        config.storage.replication.factor: 3
        offset.storage.replication.factor: 3
        status.storage.replication.factor: 3
      build: (8)
        output: (9)
          type: docker
          image: my-registry.io/my-org/my-connect-cluster:latest
          pushSecret: my-registry-credentials
        plugins: (10)
          - name: debezium-postgres-connector
            artifacts:
              - type: tgz
                url: https://repo1.maven.org/maven2/io/debezium/debezium-connector-postgres/2.1.1.Final/debezium-connector-postgres-2.1.1.Final-plugin.tar.gz
                sha512sum: 962a12151bdf9a5a30627eebac739955a4fd95a08d373b86bdcea2b4d0c27dd6e1edd5cb548045e115e33a9e69b1b2a352bee24df035a0447cb820077af00c03
          - name: camel-telegram
            artifacts:
              - type: tgz
                url: https://repo.maven.apache.org/maven2/org/apache/camel/kafkaconnector/camel-telegram-kafka-connector/0.9.0/camel-telegram-kafka-connector-0.9.0-package.tar.gz
                sha512sum: a9b1ac63e3284bea7836d7d24d84208c49cdf5600070e6bd1535de654f6920b74ad950d51733e8020bf4187870699819f54ef5859c7846ee4081507f48873479
      externalConfiguration: (11)
        env:
          - name: AWS_ACCESS_KEY_ID
            valueFrom:
              secretKeyRef:
                name: aws-creds
                key: awsAccessKey
          - name: AWS_SECRET_ACCESS_KEY
            valueFrom:
              secretKeyRef:
                name: aws-creds
                key: awsSecretAccessKey
      resources: (12)
        requests:
          cpu: "1"
          memory: 2Gi
        limits:
          cpu: "2"
          memory: 2Gi
      logging: (13)
        type: inline
        loggers:
          log4j.rootLogger: "INFO"
      readinessProbe: (14)
        initialDelaySeconds: 15
        timeoutSeconds: 5
      livenessProbe:
        initialDelaySeconds: 15
        timeoutSeconds: 5
      metricsConfig: (15)
        type: jmxPrometheusExporter
        valueFrom:
          configMapKeyRef:
            name: my-config-map
            key: my-key
      jvmOptions: (16)
        "-Xmx": "1g"
        "-Xms": "1g"
      image: my-org/my-image:latest (17)
      rack:
        topologyKey: topology.kubernetes.io/zone (18)
      template: (19)
        pod:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: application
                        operator: In
                        values:
                          - postgresql
                          - mongodb
                  topologyKey: "kubernetes.io/hostname"
        connectContainer: (20)
          env:
            - name: JAEGER_SERVICE_NAME
              value: my-jaeger-service
            - name: JAEGER_AGENT_HOST
              value: jaeger-agent-name
            - name: JAEGER_AGENT_PORT
              value: "6831"
    1. Use KafkaConnect.

    2. Enables KafkaConnectors for the Kafka Connect cluster.

    3. The number of replica nodes for the workers that run tasks.

    4. Authentication for the Kafka Connect cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN. By default, Kafka Connect connects to Kafka brokers using a plain text connection.

    5. Bootstrap server for connection to the Kafka Connect cluster.

    6. TLS encryption with key names under which TLS certificates are stored in X.509 format for the cluster. If certificates are stored in the same secret, it can be listed multiple times.

    7. Kafka Connect configuration of workers (not connectors). Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.

    8. Build configuration properties for building a container image with connector plugins automatically.

    9. (Required) Configuration of the container registry where new images are pushed.

    10. (Required) List of connector plugins and their artifacts to add to the new container image. Each plugin must be configured with at least one artifact.

    11. External configuration for Kafka connectors using environment variables, as shown here, or volumes. You can also use configuration provider plugins to load configuration values from external sources.

    12. Requests for reservation of supported resources, currently cpu and memory, and limits to specify the maximum resources that can be consumed.

    13. Specified Kafka Connect loggers and log levels added directly (inline) or indirectly (external) through a ConfigMap. A custom ConfigMap must be placed under the log4j.properties or log4j2.properties key. For the Kafka Connect log4j.rootLogger logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.

    14. Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).

    15. Prometheus metrics, which are enabled by referencing a ConfigMap containing configuration for the Prometheus JMX exporter in this example. You can enable metrics without further configuration using a reference to a ConfigMap containing an empty file under metricsConfig.valueFrom.configMapKeyRef.key.

    16. JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka Connect.

    17. ADVANCED OPTION: Container image configuration, which is recommended only in special situations.

    18. SPECIALIZED OPTION: Rack awareness configuration for the deployment. This is a specialized option intended for a deployment within the same location, not across regions. Use this option if you want connectors to consume from the closest replica rather than the leader replica. In certain cases, consuming from the closest replica can improve network utilization or reduce costs . The topologyKey must match a node label containing the rack ID. The example used in this configuration specifies a zone using the standard topology.kubernetes.io/zone label. To consume from the closest replica, enable the RackAwareReplicaSelector in the Kafka broker configuration.

    19. Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.

    20. Environment variables are set for distributed tracing.

  2. Create or update the resource:

    kubectl apply -f KAFKA-CONNECT-CONFIG-FILE
  3. If authorization is enabled for Kafka Connect, configure Kafka Connect users to enable access to the Kafka Connect consumer group and topics.

Additional resources

2.2.2. Configuring Kafka Connect for multiple instances

If you are running multiple instances of Kafka Connect, you have to change the default configuration of the following config properties:

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
  name: my-connect
spec:
  # ...
  config:
    group.id: connect-cluster (1)
    offset.storage.topic: connect-cluster-offsets (2)
    config.storage.topic: connect-cluster-configs (3)
    status.storage.topic: connect-cluster-status  (4)
    # ...
# ...
  1. The Kafka Connect cluster ID within Kafka.

  2. Kafka topic that stores connector offsets.

  3. Kafka topic that stores connector and task status configurations.

  4. Kafka topic that stores connector and task status updates.

Note
Values for the three topics must be the same for all Kafka Connect instances with the same group.id.

Unless you change the default settings, each Kafka Connect instance connecting to the same Kafka cluster is deployed with the same values. What happens, in effect, is all instances are coupled to run in a cluster and use the same topics.

If multiple Kafka Connect clusters try to use the same topics, Kafka Connect will not work as expected and generate errors.

If you wish to run multiple Kafka Connect instances, change the values of these properties for each instance.

2.2.3. Configuring Kafka Connect user authorization

This procedure describes how to authorize user access to Kafka Connect.

When any type of authorization is being used in Kafka, a Kafka Connect user requires read/write access rights to the consumer group and the internal topics of Kafka Connect.

The properties for the consumer group and internal topics are automatically configured by Strimzi, or they can be specified explicitly in the spec of the KafkaConnect resource.

Example configuration properties in the KafkaConnect resource
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
  name: my-connect
spec:
  # ...
  config:
    group.id: my-connect-cluster (1)
    offset.storage.topic: my-connect-cluster-offsets (2)
    config.storage.topic: my-connect-cluster-configs (3)
    status.storage.topic: my-connect-cluster-status (4)
    # ...
  # ...
  1. The Kafka Connect cluster ID within Kafka.

  2. Kafka topic that stores connector offsets.

  3. Kafka topic that stores connector and task status configurations.

  4. Kafka topic that stores connector and task status updates.

This procedure shows how access is provided when simple authorization is being used.

Simple authorization uses ACL rules, handled by the Kafka AclAuthorizer plugin, to provide the right level of access. For more information on configuring a KafkaUser resource to use simple authorization, see the AclRule schema reference.

Note
The default values for the consumer group and topics will differ when running multiple instances.
Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

Procedure
  1. Edit the authorization property in the KafkaUser resource to provide access rights to the user.

    In the following example, access rights are configured for the Kafka Connect topics and consumer group using literal name values:

    Property Name

    offset.storage.topic

    connect-cluster-offsets

    status.storage.topic

    connect-cluster-status

    config.storage.topic

    connect-cluster-configs

    group

    connect-cluster

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaUser
    metadata:
      name: my-user
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      # ...
      authorization:
        type: simple
        acls:
          # access to offset.storage.topic
          - resource:
              type: topic
              name: connect-cluster-offsets
              patternType: literal
            operations:
              - Create
              - Describe
              - Read
              - Write
            host: "*"
          # access to status.storage.topic
          - resource:
              type: topic
              name: connect-cluster-status
              patternType: literal
            operations:
              - Create
              - Describe
              - Read
              - Write
            host: "*"
          # access to config.storage.topic
          - resource:
              type: topic
              name: connect-cluster-configs
              patternType: literal
            operations:
              - Create
              - Describe
              - Read
              - Write
            host: "*"
          # consumer group
          - resource:
              type: group
              name: connect-cluster
              patternType: literal
            operations:
              - Read
            host: "*"
  2. Create or update the resource.

    kubectl apply -f KAFKA-USER-CONFIG-FILE

2.2.4. List of Kafka Connect cluster resources

The following resources are created by the Cluster Operator in the Kubernetes cluster:

connect-cluster-name-connect

Deployment which is in charge to create the Kafka Connect worker node pods.

connect-cluster-name-connect-api

Service which exposes the REST interface for managing the Kafka Connect cluster.

connect-cluster-name-config

ConfigMap which contains the Kafka Connect ancillary configuration and is mounted as a volume by the Kafka broker pods.

connect-cluster-name-connect

Pod Disruption Budget configured for the Kafka Connect worker nodes.

2.3. Kafka MirrorMaker 2.0 cluster configuration

Configure a Kafka MirrorMaker 2.0 deployment using the KafkaMirrorMaker2 resource. MirrorMaker 2.0 replicates data between two or more Kafka clusters, within or across data centers.

KafkaMirrorMaker2 schema reference describes the full schema of the KafkaMirrorMaker2 resource.

MirrorMaker 2.0 resource configuration differs from the previous version of MirrorMaker. If you choose to use MirrorMaker 2.0, there is currently no legacy support, so any resources must be manually converted into the new format.

2.3.1. MirrorMaker 2.0 data replication

Data replication across clusters supports scenarios that require:

  • Recovery of data in the event of a system failure

  • Aggregation of data for analysis

  • Restriction of data access to a specific cluster

  • Provision of data at a specific location to improve latency

MirrorMaker 2.0 configuration

MirrorMaker 2.0 consumes messages from a source Kafka cluster and writes them to a target Kafka cluster.

MirrorMaker 2.0 uses:

  • Source cluster configuration to consume data from the source cluster

  • Target cluster configuration to output data to the target cluster

MirrorMaker 2.0 is based on the Kafka Connect framework, connectors managing the transfer of data between clusters.

You configure MirrorMaker 2.0 to define the Kafka Connect deployment, including the connection details of the source and target clusters, and then run a set of MirrorMaker 2.0 connectors to make the connection.

MirrorMaker 2.0 consists of the following connectors:

MirrorSourceConnector

The source connector replicates topics from a source cluster to a target cluster. It also replicates ACLs and is necessary for the MirrorCheckpointConnector to run.

MirrorCheckpointConnector

The checkpoint connector periodically tracks offsets. If enabled, it also synchronizes consumer group offsets between the source and target cluster.

MirrorHeartbeatConnector

The heartbeat connector periodically checks connectivity between the source and target cluster.

Note
If you are using the User Operator to manage ACLs, ACL replication through the connector is not possible.

The process of mirroring data from a source cluster to a target cluster is asynchronous. Each MirrorMaker 2.0 instance mirrors data from one source cluster to one target cluster. You can use more than one MirrorMaker 2.0 instance to mirror data between any number of clusters.

MirrorMaker 2.0 replication
Figure 1. Replication across two clusters

By default, a check for new topics in the source cluster is made every 10 minutes. You can change the frequency by adding refresh.topics.interval.seconds to the source connector configuration.

Cluster configuration

You can use MirrorMaker 2.0 in active/passive or active/active cluster configurations.

active/active cluster configuration

An active/active configuration has two active clusters replicating data bidirectionally. Applications can use either cluster. Each cluster can provide the same data. In this way, you can make the same data available in different geographical locations. As consumer groups are active in both clusters, consumer offsets for replicated topics are not synchronized back to the source cluster.

active/passive cluster configuration

An active/passive configuration has an active cluster replicating data to a passive cluster. The passive cluster remains on standby. You might use the passive cluster for data recovery in the event of system failure.

The expectation is that producers and consumers connect to active clusters only. A MirrorMaker 2.0 cluster is required at each target destination.

Bidirectional replication (active/active)

The MirrorMaker 2.0 architecture supports bidirectional replication in an active/active cluster configuration.

Each cluster replicates the data of the other cluster using the concept of source and remote topics. As the same topics are stored in each cluster, remote topics are automatically renamed by MirrorMaker 2.0 to represent the source cluster. The name of the originating cluster is prepended to the name of the topic.

MirrorMaker 2.0 bidirectional architecture
Figure 2. Topic renaming

By flagging the originating cluster, topics are not replicated back to that cluster.

The concept of replication through remote topics is useful when configuring an architecture that requires data aggregation. Consumers can subscribe to source and remote topics within the same cluster, without the need for a separate aggregation cluster.

Unidirectional replication (active/passive)

The MirrorMaker 2.0 architecture supports unidirectional replication in an active/passive cluster configuration.

You can use an active/passive cluster configuration to make backups or migrate data to another cluster. In this situation, you might not want automatic renaming of remote topics.

You can override automatic renaming by adding IdentityReplicationPolicy to the source connector configuration. With this configuration applied, topics retain their original names.

Topic configuration synchronization

MirrorMaker 2.0 supports topic configuration synchronization between source and target clusters. You specify source topics in the MirrorMaker 2.0 configuration. MirrorMaker 2.0 monitors the source topics. MirrorMaker 2.0 detects and propagates changes to the source topics to the remote topics. Changes might include automatically creating missing topics and partitions.

Note
In most cases you write to local topics and read from remote topics. Though write operations are not prevented on remote topics, they should be avoided.
Offset tracking

MirrorMaker 2.0 tracks offsets for consumer groups using internal topics.

offset-syncs topic

The offset-syncs topic maps the source and target offsets for replicated topic partitions from record metadata.

checkpoints topic

The checkpoints topic maps the last committed offset in the source and target cluster for replicated topic partitions in each consumer group.

As they used internally by MirrorMaker 2.0, you do not interact directly with these topics.

MirrorCheckpointConnector emits checkpoints for offset tracking. Offsets for the checkpoints topic are tracked at predetermined intervals through configuration. Both topics enable replication to be fully restored from the correct offset position on failover.

The location of the offset-syncs topic is the source cluster by default. You can use the offset-syncs.topic.location connector configuration to change this to the target cluster. You need read/write access to the cluster that contains the topic. Using the target cluster as the location of the offset-syncs topic allows you to use MirrorMaker 2.0 even if you have only read access to the source cluster.

Synchronizing consumer group offsets

The __consumer_offsets topic stores information on committed offsets for each consumer group. Offset synchronization periodically transfers the consumer offsets for the consumer groups of a source cluster into the consumer offsets topic of a target cluster.

Offset synchronization is particularly useful in an active/passive configuration. If the active cluster goes down, consumer applications can switch to the passive (standby) cluster and pick up from the last transferred offset position.

To use topic offset synchronization, enable the synchronization by adding sync.group.offsets.enabled to the checkpoint connector configuration, and setting the property to true. Synchronization is disabled by default.

When using the IdentityReplicationPolicy in the source connector, it also has to be configured in the checkpoint connector configuration. This ensures that the mirrored consumer offsets will be applied for the correct topics.

Consumer offsets are only synchronized for consumer groups that are not active in the target cluster. If the consumer groups are in the target cluster, the synchronization cannot be performed and an UNKNOWN_MEMBER_ID error is returned.

If enabled, the synchronization of offsets from the source cluster is made periodically. You can change the frequency by adding sync.group.offsets.interval.seconds and emit.checkpoints.interval.seconds to the checkpoint connector configuration. The properties specify the frequency in seconds that the consumer group offsets are synchronized, and the frequency of checkpoints emitted for offset tracking. The default for both properties is 60 seconds. You can also change the frequency of checks for new consumer groups using the refresh.groups.interval.seconds property, which is performed every 10 minutes by default.

Because the synchronization is time-based, any switchover by consumers to a passive cluster will likely result in some duplication of messages.

Note
If you have an application written in Java, you can use the RemoteClusterUtils.java utility to synchronize offsets through the application. The utility fetches remote offsets for a consumer group from the checkpoints topic.
Connectivity checks

MirrorHeartbeatConnector emits heartbeats to check connectivity between clusters.

An internal heartbeat topic is replicated from the source cluster. Target clusters use the heartbeat topic to check the following:

  • The connector managing connectivity between clusters is running

  • The source cluster is available

2.3.2. Connector configuration

Use Mirrormaker 2.0 connector configuration for the internal connectors that orchestrate the synchronization of data between Kafka clusters.

The following table describes connector properties and the connectors you configure to use them.

Table 1. MirrorMaker 2.0 connector configuration properties
Property sourceConnector checkpointConnector heartbeatConnector
admin.timeout.ms

Timeout for admin tasks, such as detecting new topics. Default is 60000 (1 minute).

replication.policy.class

Policy to define the remote topic naming convention. Default is org.apache.kafka.connect.mirror.DefaultReplicationPolicy.

replication.policy.separator

The separator used for topic naming in the target cluster. Default is . (dot). It is only used when the replication.policy.class is the DefaultReplicationPolicy.

consumer.poll.timeout.ms

Timeout when polling the source cluster. Default is 1000 (1 second).

offset-syncs.topic.location

The location of the offset-syncs topic, which can be the source (default) or target cluster.

topic.filter.class

Topic filter to select the topics to replicate. Default is org.apache.kafka.connect.mirror.DefaultTopicFilter.

config.property.filter.class

Topic filter to select the topic configuration properties to replicate. Default is org.apache.kafka.connect.mirror.DefaultConfigPropertyFilter.

config.properties.exclude

Topic configuration properties that should not be replicated. Supports comma-separated property names and regular expressions.

offset.lag.max

Maximum allowable (out-of-sync) offset lag before a remote partition is synchronized. Default is 100.

offset-syncs.topic.replication.factor

Replication factor for the internal offset-syncs topic. Default is 3.

refresh.topics.enabled

Enables check for new topics and partitions. Default is true.

refresh.topics.interval.seconds

Frequency of topic refresh. Default is 600 (10 minutes).

replication.factor

The replication factor for new topics. Default is 2.

sync.topic.acls.enabled

Enables synchronization of ACLs from the source cluster. Default is true. Not compatible with the User Operator.

sync.topic.acls.interval.seconds

Frequency of ACL synchronization. Default is 600 (10 minutes).

sync.topic.configs.enabled

Enables synchronization of topic configuration from the source cluster. Default is true.

sync.topic.configs.interval.seconds

Frequency of topic configuration synchronization. Default 600 (10 minutes).

checkpoints.topic.replication.factor

Replication factor for the internal checkpoints topic. Default is 3.

emit.checkpoints.enabled

Enables synchronization of consumer offsets to the target cluster. Default is true.

emit.checkpoints.interval.seconds

Frequency of consumer offset synchronization. Default is 60 (1 minute).

group.filter.class

Group filter to select the consumer groups to replicate. Default is org.apache.kafka.connect.mirror.DefaultGroupFilter.

refresh.groups.enabled

Enables check for new consumer groups. Default is true.

refresh.groups.interval.seconds

Frequency of consumer group refresh. Default is 600 (10 minutes).

sync.group.offsets.enabled

Enables synchronization of consumer group offsets to the target cluster __consumer_offsets topic. Default is false.

sync.group.offsets.interval.seconds

Frequency of consumer group offset synchronization. Default is 60 (1 minute).

emit.heartbeats.enabled

Enables connectivity checks on the target cluster. Default is true.

emit.heartbeats.interval.seconds

Frequency of connectivity checks. Default is 1 (1 second).

heartbeats.topic.replication.factor

Replication factor for the internal heartbeats topic. Default is 3.

2.3.3. Connector producer and consumer configuration

MirrorMaker 2.0 connectors use internal producers and consumers. If needed, you can configure these producers and consumers to override the default settings.

For example, you can increase the batch.size for the source producer that sends topics to the target Kafka cluster to better accommodate large volumes of messages.

Important
Producer and consumer configuration options depend on the MirrorMaker 2.0 implementation, and may be subject to change.

The following tables describe the producers and consumers for each of the connectors and where you can add configuration.

Table 2. Source connector producers and consumers
Type Description Configuration

Producer

Sends topic messages to the target Kafka cluster. Consider tuning the configuration of this producer when it is handling large volumes of data.

mirrors.sourceConnector.config: producer.override.*

Producer

Writes to the offset-syncs topic, which maps the source and target offsets for replicated topic partitions.

mirrors.sourceConnector.config: producer.*

Consumer

Retrieves topic messages from the source Kafka cluster.

mirrors.sourceConnector.config: consumer.*

Table 3. Checkpoint connector producers and consumers
Type Description Configuration

Producer

Emits consumer offset checkpoints.

mirrors.checkpointConnector.config: producer.override.*

Consumer

Loads the offset-syncs topic.

mirrors.checkpointConnector.config: consumer.*

Note
You can set offset-syncs.topic.location to target to use the target Kafka cluster as the location of the offset-syncs topic.
Table 4. Heartbeat connector producer
Type Description Configuration

Producer

Emits heartbeats.

mirrors.heartbeatConnector.config: producer.override.*

The following example shows how you configure the producers and consumers.

Example configuration for connector producers and consumers
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
  name: my-mirror-maker2
spec:
  version: 3.3.2
  # ...
  mirrors:
  - sourceCluster: "my-cluster-source"
    targetCluster: "my-cluster-target"
    sourceConnector:
      tasksMax: 5
      config:
        producer.override.batch.size: 327680
        producer.override.linger.ms: 100
        producer.request.timeout.ms: 30000
        consumer.fetch.max.bytes: 52428800
        # ...
    checkpointConnector:
      config:
        producer.override.request.timeout.ms: 30000
        consumer.max.poll.interval.ms: 300000
        # ...
    heartbeatConnector:
      config:
        producer.override.request.timeout.ms: 30000
        # ...

2.3.4. Specifying a maximum number of tasks

Connectors create the tasks that are responsible for moving data in and out of Kafka. Each connector comprises one or more tasks that are distributed across a group of worker pods that run the tasks. Increasing the number of tasks can help with performance issues when replicating a large number of partitions or synchronizing the offsets of a large number of consumer groups.

Tasks run in parallel. Workers are assigned one or more tasks. A single task is handled by one worker pod, so you don’t need more worker pods than tasks. If there are more tasks than workers, workers handle multiple tasks.

You can specify the maximum number of connector tasks in your MirrorMaker configuration using the tasksMax property. Without specifying a maximum number of tasks, the default setting is a single task.

The heartbeat connector always uses a single task.

The number of tasks that are started for the source and checkpoint connectors is the lower value between the maximum number of possible tasks and the value for tasksMax. For the source connector, the maximum number of tasks possible is one for each partition being replicated from the source cluster. For the checkpoint connector, the maximum number of tasks possible is one for each consumer group being replicated from the source cluster. When setting a maximum number of tasks, consider the number of partitions and the hardware resources that support the process.

If the infrastructure supports the processing overhead, increasing the number of tasks can improve throughput and latency. For example, adding more tasks reduces the time taken to poll the source cluster when there is a high number of partitions or consumer groups.

Increasing the number of tasks for the checkpoint connector is useful when you have a large number of partitions.

Increasing the number of tasks for the source connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
  name: my-mirror-maker2
spec:
  # ...
  mirrors:
  - sourceCluster: "my-cluster-source"
    targetCluster: "my-cluster-target"
    sourceConnector:
      tasksMax: 10
  # ...

Increasing the number of tasks for the checkpoint connector is useful when you have a large number of consumer groups.

Increasing the number of tasks for the checkpoint connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
  name: my-mirror-maker2
spec:
  # ...
  mirrors:
  - sourceCluster: "my-cluster-source"
    targetCluster: "my-cluster-target"
    checkpointConnector:
      tasksMax: 10
  # ...

By default, MirrorMaker 2.0 checks for new consumer groups every 10 minutes. You can adjust the refresh.groups.interval.seconds configuration to change the frequency. Take care when adjusting lower. More frequent checks can have a negative impact on performance.

Checking connector task operations

If you are using Prometheus and Grafana to monitor your deployment, you can check MirrorMaker 2.0 performance. The example MirrorMaker 2.0 Grafana dashboard provided with Strimzi shows the following metrics related to tasks and latency.

  • The number of tasks

  • Replication latency

  • Offset synchronization latency

Additional resources

2.3.5. ACL rules synchronization

ACL access to remote topics is possible if you are not using the User Operator.

If AclAuthorizer is being used, without the User Operator, ACL rules that manage access to brokers also apply to remote topics. Users that can read a source topic can read its remote equivalent.

Note
OAuth 2.0 authorization does not support access to remote topics in this way.

2.3.6. Configuring Kafka MirrorMaker 2.0

Use the properties of the KafkaMirrorMaker2 resource to configure your Kafka MirrorMaker 2.0 deployment. Use MirrorMaker 2.0 to synchronize data between Kafka clusters.

The configuration must specify:

  • Each Kafka cluster

  • Connection information for each cluster, including authentication

  • The replication flow and direction

    • Cluster to cluster

    • Topic to topic

Note
The previous version of MirrorMaker continues to be supported. If you wish to use the resources configured for the previous version, they must be updated to the format supported by MirrorMaker 2.0.

MirrorMaker 2.0 provides default configuration values for properties such as replication factors. A minimal configuration, with defaults left unchanged, would be something like this example:

Minimal configuration for MirrorMaker 2.0
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
  name: my-mirror-maker2
spec:
  version: 3.3.2
  connectCluster: "my-cluster-target"
  clusters:
  - alias: "my-cluster-source"
    bootstrapServers: my-cluster-source-kafka-bootstrap:9092
  - alias: "my-cluster-target"
    bootstrapServers: my-cluster-target-kafka-bootstrap:9092
  mirrors:
  - sourceCluster: "my-cluster-source"
    targetCluster: "my-cluster-target"
    sourceConnector: {}

You can configure access control for source and target clusters using mTLS or SASL authentication. This procedure shows a configuration that uses TLS encryption and mTLS authentication for the source and target cluster.

You can specify the topics and consumer groups you wish to replicate from a source cluster in the KafkaMirrorMaker2 resource. You use the topicsPattern and groupsPattern properties to do this. You can provide a list of names or use a regular expression. By default, all topics and consumer groups are replicated if you do not set the topicsPattern and groupsPattern properties. You can also replicate all topics and consumer groups by using ".*" as a regular expression. However, try to specify only the topics and consumer groups you need to avoid causing any unnecessary extra load on the cluster.

Handling high volumes of messages

You can tune the configuration to handle high volumes of messages. For more information, see Handling high volumes of messages.

Prerequisites
  • Strimzi is running

  • Source and target Kafka clusters are available

Procedure
  1. Edit the spec properties for the KafkaMirrorMaker2 resource.

    The properties you can configure are shown in this example configuration:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaMirrorMaker2
    metadata:
      name: my-mirror-maker2
    spec:
      version: 3.3.2 # (1)
      replicas: 3 # (2)
      connectCluster: "my-cluster-target" # (3)
      clusters: # (4)
      - alias: "my-cluster-source" # (5)
        authentication: # (6)
          certificateAndKey:
            certificate: source.crt
            key: source.key
            secretName: my-user-source
          type: tls
        bootstrapServers: my-cluster-source-kafka-bootstrap:9092 # (7)
        tls: # (8)
          trustedCertificates:
          - certificate: ca.crt
            secretName: my-cluster-source-cluster-ca-cert
      - alias: "my-cluster-target" # (9)
        authentication: # (10)
          certificateAndKey:
            certificate: target.crt
            key: target.key
            secretName: my-user-target
          type: tls
        bootstrapServers: my-cluster-target-kafka-bootstrap:9092 # (11)
        config: # (12)
          config.storage.replication.factor: 1
          offset.storage.replication.factor: 1
          status.storage.replication.factor: 1
          ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" # (13)
          ssl.enabled.protocols: "TLSv1.2"
          ssl.protocol: "TLSv1.2"
          ssl.endpoint.identification.algorithm: HTTPS # (14)
        tls: # (15)
          trustedCertificates:
          - certificate: ca.crt
            secretName: my-cluster-target-cluster-ca-cert
      mirrors: # (16)
      - sourceCluster: "my-cluster-source" # (17)
        targetCluster: "my-cluster-target" # (18)
        sourceConnector: # (19)
          tasksMax: 10 # (20)
          autoRestart: # (21)
            enabled: true
          config:
            replication.factor: 1 # (22)
            offset-syncs.topic.replication.factor: 1 # (23)
            sync.topic.acls.enabled: "false" # (24)
            refresh.topics.interval.seconds: 60 # (25)
            replication.policy.separator: "" # (26)
            replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy" # (27)
        heartbeatConnector: # (28)
          autoRestart:
            enabled: true
          config:
            heartbeats.topic.replication.factor: 1 # (29)
        checkpointConnector: # (30)
          autoRestart:
            enabled: true
          config:
            checkpoints.topic.replication.factor: 1 # (31)
            refresh.groups.interval.seconds: 600 # (32)
            sync.group.offsets.enabled: true # (33)
            sync.group.offsets.interval.seconds: 60 # (34)
            emit.checkpoints.interval.seconds: 60 # (35)
            replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"
        topicsPattern: "topic1|topic2|topic3" # (36)
        groupsPattern: "group1|group2|group3" # (37)
      resources: # (38)
        requests:
          cpu: "1"
          memory: 2Gi
        limits:
          cpu: "2"
          memory: 2Gi
      logging: # (39)
        type: inline
        loggers:
          connect.root.logger.level: "INFO"
      readinessProbe: # (40)
        initialDelaySeconds: 15
        timeoutSeconds: 5
      livenessProbe:
        initialDelaySeconds: 15
        timeoutSeconds: 5
      jvmOptions: # (41)
        "-Xmx": "1g"
        "-Xms": "1g"
      image: my-org/my-image:latest # (42)
      rack:
        topologyKey: topology.kubernetes.io/zone # (43)
      template: # (44)
        pod:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: application
                        operator: In
                        values:
                          - postgresql
                          - mongodb
                  topologyKey: "kubernetes.io/hostname"
        connectContainer: # (45)
          env:
            - name: JAEGER_SERVICE_NAME
              value: my-jaeger-service
            - name: JAEGER_AGENT_HOST
              value: jaeger-agent-name
            - name: JAEGER_AGENT_PORT
              value: "6831"
      tracing:
        type: jaeger # (46)
      externalConfiguration: # (47)
        env:
          - name: AWS_ACCESS_KEY_ID
            valueFrom:
              secretKeyRef:
                name: aws-creds
                key: awsAccessKey
          - name: AWS_SECRET_ACCESS_KEY
            valueFrom:
              secretKeyRef:
                name: aws-creds
                key: awsSecretAccessKey
    1. The Kafka Connect and Mirror Maker 2.0 version, which will always be the same.

    2. The number of replica nodes for the workers that run tasks.

    3. Kafka cluster alias for Kafka Connect, which must specify the target Kafka cluster. The Kafka cluster is used by Kafka Connect for its internal topics.

    4. Specification for the Kafka clusters being synchronized.

    5. Cluster alias for the source Kafka cluster.

    6. Authentication for the source cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.

    7. Bootstrap server for connection to the source Kafka cluster.

    8. TLS encryption with key names under which TLS certificates are stored in X.509 format for the source Kafka cluster. If certificates are stored in the same secret, it can be listed multiple times.

    9. Cluster alias for the target Kafka cluster.

    10. Authentication for the target Kafka cluster is configured in the same way as for the source Kafka cluster.

    11. Bootstrap server for connection to the target Kafka cluster.

    12. Kafka Connect configuration. Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.

    13. SSL properties for external listeners to run with a specific cipher suite for a TLS version.

    14. Hostname verification is enabled by setting to HTTPS. An empty string disables the verification.

    15. TLS encryption for the target Kafka cluster is configured in the same way as for the source Kafka cluster.

    16. MirrorMaker 2.0 connectors.

    17. Cluster alias for the source cluster used by the MirrorMaker 2.0 connectors.

    18. Cluster alias for the target cluster used by the MirrorMaker 2.0 connectors.

    19. Configuration for the MirrorSourceConnector that creates remote topics. The config overrides the default configuration options.

    20. The maximum number of tasks that the connector may create. Tasks handle the data replication and run in parallel. If the infrastructure supports the processing overhead, increasing this value can improve throughput. Kafka Connect distributes the tasks between members of the cluster. If there are more tasks than workers, workers are assigned multiple tasks. For sink connectors, aim to have one task for each topic partition consumed. For source connectors, the number of tasks that can run in parallel may also depend on the external system. The connector creates fewer than the maximum number of tasks if it cannot achieve the parallelism.

    21. Enables automatic restarts of failed connectors and tasks. Up to seven restart attempts are made, after which restarts must be made manually.

    22. Replication factor for mirrored topics created at the target cluster.

    23. Replication factor for the MirrorSourceConnector offset-syncs internal topic that maps the offsets of the source and target clusters.

    24. When ACL rules synchronization is enabled, ACLs are applied to synchronized topics. The default is true. This feature is not compatible with the User Operator. If you are using the User Operator, set this property to false.

    25. Optional setting to change the frequency of checks for new topics. The default is for a check every 10 minutes.

    26. Defines the separator used for the renaming of remote topics.

    27. Adds a policy that overrides the automatic renaming of remote topics. Instead of prepending the name with the name of the source cluster, the topic retains its original name. This optional setting is useful for active/passive backups and data migration. To configure topic offset synchronization, this property must also be set for the checkpointConnector.config.

    28. Configuration for the MirrorHeartbeatConnector that performs connectivity checks. The config overrides the default configuration options.

    29. Replication factor for the heartbeat topic created at the target cluster.

    30. Configuration for the MirrorCheckpointConnector that tracks offsets. The config overrides the default configuration options.

    31. Replication factor for the checkpoints topic created at the target cluster.

    32. Optional setting to change the frequency of checks for new consumer groups. The default is for a check every 10 minutes.

    33. Optional setting to synchronize consumer group offsets, which is useful for recovery in an active/passive configuration. Synchronization is not enabled by default.

    34. If the synchronization of consumer group offsets is enabled, you can adjust the frequency of the synchronization.

    35. Adjusts the frequency of checks for offset tracking. If you change the frequency of offset synchronization, you might also need to adjust the frequency of these checks.

    36. Topic replication from the source cluster defined as a comma-separated list or regular expression pattern. The source connector replicates the specified topics. The checkpoint connector tracks offsets for the specified topics. Here we request three topics by name.

    37. Consumer group replication from the source cluster defined as a comma-separated list or regular expression pattern. The checkpoint connector replicates the specified consumer groups. Here we request three consumer groups by name.

    38. Requests for reservation of supported resources, currently cpu and memory, and limits to specify the maximum resources that can be consumed.

    39. Specified Kafka Connect loggers and log levels added directly (inline) or indirectly (external) through a ConfigMap. A custom ConfigMap must be placed under the log4j.properties or log4j2.properties key. For the Kafka Connect log4j.rootLogger logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.

    40. Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).

    41. JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka MirrorMaker.

    42. ADVANCED OPTION: Container image configuration, which is recommended only in special situations.

    43. SPECIALIZED OPTION: Rack awareness configuration for the deployment. This is a specialized option intended for a deployment within the same location, not across regions. Use this option if you want connectors to consume from the closest replica rather than the leader replica. In certain cases, consuming from the closest replica can improve network utilization or reduce costs . The topologyKey must match a node label containing the rack ID. The example used in this configuration specifies a zone using the standard topology.kubernetes.io/zone label. To consume from the closest replica, enable the RackAwareReplicaSelector in the Kafka broker configuration.

    44. Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.

    45. Environment variables are set for distributed tracing.

    46. Distributed tracing is enabled for Jaeger.

    47. External configuration for a Kubernetes Secret mounted to Kafka MirrorMaker as an environment variable. You can also use configuration provider plugins to load configuration values from external sources.

  2. Create or update the resource:

    kubectl apply -f MIRRORMAKER-CONFIGURATION-FILE
Additional resources

2.3.7. Securing a Kafka MirrorMaker 2.0 deployment

This procedure describes in outline the configuration required to secure a MirrorMaker 2.0 deployment.

You need separate configuration for the source Kafka cluster and the target Kafka cluster. You also need separate user configuration to provide the credentials required for MirrorMaker to connect to the source and target Kafka clusters.

For the Kafka clusters, you specify internal listeners for secure connections within a Kubernetes cluster and external listeners for connections outside the Kubernetes cluster.

You can configure authentication and authorization mechanisms. The security options implemented for the source and target Kafka clusters must be compatible with the security options implemented for MirrorMaker 2.0.

After you have created the cluster and user authentication credentials, you specify them in your MirrorMaker configuration for secure connections.

Note
In this procedure, the certificates generated by the Cluster Operator are used, but you can replace them by installing your own certificates. You can also configure your listener to use a Kafka listener certificate managed by an external CA (certificate authority).
Before you start

Before starting this procedure, take a look at the example configuration files provided by Strimzi. They include examples for securing a deployment of MirrorMaker 2.0 using mTLS or SCRAM-SHA-512 authentication. The examples specify internal listeners for connecting within a Kubernetes cluster.

The examples provide the configuration for full authorization, including all the ACLs needed by MirrorMaker 2.0 to allow operations on the source and target Kafka clusters.

Prerequisites
  • Strimzi is running

  • Separate namespaces for source and target clusters

The procedure assumes that the source and target Kafka clusters are installed to separate namespaces If you want to use the Topic Operator, you’ll need to do this. The Topic Operator only watches a single cluster in a specified namespace.

By separating the clusters into namespaces, you will need to copy the cluster secrets so they can be accessed outside the namespace. You need to reference the secrets in the MirrorMaker configuration.

Procedure
  1. Configure two Kafka resources, one to secure the source Kafka cluster and one to secure the target Kafka cluster.

    You can add listener configuration for authentication and enable authorization.

    In this example, an internal listener is configured for a Kafka cluster with TLS encryption and mTLS authentication. Kafka simple authorization is enabled.

    Example source Kafka cluster configuration with TLS encryption and mTLS authentication
    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-source-cluster
    spec:
      kafka:
        version: 3.3.2
        replicas: 1
        listeners:
          - name: tls
            port: 9093
            type: internal
            tls: true
            authentication:
              type: tls
        authorization:
          type: simple
        config:
          offsets.topic.replication.factor: 1
          transaction.state.log.replication.factor: 1
          transaction.state.log.min.isr: 1
          default.replication.factor: 1
          min.insync.replicas: 1
          inter.broker.protocol.version: "3.3"
        storage:
          type: jbod
          volumes:
          - id: 0
            type: persistent-claim
            size: 100Gi
            deleteClaim: false
      zookeeper:
        replicas: 1
        storage:
          type: persistent-claim
          size: 100Gi
          deleteClaim: false
      entityOperator:
        topicOperator: {}
        userOperator: {}
    Example target Kafka cluster configuration with TLS encryption and mTLS authentication
    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-target-cluster
    spec:
      kafka:
        version: 3.3.2
        replicas: 1
        listeners:
          - name: tls
            port: 9093
            type: internal
            tls: true
            authentication:
              type: tls
        authorization:
          type: simple
        config:
          offsets.topic.replication.factor: 1
          transaction.state.log.replication.factor: 1
          transaction.state.log.min.isr: 1
          default.replication.factor: 1
          min.insync.replicas: 1
          inter.broker.protocol.version: "3.3"
        storage:
          type: jbod
          volumes:
            - id: 0
              type: persistent-claim
              size: 100Gi
              deleteClaim: false
      zookeeper:
        replicas: 1
        storage:
          type: persistent-claim
          size: 100Gi
          deleteClaim: false
      entityOperator:
        topicOperator: {}
        userOperator: {}
  2. Create or update the Kafka resources in separate namespaces.

    kubectl apply -f <kafka_configuration_file> -n <namespace>

    The Cluster Operator creates the listeners and sets up the cluster and client certificate authority (CA) certificates to enable authentication within the Kafka cluster.

    The certificates are created in the secret <cluster_name>-cluster-ca-cert.

  3. Configure two KafkaUser resources, one for a user of the source Kafka cluster and one for a user of the target Kafka cluster.

    1. Configure the same authentication and authorization types as the corresponding source and target Kafka cluster. For example, if you used tls authentication and the simple authorization type in the Kafka configuration for the source Kafka cluster, use the same in the KafkaUser configuration.

    2. Configure the ACLs needed by MirrorMaker 2.0 to allow operations on the source and target Kafka clusters.

      The ACLs are used by the internal MirrorMaker connectors, and by the underlying Kafka Connect framework.

    Example source user configuration for mTLS authentication
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaUser
    metadata:
      name: my-source-user
      labels:
        strimzi.io/cluster: my-source-cluster
    spec:
      authentication:
        type: tls
      authorization:
        type: simple
        acls:
          # MirrorSourceConnector
          - resource: # Not needed if offset-syncs.topic.location=target
              type: topic
              name: mm2-offset-syncs.my-target-cluster.internal
            operations:
              - Create
              - DescribeConfigs
              - Read
              - Write
          - resource: # Needed for every topic which is mirrored
              type: topic
              name: "*"
            operations:
              - DescribeConfigs
              - Read
          # MirrorCheckpointConnector
          - resource:
              type: cluster
            operations:
              - Describe
          - resource: # Needed for every group for which offsets are synced
              type: group
              name: "*"
            operations:
              - Describe
          - resource: # Not needed if offset-syncs.topic.location=target
              type: topic
              name: mm2-offset-syncs.my-target-cluster.internal
            operations:
              - Read
    Example target user configuration for mTLS authentication
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaUser
    metadata:
      name: my-target-user
      labels:
        strimzi.io/cluster: my-target-cluster
    spec:
      authentication:
        type: tls
      authorization:
        type: simple
        acls:
          # Underlying Kafka Connect internal topics to store configuration, offsets, or status
          - resource:
              type: group
              name: mirrormaker2-cluster
            operations:
              - Read
          - resource:
              type: topic
              name: mirrormaker2-cluster-configs
            operations:
              - Create
              - Describe
              - DescribeConfigs
              - Read
              - Write
          - resource:
              type: topic
              name: mirrormaker2-cluster-status
            operations:
              - Create
              - Describe
              - DescribeConfigs
              - Read
              - Write
          - resource:
              type: topic
              name: mirrormaker2-cluster-offsets
            operations:
              - Create
              - Describe
              - DescribeConfigs
              - Read
              - Write
          # MirrorSourceConnector
          - resource: # Needed for every topic which is mirrored
              type: topic
              name: "*"
            operations:
              - Create
              - Alter
              - AlterConfigs
              - Write
          # MirrorCheckpointConnector
          - resource:
              type: cluster
            operations:
              - Describe
          - resource:
              type: topic
              name: my-source-cluster.checkpoints.internal
            operations:
              - Create
              - Describe
              - Read
              - Write
          - resource: # Needed for every group for which the offset is synced
              type: group
              name: "*"
            operations:
              - Read
              - Describe
          # MirrorHeartbeatConnector
          - resource:
              type: topic
              name: heartbeats
            operations:
              - Create
              - Describe
              - Write
    Note
    You can use a certificate issued outside the User Operator by setting type to tls-external. For more information, see KafkaUserSpec schema reference.
  4. Create or update a KafkaUser resource in each of the namespaces you created for the source and target Kafka clusters.

    kubectl apply -f <kafka_user_configuration_file> -n <namespace>

    The User Operator creates the users representing the client (MirrorMaker), and the security credentials used for client authentication, based on the chosen authentication type.

    The User Operator creates a new secret with the same name as the KafkaUser resource. The secret contains a private and public key for mTLS authentication. The public key is contained in a user certificate, which is signed by the clients CA.

  5. Configure a KafkaMirrorMaker2 resource with the authentication details to connect to the source and target Kafka clusters.

    Example MirrorMaker 2.0 configuration with TLS encryption and mTLS authentication
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaMirrorMaker2
    metadata:
      name: my-mirror-maker-2
    spec:
      version: 3.3.2
      replicas: 1
      connectCluster: "my-target-cluster"
      clusters:
        - alias: "my-source-cluster"
          bootstrapServers: my-source-cluster-kafka-bootstrap:9093
          tls: # (1)
            trustedCertificates:
              - secretName: my-source-cluster-cluster-ca-cert
                certificate: ca.crt
          authentication: # (2)
            type: tls
            certificateAndKey:
              secretName: my-source-user
              certificate: user.crt
              key: user.key
        - alias: "my-target-cluster"
          bootstrapServers: my-target-cluster-kafka-bootstrap:9093
          tls: # (3)
            trustedCertificates:
              - secretName: my-target-cluster-cluster-ca-cert
                certificate: ca.crt
          authentication: # (4)
            type: tls
            certificateAndKey:
              secretName: my-target-user
              certificate: user.crt
              key: user.key
          config:
            # -1 means it will use the default replication factor configured in the broker
            config.storage.replication.factor: -1
            offset.storage.replication.factor: -1
            status.storage.replication.factor: -1
      mirrors:
        - sourceCluster: "my-source-cluster"
          targetCluster: "my-target-cluster"
          sourceConnector:
            config:
              replication.factor: 1
              offset-syncs.topic.replication.factor: 1
              sync.topic.acls.enabled: "false"
          heartbeatConnector:
            config:
              heartbeats.topic.replication.factor: 1
          checkpointConnector:
            config:
              checkpoints.topic.replication.factor: 1
              sync.group.offsets.enabled: "true"
          topicsPattern: "topic1|topic2|topic3"
          groupsPattern: "group1|group2|group3"
    1. The TLS certificates for the source Kafka cluster. If they are in a separate namespace, copy the cluster secrets from the namespace of the Kafka cluster.

    2. The user authentication for accessing the source Kafka cluster using the TLS mechanism.

    3. The TLS certificates for the target Kafka cluster.

    4. The user authentication for accessing the target Kafka cluster.

  6. Create or update the KafkaMirrorMaker2 resource in the same namespace as the target Kafka cluster.

    kubectl apply -f <mirrormaker2_configuration_file> -n <namespace_of_target_cluster>
Additional resources
  • type-KafkaMirrorMaker2ClusterSpec-reference[]

2.3.8. Performing a restart of a Kafka MirrorMaker 2.0 connector

This procedure describes how to manually trigger a restart of a Kafka MirrorMaker 2.0 connector by using a Kubernetes annotation.

Prerequisites
  • The Cluster Operator is running.

Procedure
  1. Find the name of the KafkaMirrorMaker2 custom resource that controls the Kafka MirrorMaker 2.0 connector you want to restart:

    kubectl get KafkaMirrorMaker2
  2. Find the name of the Kafka MirrorMaker 2.0 connector to be restarted from the KafkaMirrorMaker2 custom resource.

    kubectl describe KafkaMirrorMaker2 KAFKAMIRRORMAKER-2-NAME
  3. To restart the connector, annotate the KafkaMirrorMaker2 resource in Kubernetes. In this example, kubectl annotate restarts a connector named my-source->my-target.MirrorSourceConnector:

    kubectl annotate KafkaMirrorMaker2 KAFKAMIRRORMAKER-2-NAME "strimzi.io/restart-connector=my-source->my-target.MirrorSourceConnector"
  4. Wait for the next reconciliation to occur (every two minutes by default).

    The Kafka MirrorMaker 2.0 connector is restarted, as long as the annotation was detected by the reconciliation process. When the restart request is accepted, the annotation is removed from the KafkaMirrorMaker2 custom resource.

2.3.9. Performing a restart of a Kafka MirrorMaker 2.0 connector task

This procedure describes how to manually trigger a restart of a Kafka MirrorMaker 2.0 connector task by using a Kubernetes annotation.

Prerequisites
  • The Cluster Operator is running.

Procedure
  1. Find the name of the KafkaMirrorMaker2 custom resource that controls the Kafka MirrorMaker 2.0 connector you want to restart:

    kubectl get KafkaMirrorMaker2
  2. Find the name of the Kafka MirrorMaker 2.0 connector and the ID of the task to be restarted from the KafkaMirrorMaker2 custom resource. Task IDs are non-negative integers, starting from 0.

    kubectl describe KafkaMirrorMaker2 KAFKAMIRRORMAKER-2-NAME
  3. To restart the connector task, annotate the KafkaMirrorMaker2 resource in Kubernetes. In this example, kubectl annotate restarts task 0 of a connector named my-source->my-target.MirrorSourceConnector:

    kubectl annotate KafkaMirrorMaker2 KAFKAMIRRORMAKER-2-NAME "strimzi.io/restart-connector-task=my-source->my-target.MirrorSourceConnector:0"
  4. Wait for the next reconciliation to occur (every two minutes by default).

    The Kafka MirrorMaker 2.0 connector task is restarted, as long as the annotation was detected by the reconciliation process. When the restart task request is accepted, the annotation is removed from the KafkaMirrorMaker2 custom resource.

2.4. Kafka MirrorMaker cluster configuration

Configure a Kafka MirrorMaker deployment using the KafkaMirrorMaker resource. KafkaMirrorMaker replicates data between Kafka clusters.

KafkaMirrorMaker schema reference describes the full schema of the KafkaMirrorMaker resource.

You can use Strimzi with MirrorMaker or MirrorMaker 2.0. MirrorMaker 2.0 is the latest version, and offers a more efficient way to mirror data between Kafka clusters.

Important
Kafka MirrorMaker 1 (referred to as just MirrorMaker in the documentation) has been deprecated in Apache Kafka 3.0.0 and will be removed in Apache Kafka 4.0.0. As a result, the KafkaMirrorMaker custom resource which is used to deploy Kafka MirrorMaker 1 has been deprecated in Strimzi as well. The KafkaMirrorMaker resource will be removed from Strimzi when we adopt Apache Kafka 4.0.0. As a replacement, use the KafkaMirrorMaker2 custom resource with the IdentityReplicationPolicy.

2.4.1. Configuring Kafka MirrorMaker

Use the properties of the KafkaMirrorMaker resource to configure your Kafka MirrorMaker deployment.

You can configure access control for producers and consumers using TLS or SASL authentication. This procedure shows a configuration that uses TLS encryption and mTLS authentication on the consumer and producer side.

Prerequisites
  • See the Deploying and Upgrading Strimzi guide for instructions on running a:

  • Source and target Kafka clusters must be available

Procedure
  1. Edit the spec properties for the KafkaMirrorMaker resource.

    The properties you can configure are shown in this example configuration:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaMirrorMaker
    metadata:
      name: my-mirror-maker
    spec:
      replicas: 3 (1)
      consumer:
        bootstrapServers: my-source-cluster-kafka-bootstrap:9092 (2)
        groupId: "my-group" (3)
        numStreams: 2 (4)
        offsetCommitInterval: 120000 (5)
        tls: (6)
          trustedCertificates:
          - secretName: my-source-cluster-ca-cert
            certificate: ca.crt
        authentication: (7)
          type: tls
          certificateAndKey:
            secretName: my-source-secret
            certificate: public.crt
            key: private.key
        config: (8)
          max.poll.records: 100
          receive.buffer.bytes: 32768
          ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" (9)
          ssl.enabled.protocols: "TLSv1.2"
          ssl.protocol: "TLSv1.2"
          ssl.endpoint.identification.algorithm: HTTPS (10)
      producer:
        bootstrapServers: my-target-cluster-kafka-bootstrap:9092
        abortOnSendFailure: false (11)
        tls:
          trustedCertificates:
          - secretName: my-target-cluster-ca-cert
            certificate: ca.crt
        authentication:
          type: tls
          certificateAndKey:
            secretName: my-target-secret
            certificate: public.crt
            key: private.key
        config:
          compression.type: gzip
          batch.size: 8192
          ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" (12)
          ssl.enabled.protocols: "TLSv1.2"
          ssl.protocol: "TLSv1.2"
          ssl.endpoint.identification.algorithm: HTTPS (13)
      include: "my-topic|other-topic" (14)
      resources: (15)
        requests:
          cpu: "1"
          memory: 2Gi
        limits:
          cpu: "2"
          memory: 2Gi
      logging: (16)
        type: inline
        loggers:
          mirrormaker.root.logger: "INFO"
      readinessProbe: (17)
        initialDelaySeconds: 15
        timeoutSeconds: 5
      livenessProbe:
        initialDelaySeconds: 15
        timeoutSeconds: 5
      metricsConfig: (18)
       type: jmxPrometheusExporter
       valueFrom:
         configMapKeyRef:
           name: my-config-map
           key: my-key
      jvmOptions: (19)
        "-Xmx": "1g"
        "-Xms": "1g"
      image: my-org/my-image:latest (20)
      template: (21)
        pod:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: application
                        operator: In
                        values:
                          - postgresql
                          - mongodb
                  topologyKey: "kubernetes.io/hostname"
        connectContainer: (22)
          env:
            - name: JAEGER_SERVICE_NAME
              value: my-jaeger-service
            - name: JAEGER_AGENT_HOST
              value: jaeger-agent-name
            - name: JAEGER_AGENT_PORT
              value: "6831"
      tracing: (23)
        type: jaeger
    1. The number of replica nodes.

    2. Bootstrap servers for consumer and producer.

    3. Group ID for the consumer.

    4. The number of consumer streams.

    5. The offset auto-commit interval in milliseconds.

    6. TLS encryption with key names under which TLS certificates are stored in X.509 format for consumer or producer. If certificates are stored in the same secret, it can be listed multiple times.

    7. Authentication for consumer or producer, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.

    8. Kafka configuration options for consumer and producer.

    9. SSL properties for external listeners to run with a specific cipher suite for a TLS version.

    10. Hostname verification is enabled by setting to HTTPS. An empty string disables the verification.

    11. If the abortOnSendFailure property is set to true, Kafka MirrorMaker will exit and the container will restart following a send failure for a message.

    12. SSL properties for external listeners to run with a specific cipher suite for a TLS version.

    13. Hostname verification is enabled by setting to HTTPS. An empty string disables the verification.

    14. A included topics mirrored from source to target Kafka cluster.

    15. Requests for reservation of supported resources, currently cpu and memory, and limits to specify the maximum resources that can be consumed.

    16. Specified loggers and log levels added directly (inline) or indirectly (external) through a ConfigMap. A custom ConfigMap must be placed under the log4j.properties or log4j2.properties key. MirrorMaker has a single logger called mirrormaker.root.logger. You can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.

    17. Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).

    18. Prometheus metrics, which are enabled by referencing a ConfigMap containing configuration for the Prometheus JMX exporter in this example. You can enable metrics without further configuration using a reference to a ConfigMap containing an empty file under metricsConfig.valueFrom.configMapKeyRef.key.

    19. JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka MirrorMaker.

    20. ADVANCED OPTION: Container image configuration, which is recommended only in special situations.

    21. Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.

    22. Environment variables are set for distributed tracing.

    23. Distributed tracing is enabled for Jaeger.

    Warning
    With the abortOnSendFailure property set to false, the producer attempts to send the next message in a topic. The original message might be lost, as there is no attempt to resend a failed message.
  2. Create or update the resource:

    kubectl apply -f <your-file>
Additional resources

2.4.2. List of Kafka MirrorMaker cluster resources

The following resources are created by the Cluster Operator in the Kubernetes cluster:

<mirror-maker-name>-mirror-maker

Deployment which is responsible for creating the Kafka MirrorMaker pods.

<mirror-maker-name>-config

ConfigMap which contains ancillary configuration for the Kafka MirrorMaker, and is mounted as a volume by the Kafka broker pods.

<mirror-maker-name>-mirror-maker

Pod Disruption Budget configured for the Kafka MirrorMaker worker nodes.

2.5. Kafka Bridge cluster configuration

Configure a Kafka Bridge deployment using the KafkaBridge resource. Kafka Bridge provides an API for integrating HTTP-based clients with a Kafka cluster.

KafkaBridge schema reference describes the full schema of the KafkaBridge resource.

2.5.1. Configuring the Kafka Bridge

Use the Kafka Bridge to make HTTP-based requests to the Kafka cluster.

Use the properties of the KafkaBridge resource to configure your Kafka Bridge deployment.

In order to prevent issues arising when client consumer requests are processed by different Kafka Bridge instances, address-based routing must be employed to ensure that requests are routed to the right Kafka Bridge instance. Additionally, each independent Kafka Bridge instance must have a replica. A Kafka Bridge instance has its own state which is not shared with another instances.

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

See the Deploying and Upgrading Strimzi guide for instructions on running a:

Procedure
  1. Edit the spec properties for the KafkaBridge resource.

    The properties you can configure are shown in this example configuration:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaBridge
    metadata:
      name: my-bridge
    spec:
      replicas: 3 (1)
      bootstrapServers: <cluster_name>-cluster-kafka-bootstrap:9092 (2)
      tls: (3)
        trustedCertificates:
          - secretName: my-cluster-cluster-cert
            certificate: ca.crt
          - secretName: my-cluster-cluster-cert
            certificate: ca2.crt
      authentication: (4)
        type: tls
        certificateAndKey:
          secretName: my-secret
          certificate: public.crt
          key: private.key
      http: (5)
        port: 8080
        cors: (6)
          allowedOrigins: "https://strimzi.io"
          allowedMethods: "GET,POST,PUT,DELETE,OPTIONS,PATCH"
      consumer: (7)
        config:
          auto.offset.reset: earliest
      producer: (8)
        config:
          delivery.timeout.ms: 300000
      resources: (9)
        requests:
          cpu: "1"
          memory: 2Gi
        limits:
          cpu: "2"
          memory: 2Gi
      logging: (10)
        type: inline
        loggers:
          logger.bridge.level: "INFO"
          # enabling DEBUG just for send operation
          logger.send.name: "http.openapi.operation.send"
          logger.send.level: "DEBUG"
      jvmOptions: (11)
        "-Xmx": "1g"
        "-Xms": "1g"
      readinessProbe: (12)
        initialDelaySeconds: 15
        timeoutSeconds: 5
      livenessProbe:
        initialDelaySeconds: 15
        timeoutSeconds: 5
      image: my-org/my-image:latest (13)
      template: (14)
        pod:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: application
                        operator: In
                        values:
                          - postgresql
                          - mongodb
                  topologyKey: "kubernetes.io/hostname"
        bridgeContainer: (15)
          env:
            - name: JAEGER_SERVICE_NAME
              value: my-jaeger-service
            - name: JAEGER_AGENT_HOST
              value: jaeger-agent-name
            - name: JAEGER_AGENT_PORT
              value: "6831"
    1. The number of replica nodes.

    2. Bootstrap server for connection to the target Kafka cluster. Use the name of the Kafka cluster as the <cluster_name>.

    3. TLS encryption with key names under which TLS certificates are stored in X.509 format for the source Kafka cluster. If certificates are stored in the same secret, it can be listed multiple times.

    4. Authentication for the Kafka Bridge cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN. By default, the Kafka Bridge connects to Kafka brokers without authentication.

    5. HTTP access to Kafka brokers.

    6. CORS access specifying selected resources and access methods. Additional HTTP headers in requests describe the origins that are permitted access to the Kafka cluster.

    7. Consumer configuration options.

    8. Producer configuration options.

    9. Requests for reservation of supported resources, currently cpu and memory, and limits to specify the maximum resources that can be consumed.

    10. Specified Kafka Bridge loggers and log levels added directly (inline) or indirectly (external) through a ConfigMap. A custom ConfigMap must be placed under the log4j.properties or log4j2.properties key. For the Kafka Bridge loggers, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.

    11. JVM configuration options to optimize performance for the Virtual Machine (VM) running the Kafka Bridge.

    12. Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).

    13. Optional: Container image configuration, which is recommended only in special situations.

    14. Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.

    15. Environment variables are set for distributed tracing.

  2. Create or update the resource:

    kubectl apply -f KAFKA-BRIDGE-CONFIG-FILE

2.5.2. List of Kafka Bridge cluster resources

The following resources are created by the Cluster Operator in the Kubernetes cluster:

bridge-cluster-name-bridge

Deployment which is in charge to create the Kafka Bridge worker node pods.

bridge-cluster-name-bridge-service

Service which exposes the REST interface of the Kafka Bridge cluster.

bridge-cluster-name-bridge-config

ConfigMap which contains the Kafka Bridge ancillary configuration and is mounted as a volume by the Kafka broker pods.

bridge-cluster-name-bridge

Pod Disruption Budget configured for the Kafka Bridge worker nodes.

2.6. Customizing Kubernetes resources

A Strimzi deployment creates Kubernetes resources, such as Deployments, StatefulSets, Pods, and Services. These resources are managed by Strimzi operators. Only the operator that is responsible for managing a particular Kubernetes resource can change that resource. If you try to manually change an operator-managed Kubernetes resource, the operator will revert your changes back.

Changing an operator-managed Kubernetes resource can be useful if you want to perform certain tasks, such as:

  • Adding custom labels or annotations that control how Pods are treated by Istio or other services

  • Managing how Loadbalancer-type Services are created by the cluster

You can make the changes using the template property in the Strimzi custom resources. The template property is supported in the following resources. The API reference provides more details about the customizable fields.

Kafka.spec.kafka

See KafkaClusterTemplate schema reference

Kafka.spec.zookeeper

See ZookeeperClusterTemplate schema reference

Kafka.spec.entityOperator

See EntityOperatorTemplate schema reference

Kafka.spec.kafkaExporter

See KafkaExporterTemplate schema reference

Kafka.spec.cruiseControl

See CruiseControlTemplate schema reference

Kafka.spec.jmxTrans

See JmxTransTemplate schema reference

KafkaConnect.spec

See KafkaConnectTemplate schema reference

KafkaMirrorMaker.spec

See KafkaMirrorMakerTemplate schema reference

KafkaMirrorMaker2.spec

See KafkaConnectTemplate schema reference

KafkaBridge.spec

See KafkaBridgeTemplate schema reference

KafkaUser.spec

See KafkaUserTemplate schema reference

In the following example, the template property is used to modify the labels in a Kafka broker’s pod.

Example template customization
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
  labels:
    app: my-cluster
spec:
  kafka:
    # ...
    template:
      pod:
        metadata:
          labels:
            mylabel: myvalue
    # ...

2.6.1. Customizing the image pull policy

Strimzi allows you to customize the image pull policy for containers in all pods deployed by the Cluster Operator. The image pull policy is configured using the environment variable STRIMZI_IMAGE_PULL_POLICY in the Cluster Operator deployment. The STRIMZI_IMAGE_PULL_POLICY environment variable can be set to three different values:

Always

Container images are pulled from the registry every time the pod is started or restarted.

IfNotPresent

Container images are pulled from the registry only when they were not pulled before.

Never

Container images are never pulled from the registry.

The image pull policy can be currently customized only for all Kafka, Kafka Connect, and Kafka MirrorMaker clusters at once. Changing the policy will result in a rolling update of all your Kafka, Kafka Connect, and Kafka MirrorMaker clusters.

Additional resources

2.6.2. Applying a termination grace period

Apply a termination grace period to give a Kafka cluster enough time to shut down cleanly.

Specify the time using the terminationGracePeriodSeconds property. Add the property to the template.pod configuration of the Kafka custom resource.

The time you add will depend on the size of your Kafka cluster. The Kubernetes default for the termination grace period is 30 seconds. If you observe that your clusters are not shutting down cleanly, you can increase the termination grace period.

A termination grace period is applied every time a pod is restarted. The period begins when Kubernetes sends a term (termination) signal to the processes running in the pod. The period should reflect the amount of time required to transfer the processes of the terminating pod to another pod before they are stopped. After the period ends, a kill signal stops any processes still running in the pod.

The following example adds a termination grace period of 120 seconds to the Kafka custom resource. You can also specify the configuration in the custom resources of other Kafka components.

Example termination grace period configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    template:
      pod:
        terminationGracePeriodSeconds: 120
        # ...
    # ...

2.7. Configuring pod scheduling

When two applications are scheduled to the same Kubernetes node, both applications might use the same resources like disk I/O and impact performance. That can lead to performance degradation. Scheduling Kafka pods in a way that avoids sharing nodes with other critical workloads, using the right nodes or dedicated a set of nodes only for Kafka are the best ways how to avoid such problems.

2.7.1. Specifying affinity, tolerations, and topology spread constraints

Use affinity, tolerations and topology spread constraints to schedule the pods of kafka resources onto nodes. Affinity, tolerations and topology spread constraints are configured using the affinity, tolerations, and topologySpreadConstraint properties in following resources:

  • Kafka.spec.kafka.template.pod

  • Kafka.spec.zookeeper.template.pod

  • Kafka.spec.entityOperator.template.pod

  • KafkaConnect.spec.template.pod

  • KafkaBridge.spec.template.pod

  • KafkaMirrorMaker.spec.template.pod

  • KafkaMirrorMaker2.spec.template.pod

The format of the affinity, tolerations, and topologySpreadConstraint properties follows the Kubernetes specification. The affinity configuration can include different types of affinity:

  • Pod affinity and anti-affinity

  • Node affinity

Use pod anti-affinity to avoid critical applications sharing nodes

Use pod anti-affinity to ensure that critical applications are never scheduled on the same disk. When running a Kafka cluster, it is recommended to use pod anti-affinity to ensure that the Kafka brokers do not share nodes with other workloads, such as databases.

Use node affinity to schedule workloads onto specific nodes

The Kubernetes cluster usually consists of many different types of worker nodes. Some are optimized for CPU heavy workloads, some for memory, while other might be optimized for storage (fast local SSDs) or network. Using different nodes helps to optimize both costs and performance. To achieve the best possible performance, it is important to allow scheduling of Strimzi components to use the right nodes.

Kubernetes uses node affinity to schedule workloads onto specific nodes. Node affinity allows you to create a scheduling constraint for the node on which the pod will be scheduled. The constraint is specified as a label selector. You can specify the label using either the built-in node label like beta.kubernetes.io/instance-type or custom labels to select the right node.

Use node affinity and tolerations for dedicated nodes

Use taints to create dedicated nodes, then schedule Kafka pods on the dedicated nodes by configuring node affinity and tolerations.

Cluster administrators can mark selected Kubernetes nodes as tainted. Nodes with taints are excluded from regular scheduling and normal pods will not be scheduled to run on them. Only services which can tolerate the taint set on the node can be scheduled on it. The only other services running on such nodes will be system services such as log collectors or software defined networks.

Running Kafka and its components on dedicated nodes can have many advantages. There will be no other applications running on the same nodes which could cause disturbance or consume the resources needed for Kafka. That can lead to improved performance and stability.

2.7.2. Configuring pod anti-affinity to schedule each Kafka broker on a different worker node

Many Kafka brokers or ZooKeeper nodes can run on the same Kubernetes worker node. If the worker node fails, they will all become unavailable at the same time. To improve reliability, you can use podAntiAffinity configuration to schedule each Kafka broker or ZooKeeper node on a different Kubernetes worker node.

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

Procedure
  1. Edit the affinity property in the resource specifying the cluster deployment. To make sure that no worker nodes are shared by Kafka brokers or ZooKeeper nodes, use the strimzi.io/name label. Set the topologyKey to kubernetes.io/hostname to specify that the selected pods are not scheduled on nodes with the same hostname. This will still allow the same worker node to be shared by a single Kafka broker and a single ZooKeeper node. For example:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      kafka:
        # ...
        template:
          pod:
            affinity:
              podAntiAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchExpressions:
                        - key: strimzi.io/name
                          operator: In
                          values:
                            - CLUSTER-NAME-kafka
                    topologyKey: "kubernetes.io/hostname"
        # ...
      zookeeper:
        # ...
        template:
          pod:
            affinity:
              podAntiAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchExpressions:
                        - key: strimzi.io/name
                          operator: In
                          values:
                            - CLUSTER-NAME-zookeeper
                    topologyKey: "kubernetes.io/hostname"
        # ...

    Where CLUSTER-NAME is the name of your Kafka custom resource.

  2. If you even want to make sure that a Kafka broker and ZooKeeper node do not share the same worker node, use the strimzi.io/cluster label. For example:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      kafka:
        # ...
        template:
          pod:
            affinity:
              podAntiAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchExpressions:
                        - key: strimzi.io/cluster
                          operator: In
                          values:
                            - CLUSTER-NAME
                    topologyKey: "kubernetes.io/hostname"
        # ...
      zookeeper:
        # ...
        template:
          pod:
            affinity:
              podAntiAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchExpressions:
                        - key: strimzi.io/cluster
                          operator: In
                          values:
                            - CLUSTER-NAME
                    topologyKey: "kubernetes.io/hostname"
        # ...

    Where CLUSTER-NAME is the name of your Kafka custom resource.

  3. Create or update the resource.

    kubectl apply -f <kafka_configuration_file>

2.7.3. Configuring pod anti-affinity in Kafka components

Pod anti-affinity configuration helps with the stability and performance of Kafka brokers. By using podAntiAffinity, Kubernetes will not schedule Kafka brokers on the same nodes as other workloads. Typically, you want to avoid Kafka running on the same worker node as other network or storage intensive applications such as databases, storage or other messaging platforms.

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

Procedure
  1. Edit the affinity property in the resource specifying the cluster deployment. Use labels to specify the pods which should not be scheduled on the same nodes. The topologyKey should be set to kubernetes.io/hostname to specify that the selected pods should not be scheduled on nodes with the same hostname. For example:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      kafka:
        # ...
        template:
          pod:
            affinity:
              podAntiAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchExpressions:
                        - key: application
                          operator: In
                          values:
                            - postgresql
                            - mongodb
                    topologyKey: "kubernetes.io/hostname"
        # ...
      zookeeper:
        # ...
  2. Create or update the resource.

    This can be done using kubectl apply:

    kubectl apply -f <kafka_configuration_file>

2.7.4. Configuring node affinity in Kafka components

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

Procedure
  1. Label the nodes where Strimzi components should be scheduled.

    This can be done using kubectl label:

    kubectl label node NAME-OF-NODE node-type=fast-network

    Alternatively, some of the existing labels might be reused.

  2. Edit the affinity property in the resource specifying the cluster deployment. For example:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      kafka:
        # ...
        template:
          pod:
            affinity:
              nodeAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  nodeSelectorTerms:
                    - matchExpressions:
                      - key: node-type
                        operator: In
                        values:
                        - fast-network
        # ...
      zookeeper:
        # ...
  3. Create or update the resource.

    This can be done using kubectl apply:

    kubectl apply -f <kafka_configuration_file>

2.7.5. Setting up dedicated nodes and scheduling pods on them

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

Procedure
  1. Select the nodes which should be used as dedicated.

  2. Make sure there are no workloads scheduled on these nodes.

  3. Set the taints on the selected nodes:

    This can be done using kubectl taint:

    kubectl taint node NAME-OF-NODE dedicated=Kafka:NoSchedule
  4. Additionally, add a label to the selected nodes as well.

    This can be done using kubectl label:

    kubectl label node NAME-OF-NODE dedicated=Kafka
  5. Edit the affinity and tolerations properties in the resource specifying the cluster deployment.

    For example:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      kafka:
        # ...
        template:
          pod:
            tolerations:
              - key: "dedicated"
                operator: "Equal"
                value: "Kafka"
                effect: "NoSchedule"
            affinity:
              nodeAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  nodeSelectorTerms:
                  - matchExpressions:
                    - key: dedicated
                      operator: In
                      values:
                      - Kafka
        # ...
      zookeeper:
        # ...
  6. Create or update the resource.

    This can be done using kubectl apply:

    kubectl apply -f <kafka_configuration_file>

2.8. Logging configuration

Configure logging levels in the custom resources of Kafka components and Strimzi Operators. You can specify the logging levels directly in the spec.logging property of the custom resource. Or you can define the logging properties in a ConfigMap that’s referenced in the custom resource using the configMapKeyRef property.

The advantages of using a ConfigMap are that the logging properties are maintained in one place and are accessible to more than one resource. You can also reuse the ConfigMap for more than one resource. If you are using a ConfigMap to specify loggers for Strimzi Operators, you can also append the logging specification to add filters.

You specify a logging type in your logging specification:

  • inline when specifying logging levels directly

  • external when referencing a ConfigMap

Example inline logging configuration
spec:
  # ...
  logging:
    type: inline
    loggers:
      kafka.root.logger.level: "INFO"
Example external logging configuration
spec:
  # ...
  logging:
    type: external
    valueFrom:
      configMapKeyRef:
        name: my-config-map
        key: my-config-map-key

Values for the name and key of the ConfigMap are mandatory. Default logging is used if the name or key is not set.

2.8.2. Creating a ConfigMap for logging

To use a ConfigMap to define logging properties, you create the ConfigMap and then reference it as part of the logging definition in the spec of a resource.

The ConfigMap must contain the appropriate logging configuration.

  • log4j.properties for Kafka components, ZooKeeper, and the Kafka Bridge

  • log4j2.properties for the Topic Operator and User Operator

The configuration must be placed under these properties.

In this procedure a ConfigMap defines a root logger for a Kafka resource.

Procedure
  1. Create the ConfigMap.

    You can create the ConfigMap as a YAML file or from a properties file.

    ConfigMap example with a root logger definition for Kafka:

    kind: ConfigMap
    apiVersion: v1
    metadata:
      name: logging-configmap
    data:
      log4j.properties:
        kafka.root.logger.level="INFO"

    If you are using a properties file, specify the file at the command line:

    kubectl create configmap logging-configmap --from-file=log4j.properties

    The properties file defines the logging configuration:

    # Define the logger
    kafka.root.logger.level="INFO"
    # ...
  2. Define external logging in the spec of the resource, setting the logging.valueFrom.configMapKeyRef.name to the name of the ConfigMap and logging.valueFrom.configMapKeyRef.key to the key in this ConfigMap.

    spec:
      # ...
      logging:
        type: external
        valueFrom:
          configMapKeyRef:
            name: logging-configmap
            key: log4j.properties
  3. Create or update the resource.

    kubectl apply -f <kafka_configuration_file>

2.8.3. Adding logging filters to Operators

If you are using a ConfigMap to configure the (log4j2) logging levels for Strimzi Operators, you can also define logging filters to limit what’s returned in the log.

Logging filters are useful when you have a large number of logging messages. Suppose you set the log level for the logger as DEBUG (rootLogger.level="DEBUG"). Logging filters reduce the number of logs returned for the logger at that level, so you can focus on a specific resource. When the filter is set, only log messages matching the filter are logged.

Filters use markers to specify what to include in the log. You specify a kind, namespace and name for the marker. For example, if a Kafka cluster is failing, you can isolate the logs by specifying the kind as Kafka, and use the namespace and name of the failing cluster.

This example shows a marker filter for a Kafka cluster named my-kafka-cluster.

Basic logging filter configuration
rootLogger.level="INFO"
appender.console.filter.filter1.type=MarkerFilter (1)
appender.console.filter.filter1.onMatch=ACCEPT (2)
appender.console.filter.filter1.onMismatch=DENY (3)
appender.console.filter.filter1.marker=Kafka(my-namespace/my-kafka-cluster) (4)
  1. The MarkerFilter type compares a specified marker for filtering.

  2. The onMatch property accepts the log if the marker matches.

  3. The onMismatch property rejects the log if the marker does not match.

  4. The marker used for filtering is in the format KIND(NAMESPACE/NAME-OF-RESOURCE).

You can create one or more filters. Here, the log is filtered for two Kafka clusters.

Multiple logging filter configuration
appender.console.filter.filter1.type=MarkerFilter
appender.console.filter.filter1.onMatch=ACCEPT
appender.console.filter.filter1.onMismatch=DENY
appender.console.filter.filter1.marker=Kafka(my-namespace/my-kafka-cluster-1)
appender.console.filter.filter2.type=MarkerFilter
appender.console.filter.filter2.onMatch=ACCEPT
appender.console.filter.filter2.onMismatch=DENY
appender.console.filter.filter2.marker=Kafka(my-namespace/my-kafka-cluster-2)
Adding filters to the Cluster Operator

To add filters to the Cluster Operator, update its logging ConfigMap YAML file (install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml).

Procedure
  1. Update the 050-ConfigMap-strimzi-cluster-operator.yaml file to add the filter properties to the ConfigMap.

    In this example, the filter properties return logs only for the my-kafka-cluster Kafka cluster:

    kind: ConfigMap
    apiVersion: v1
    metadata:
      name: strimzi-cluster-operator
    data:
      log4j2.properties:
        #...
        appender.console.filter.filter1.type=MarkerFilter
        appender.console.filter.filter1.onMatch=ACCEPT
        appender.console.filter.filter1.onMismatch=DENY
        appender.console.filter.filter1.marker=Kafka(my-namespace/my-kafka-cluster)

    Alternatively, edit the ConfigMap directly:

    kubectl edit configmap strimzi-cluster-operator
  2. If you updated the YAML file instead of editing the ConfigMap directly, apply the changes by deploying the ConfigMap:

    kubectl create -f install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml
Adding filters to the Topic Operator or User Operator

To add filters to the Topic Operator or User Operator, create or edit a logging ConfigMap.

In this procedure a logging ConfigMap is created with filters for the Topic Operator. The same approach is used for the User Operator.

Procedure
  1. Create the ConfigMap.

    You can create the ConfigMap as a YAML file or from a properties file.

    In this example, the filter properties return logs only for the my-topic topic:

    kind: ConfigMap
    apiVersion: v1
    metadata:
      name: logging-configmap
    data:
      log4j2.properties:
        rootLogger.level="INFO"
        appender.console.filter.filter1.type=MarkerFilter
        appender.console.filter.filter1.onMatch=ACCEPT
        appender.console.filter.filter1.onMismatch=DENY
        appender.console.filter.filter1.marker=KafkaTopic(my-namespace/my-topic)

    If you are using a properties file, specify the file at the command line:

    kubectl create configmap logging-configmap --from-file=log4j2.properties

    The properties file defines the logging configuration:

    # Define the logger
    rootLogger.level="INFO"
    # Set the filters
    appender.console.filter.filter1.type=MarkerFilter
    appender.console.filter.filter1.onMatch=ACCEPT
    appender.console.filter.filter1.onMismatch=DENY
    appender.console.filter.filter1.marker=KafkaTopic(my-namespace/my-topic)
    # ...
  2. Define external logging in the spec of the resource, setting the logging.valueFrom.configMapKeyRef.name to the name of the ConfigMap and logging.valueFrom.configMapKeyRef.key to the key in this ConfigMap.

    For the Topic Operator, logging is specified in the topicOperator configuration of the Kafka resource.

    spec:
      # ...
      entityOperator:
        topicOperator:
          logging:
            type: external
            valueFrom:
              configMapKeyRef:
                name: logging-configmap
                key: log4j2.properties
  3. Apply the changes by deploying the Cluster Operator:

create -f install/cluster-operator -n my-cluster-operator-namespace

3. Loading configuration values from external sources

Use configuration provider plugins to load configuration data from external sources. The providers operate independently of Strimzi. You can use them to load configuration data for all Kafka components, including producers and consumers. Use them, for example, to provide the credentials for Kafka Connect connector configuration.

Kubernetes Configuration Provider

The Kubernetes Configuration Provider plugin loads configuration data from Kubernetes secrets or ConfigMaps.

Suppose you have a Secret object that’s managed outside the Kafka namespace, or outside the Kafka cluster. The Kubernetes Configuration Provider allows you to reference the values of the secret in your configuration without extracting the files. You just need to tell the provider what secret to use and provide access rights. The provider loads the data without needing to restart the Kafka component, even when using a new Secret or ConfigMap object. This capability avoids disruption when a Kafka Connect instance hosts multiple connectors.

Environment Variables Configuration Provider

The Environment Variables Configuration Provider plugin loads configuration data from environment variables.

The values for the environment variables can be mapped from secrets or ConfigMaps. You can use the Environment Variables Configuration Provider, for example, to load certificates or JAAS configuration from environment variables mapped from Kubernetes secrets.

Note
Kubernetes Configuration Provider can’t use mounted files. For example, it can’t load values that need the location of a truststore or keystore. Instead, you can mount ConfigMaps or secrets into a Kafka Connect pod as environment variables or volumes. You can use the Environment Variables Configuration Provider to load values for environment variables. You add configuration using the externalConfiguration property in KafkaConnect.spec. You don’t need to set up access rights with this approach. However, Kafka Connect will need a restart when using a new Secret or ConfigMap for a connector. This will cause disruption to all the Kafka Connect instance’s connectors.

3.1. Loading configuration values from a ConfigMap

This procedure shows how to use the Kubernetes Configuration Provider plugin.

In the procedure, an external ConfigMap object provides configuration properties for a connector.

Prerequisites
  • A Kubernetes cluster is available.

  • A Kafka cluster is running.

  • The Cluster Operator is running.

Procedure
  1. Create a ConfigMap or Secret that contains the configuration properties.

    In this example, a ConfigMap object named my-connector-configuration contains connector properties:

    Example ConfigMap with connector properties
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: my-connector-configuration
    data:
      option1: value1
      option2: value2
  2. Specify the Kubernetes Configuration Provider in the Kafka Connect configuration.

    The specification shown here can support loading values from secrets and ConfigMaps.

    Example Kafka Connect configuration to enable the Kubernetes Configuration Provider
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaConnect
    metadata:
      name: my-connect
      annotations:
        strimzi.io/use-connector-resources: "true"
    spec:
      # ...
      config:
        # ...
        config.providers: secrets,configmaps # (1)
        config.providers.secrets.class: io.strimzi.kafka.KubernetesSecretConfigProvider # (2)
        config.providers.configmaps.class: io.strimzi.kafka.KubernetesConfigMapConfigProvider # (3)
      # ...
    1. The alias for the configuration provider is used to define other configuration parameters. The provider parameters use the alias from config.providers, taking the form config.providers.${alias}.class.

    2. KubernetesSecretConfigProvider provides values from secrets.

    3. KubernetesConfigMapConfigProvider provides values from config maps.

  3. Create or update the resource to enable the provider.

    kubectl apply -f <kafka_connect_configuration_file>
  4. Create a role that permits access to the values in the external config map.

    Example role to access values from a config map
    apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      name: connector-configuration-role
    rules:
    - apiGroups: [""]
      resources: ["configmaps"]
      resourceNames: ["my-connector-configuration"]
      verbs: ["get"]
    # ...

    The rule gives the role permission to access the my-connector-configuration config map.

  5. Create a role binding to permit access to the namespace that contains the config map.

    Example role binding to access the namespace that contains the config map
    apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      name: connector-configuration-role-binding
    subjects:
    - kind: ServiceAccount
      name: my-connect-connect
      namespace: my-project
    roleRef:
      kind: Role
      name: connector-configuration-role
      apiGroup: rbac.authorization.k8s.io
    # ...

    The role binding gives the role permission to access the my-project namespace.

    The service account must be the same one used by the Kafka Connect deployment. The service account name format is <cluster_name>-connect, where <cluster_name> is the name of the KafkaConnect custom resource.

  6. Reference the config map in the connector configuration.

    Example connector configuration referencing the config map
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaConnector
    metadata:
      name: my-connector
      labels:
        strimzi.io/cluster: my-connect
    spec:
      # ...
      config:
        option: ${configmaps:my-project/my-connector-configuration:option1}
        # ...
    # ...

    Placeholders for the property values in the config map are referenced in the connector configuration. The placeholder structure is configmaps:<path_and_file_name>:<property>. KubernetesConfigMapConfigProvider reads and extracts the option1 property value from the external config map.

3.2. Loading configuration values from environment variables

This procedure shows how to use the Environment Variables Configuration Provider plugin.

In the procedure, environment variables provide configuration properties for a connector. A database password is specified as an environment variable.

Prerequisites
  • A Kubernetes cluster is available.

  • A Kafka cluster is running.

  • The Cluster Operator is running.

Procedure
  1. Specify the Environment Variables Configuration Provider in the Kafka Connect configuration.

    Define environment variables using the externalConfiguration property.

    Example Kafka Connect configuration to enable the Environment Variables Configuration Provider
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaConnect
    metadata:
      name: my-connect
      annotations:
        strimzi.io/use-connector-resources: "true"
    spec:
      # ...
      config:
        # ...
        config.providers: env # (1)
        config.providers.env.class: io.strimzi.kafka.EnvVarConfigProvider # (2)
      # ...
      externalConfiguration:
        env:
          - name: DB_PASSWORD # (3)
            valueFrom:
              secretKeyRef:
                name: db-creds # (4)
                key: dbPassword # (5)
      # ...
    1. The alias for the configuration provider is used to define other configuration parameters. The provider parameters use the alias from config.providers, taking the form config.providers.${alias}.class.

    2. EnvVarConfigProvider provides values from environment variables.

    3. The DB_PASSWORD environment variable takes a password value from a secret.

    4. The name of the secret containing the predefined password.

    5. The key for the password stored inside the secret.

  2. Create or update the resource to enable the provider.

    kubectl apply -f <kafka_connect_configuration_file>
  3. Reference the environment variable in the connector configuration.

    Example connector configuration referencing the environment variable
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaConnector
    metadata:
      name: my-connector
      labels:
        strimzi.io/cluster: my-connect
    spec:
      # ...
      config:
        option: ${env:DB_PASSWORD}
        # ...
    # ...

4. Applying security context to Strimzi pods and containers

Security context defines constraints on pods and containers. By specifying a security context, pods and containers only have the permissions they need. For example, permissions can control runtime operations or access to resources.

4.1. How to configure security context

Use security provider plugins or template configuration to apply security context to Strimzi pods and containers.

Apply security context at the pod or container level:

Pod-level security context

Pod-level security context is applied to all containers in a specific pod.

Container-level security context

Container-level security context is applied to a specific container.

With Strimzi, security context is applied through one or both of the following methods:

Template configuration

Use template configuration of Strimzi custom resources to specify security context at the pod or container level.

Pod security provider plugins

Use pod security provider plugins to automatically set security context across all pods and containers using preconfigured settings.

Pod security providers offer a simpler alternative to specifying security context through template configuration. You can use both approaches. The template approach has a higher priority. Security context configured through template properties overrides the configuration set by pod security providers. So you might use pod security providers to automatically configure the security context for most containers. And also use template configuration to set container-specific security context where needed.

The template approach provides flexibility, but it also means you have to configure security context in numerous places to capture the security you want for all pods and containers. For example, you’ll need to apply the configuration to each pod in a Kafka cluster, as well as the pods for deployments of other Kafka components.

To avoid repeating the same configuration, you can use the following pod security provider plugins so that the security configuration is in one place.

Baseline Provider

The Baseline Provider is based on the Kubernetes baseline security profile. The baseline profile prevents privilege escalations and defines other standard access controls and limitations.

Restricted Provider

The Restricted Provider is based on the Kubernetes restricted security profile. The restricted profile is more restrictive than the baseline profile, and is used where security needs to be tighter.

For more information on the Kubernetes security profiles, see Pod security standards.

4.1.1. Template configuration for security context

In the following example, security context is configured for Kafka brokers in the template configuration of the Kafka resource. Security context is specified at the pod and container level.

Example template configuration for security context
apiVersion: {KafkaApiVersion}
kind: Kafka
metadata:
  name: my-cluster
spec:
  # ...
  kafka:
    template:
      pod: # (1)
        securityContext:
          runAsUser: 1000001
          fsGroup: 0
      kafkaContainer: # (2)
        securityContext:
          runAsUser: 2000
  # ...
  1. Pod security context

  2. Container security context of the Kafka broker container

4.1.2. Baseline Provider for pod security

The Baseline Provider is the default pod security provider. It configures the pods managed by Strimzi with a baseline security profile. The baseline profile is compatible with previous versions of Strimzi.

The Baseline Provider is enabled by default if you don’t specify a provider. Though you can enable it explicitly by setting the STRIMZI_POD_SECURITY_PROVIDER_CLASS environment variable to baseline when configuring the Cluster Operator.

Configuration for the Baseline Provider
# ...
env:
  # ...
  - name: STRIMZI_POD_SECURITY_PROVIDER_CLASS
    value: baseline
  # ...

Instead of specifying baseline as the value, you can specify the io.strimzi.plugin.security.profiles.impl.BaselinePodSecurityProvider fully-qualified domain name.

4.1.3. Restricted Provider for pod security

The Restricted Provider provides a higher level of security than the Baseline Provider. It configures the pods managed by Strimzi with a restricted security profile.

You enable the Restricted Provider by setting the STRIMZI_POD_SECURITY_PROVIDER_CLASS environment variable to restricted when configuring the Cluster Operator.

Configuration for the Restricted Provider
# ...
env:
  # ...
  - name: STRIMZI_POD_SECURITY_PROVIDER_CLASS
    value: restricted
  # ...

Instead of specifying restricted as the value, you can specify the io.strimzi.plugin.security.profiles.impl.RestrictedPodSecurityProvider fully-qualified domain name.

If you change to the Restricted Provider from the default Baseline Provider, the following restrictions are implemented in addition to the constraints defined in the baseline security profile:

  • Limits allowed volume types

  • Disallows privilege escalation

  • Requires applications to run under a non-root user

  • Requires seccomp (secure computing mode) profiles to be set as RuntimeDefault or Localhost

  • Limits container capabilities to use only the NET_BIND_SERVICE capability

With the Restricted Provider enabled, containers created by the Cluster Operator are set with the following security context.

Cluster Operator with restricted security context configuration
# ...
securityContext:
  allowPrivilegeEscalation: false
  capabilities:
    drop:
      - ALL
  runAsNonRoot: true
  seccompProfile:
    type: RuntimeDefault
# ...
Note

Container capabilities and seccomp are Linux kernel features that support container security.

  • Capabilities add fine-grained privileges for processes running on a container. The NET_BIND_SERVICE capability allows non-root user applications to bind to ports below 1024.

  • seccomp profiles limit the processes running in a container to only a subset of system calls. The RuntimeDefault profile provides a default set of system calls. A LocalHost profile uses a profile defined in a file on the node.

Additional resources

4.2. Enabling the Restricted Provider for the Cluster Operator

Security pod providers configure the security context constraints of the pods and containers created by the Cluster Operator. The Baseline Provider is the default pod security provider used by Strimzi. You can switch to the Restricted Provider by changing the STRIMZI_POD_SECURITY_PROVIDER_CLASS environment variable in the Cluster Operator configuration.

To make the required changes, configure the 060-Deployment-strimzi-cluster-operator.yaml Cluster Operator installation file located in install/cluster-operator/.

By enabling a new pod security provider, any pods or containers created by the Cluster Operator are subject to the limitations it imposes. Pods and containers that are already running are restarted for the changes to take affect.

Prerequisites
  • You need an account with permission to create and manage CustomResourceDefinition and RBAC (ClusterRole, and RoleBinding) resources.

Procedure

Edit the Deployment resource that is used to deploy the Cluster Operator, which is defined in the 060-Deployment-strimzi-cluster-operator.yaml file.

  1. Add or amend the STRIMZI_POD_SECURITY_PROVIDER_CLASS environment variable with a value of restricted.

    Cluster Operator configuration for the Restricted Provider
    # ...
    env:
      # ...
      - name: STRIMZI_POD_SECURITY_PROVIDER_CLASS
        value: restricted
      # ...

    Or you can specify the io.strimzi.plugin.security.profiles.impl.RestrictedPodSecurityProvider fully-qualified domain name.

  2. Deploy the Cluster Operator:

    kubectl create -f install/cluster-operator -n myproject
  3. (Optional) Use template configuration to set security context for specific components at the pod or container level.

    Adding security context through template configuration
    template:
      pod:
        securityContext:
          runAsUser: 1000001
          fsGroup: 0
      kafkaContainer:
        securityContext:
        runAsUser: 2000
      # ...

    If you apply specific security context for a component using template configuration, it takes priority over the general configuration provided by the pod security provider.

4.3. Implementing a custom pod security provider

If Strimzi’s Baseline Provider and Restricted Provider don’t quite match your needs, you can develop a custom pod security provider to deliver all-encompassing pod and container security context constraints.

Implement a custom pod security provider to apply your own security context profile. You can decide what applications and privileges to include in the profile.

Your custom pod security provider can implement the PodSecurityProvider.java interface that gets the security context for pods and containers; or it can extend the Baseline Provider or Restricted Provider classes.

The pod security provider plugins use the Java Service Provider Interface, so your custom pod security provider also requires a provider configuration file for service discovery.

To implement your own provider, the general steps include the following:

  1. Build the JAR file for the provider.

  2. Add the JAR file to the Cluster Operator image.

  3. Specify the custom pod security provider when setting the Cluster Operator environment variable STRIMZI_POD_SECURITY_PROVIDER_CLASS.

4.4. Handling of security context by Kubernetes platform

Handling of security context depends on the tooling of the Kubernetes platform you are using.

For example, OpenShift uses built-in security context constraints (SCCs) to control permissions. SCCs are the settings and strategies that control the security features a pod has access to.

By default, OpenShift injects security context configuration automatically. In most cases, this means you don’t need to configure security context for the pods and containers created by the Cluster Operator. Although you can still create and manage your own SCCs.

For more information, see the OpenShift documentation.

5. Using Strimzi Operators

Use the Strimzi operators to manage your Kafka cluster, and Kafka topics and users.

5.1. Watching namespaces with Strimzi operators

Operators watch and manage Strimzi resources in namespaces. The Cluster Operator can watch a single namespace, multiple namespaces, or all namespaces in a Kubernetes cluster. The Topic Operator and User Operator can watch a single namespace.

  • The Cluster Operator watches for Kafka resources

  • The Topic Operator watches for KafkaTopic resources

  • The User Operator watches for KafkaUser resources

The Topic Operator and the User Operator can only watch a single Kafka cluster in a namespace. And they can only be connected to a single Kafka cluster.

If multiple Topic Operators watch the same namespace, name collisions and topic deletion can occur. This is because each Kafka cluster uses Kafka topics that have the same name (such as __consumer_offsets). Make sure that only one Topic Operator watches a given namespace.

When using multiple User Operators with a single namespace, a user with a given username can exist in more than one Kafka cluster.

If you deploy the Topic Operator and User Operator using the Cluster Operator, they watch the Kafka cluster deployed by the Cluster Operator by default. You can also specify a namespace using watchedNamespace in the operator configuration.

For a standalone deployment of each operator, you specify a namespace and connection to the Kafka cluster to watch in the configuration.

5.2. Using the Cluster Operator

The Cluster Operator is used to deploy a Kafka cluster and other Kafka components.

For information on deploying the Cluster Operator, see Deploying the Cluster Operator.

5.2.1. Role-Based Access Control (RBAC) resources

The Cluster Operator creates and manages RBAC resources for Strimzi components that need access to Kubernetes resources.

For the Cluster Operator to function, it needs permission within the Kubernetes cluster to interact with Kafka resources, such as Kafka and KafkaConnect, as well as managed resources like ConfigMap, Pod, Deployment, StatefulSet, and Service.

Permission is specified through Kubernetes role-based access control (RBAC) resources:

  • ServiceAccount

  • Role and ClusterRole

  • RoleBinding and ClusterRoleBinding

Delegating privileges to Strimzi components

The Cluster Operator runs under a service account called strimzi-cluster-operator. It is assigned cluster roles that give it permission to create the RBAC resources for Strimzi components. Role bindings associate the cluster roles with the service account.

Kubernetes prevents components operating under one ServiceAccount from granting another ServiceAccount privileges that the granting ServiceAccount does not have. Because the Cluster Operator creates the RoleBinding and ClusterRoleBinding RBAC resources needed by the resources it manages, it requires a role that gives it the same privileges.

The following tables describe the RBAC resources created by the Cluster Operator.

Table 5. ServiceAccount resources
Name Used by

<cluster_name>-kafka

Kafka broker pods

<cluster_name>-zookeeper

ZooKeeper pods

<cluster_name>-cluster-connect

Kafka Connect pods

<cluster_name>-mirror-maker

MirrorMaker pods

<cluster_name>-mirrormaker2

MirrorMaker 2.0 pods

<cluster_name>-bridge

Kafka Bridge pods

<cluster_name>-entity-operator

Entity Operator

Table 6. ClusterRole resources
Name Used by

strimzi-cluster-operator-namespaced

Cluster Operator

strimzi-cluster-operator-global

Cluster Operator

strimzi-cluster-operator-leader-election

Cluster Operator

strimzi-kafka-broker

Cluster Operator, rack feature (when used)

strimzi-entity-operator

Cluster Operator, Topic Operator, User Operator

strimzi-kafka-client

Cluster Operator, Kafka clients for rack awareness

Table 7. ClusterRoleBinding resources
Name Used by

strimzi-cluster-operator

Cluster Operator

strimzi-cluster-operator-kafka-broker-delegation

Cluster Operator, Kafka brokers for rack awareness

strimzi-cluster-operator-kafka-client-delegation

Cluster Operator, Kafka clients for rack awareness

Table 8. RoleBinding resources
Name Used by

strimzi-cluster-operator

Cluster Operator

strimzi-cluster-operator-kafka-broker-delegation

Cluster Operator, Kafka brokers for rack awareness

Running the Cluster Operator using a ServiceAccount

The Cluster Operator is best run using a ServiceAccount:

Example ServiceAccount for the Cluster Operator
apiVersion: v1
kind: ServiceAccount
metadata:
  name: strimzi-cluster-operator
  labels:
    app: strimzi

The Deployment of the operator then needs to specify this in its spec.template.spec.serviceAccountName:

Partial example of Deployment for the Cluster Operator
apiVersion: apps/v1
kind: Deployment
metadata:
  name: strimzi-cluster-operator
  labels:
    app: strimzi
spec:
  replicas: 1
  selector:
    matchLabels:
      name: strimzi-cluster-operator
      strimzi.io/kind: cluster-operator
  template:
      # ...

Note line 12, where strimzi-cluster-operator is specified as the serviceAccountName.

ClusterRole resources

The Cluster Operator uses ClusterRole resources to provide the necessary access to resources. Depending on the Kubernetes cluster setup, a cluster administrator might be needed to create the cluster roles.

Note
Cluster administrator rights are only needed for the creation of ClusterRole resources. The Cluster Operator will not run under a cluster admin account.

ClusterRole resources follow the principle of least privilege and contain only those privileges needed by the Cluster Operator to operate the cluster of the Kafka component. The first set of assigned privileges allow the Cluster Operator to manage Kubernetes resources such as StatefulSet, Deployment, Pod, and ConfigMap.

All cluster roles are required by the Cluster Operator in order to delegate privileges.

The Cluster Operator uses the strimzi-cluster-operator-namespaced and strimzi-cluster-operator-global cluster roles to grant permission at the namespace-scoped resources level and cluster-scoped resources level.

ClusterRole with namespaced resources for the Cluster Operator
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: strimzi-cluster-operator-namespaced
  labels:
    app: strimzi
rules:
  # Resources in this role are used by the operator based on an operand being deployed in some namespace. When needed, you
  # can deploy the operator as a cluster-wide operator. But grant the rights listed in this role only on the namespaces
  # where the operands will be deployed. That way, you can limit the access the operator has to other namespaces where it
  # does not manage any clusters.
  - apiGroups:
      - "rbac.authorization.k8s.io"
    resources:
      # The cluster operator needs to access and manage rolebindings to grant Strimzi components cluster permissions
      - rolebindings
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - "rbac.authorization.k8s.io"
    resources:
      # The cluster operator needs to access and manage roles to grant the entity operator permissions
      - roles
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - ""
    resources:
      # The cluster operator needs to access and delete pods, this is to allow it to monitor pod health and coordinate rolling updates
      - pods
      # The cluster operator needs to access and manage service accounts to grant Strimzi components cluster permissions
      - serviceaccounts
      # The cluster operator needs to access and manage config maps for Strimzi components configuration
      - configmaps
      # The cluster operator needs to access and manage services and endpoints to expose Strimzi components to network traffic
      - services
      - endpoints
      # The cluster operator needs to access and manage secrets to handle credentials
      - secrets
      # The cluster operator needs to access and manage persistent volume claims to bind them to Strimzi components for persistent data
      - persistentvolumeclaims
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - "apps"
    resources:
      # The cluster operator needs to access and manage deployments to run deployment based Strimzi components
      - deployments
      - deployments/scale
      - deployments/status
      # The cluster operator needs to access and manage stateful sets to run stateful sets based Strimzi components
      - statefulsets
      # The cluster operator needs to access replica-sets to manage Strimzi components and to determine error states
      - replicasets
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - "" # legacy core events api, used by topic operator
      - "events.k8s.io" # new events api, used by cluster operator
    resources:
      # The cluster operator needs to be able to create events and delegate permissions to do so
      - events
    verbs:
      - create
  - apiGroups:
      # Kafka Connect Build on OpenShift requirement
      - build.openshift.io
    resources:
      - buildconfigs
      - buildconfigs/instantiate
      - builds
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - networking.k8s.io
    resources:
      # The cluster operator needs to access and manage network policies to lock down communication between Strimzi components
      - networkpolicies
      # The cluster operator needs to access and manage ingresses which allow external access to the services in a cluster
      - ingresses
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - route.openshift.io
    resources:
      # The cluster operator needs to access and manage routes to expose Strimzi components for external access
      - routes
      - routes/custom-host
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - image.openshift.io
    resources:
      # The cluster operator needs to verify the image stream when used for Kafka Connect image build
      - imagestreams
    verbs:
      - get
  - apiGroups:
      - policy
    resources:
      # The cluster operator needs to access and manage pod disruption budgets this limits the number of concurrent disruptions
      # that a Strimzi component experiences, allowing for higher availability
      - poddisruptionbudgets
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
ClusterRole with cluster-scoped resources for the Cluster Operator
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: strimzi-cluster-operator-global
  labels:
    app: strimzi
rules:
  - apiGroups:
      - "rbac.authorization.k8s.io"
    resources:
      # The cluster operator needs to create and manage cluster role bindings in the case of an install where a user
      # has specified they want their cluster role bindings generated
      - clusterrolebindings
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update
  - apiGroups:
      - storage.k8s.io
    resources:
      # The cluster operator requires "get" permissions to view storage class details
      # This is because only a persistent volume of a supported storage class type can be resized
      - storageclasses
    verbs:
      - get
  - apiGroups:
      - ""
    resources:
      # The cluster operator requires "list" permissions to view all nodes in a cluster
      # The listing is used to determine the node addresses when NodePort access is configured
      # These addresses are then exposed in the custom resource states
      - nodes
    verbs:
      - list

The strimzi-cluster-operator-leader-election cluster role represents the permissions needed for the leader election.

ClusterRole with leader election permissions
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: strimzi-cluster-operator-leader-election
  labels:
    app: strimzi
rules:
  - apiGroups:
      - coordination.k8s.io
    resources:
      # The cluster operator needs to access and manage leases for leader election
      # The "create" verb cannot be used with "resourceNames"
      - leases
    verbs:
      - create
  - apiGroups:
      - coordination.k8s.io
    resources:
      # The cluster operator needs to access and manage leases for leader election
      - leases
    resourceNames:
      # The default RBAC files give the operator only access to the Lease resource names strimzi-cluster-operator
      # If you want to use another resource name or resource namespace, you have to configure the RBAC resources accordingly
      - strimzi-cluster-operator
    verbs:
      - get
      - list
      - watch
      - delete
      - patch
      - update

The strimzi-kafka-broker cluster role represents the access needed by the init container in Kafka pods that use rack awareness.

A role binding named strimzi-<cluster_name>-kafka-init grants the <cluster_name>-kafka service account access to nodes within a cluster using the strimzi-kafka-broker role. If the rack feature is not used and the cluster is not exposed through nodeport, no binding is created.

ClusterRole for the Cluster Operator allowing it to delegate access to Kubernetes nodes to the Kafka broker pods
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: strimzi-kafka-broker
  labels:
    app: strimzi
rules:
  - apiGroups:
      - ""
    resources:
      # The Kafka Brokers require "get" permissions to view the node they are on
      # This information is used to generate a Rack ID that is used for High Availability configurations
      - nodes
    verbs:
      - get

The strimzi-entity-operator cluster role represents the access needed by the Topic Operator and User Operator.

The Topic Operator produces Kubernetes events with status information, so the <cluster_name>-entity-operator service account is bound to the strimzi-entity-operator role, which grants this access via the strimzi-entity-operator role binding.

ClusterRole for the Cluster Operator allowing it to delegate access to events to the Topic and User Operators
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: strimzi-entity-operator
  labels:
    app: strimzi
rules:
  - apiGroups:
      - "kafka.strimzi.io"
    resources:
      # The entity operator runs the KafkaTopic assembly operator, which needs to access and manage KafkaTopic resources
      - kafkatopics
      - kafkatopics/status
      # The entity operator runs the KafkaUser assembly operator, which needs to access and manage KafkaUser resources
      - kafkausers
      - kafkausers/status
    verbs:
      - get
      - list
      - watch
      - create
      - patch
      - update
      - delete
  - apiGroups:
      - ""
    resources:
      - events
    verbs:
      # The entity operator needs to be able to create events
      - create
  - apiGroups:
      - ""
    resources:
      # The entity operator user-operator needs to access and manage secrets to store generated credentials
      - secrets
    verbs:
      - get
      - list
      - watch
      - create
      - delete
      - patch
      - update

The strimzi-kafka-client cluster role represents the access needed by Kafka clients that use rack awareness.

ClusterRole for the Cluster Operator allowing it to delegate access to Kubernetes nodes to the Kafka client-based pods
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: strimzi-kafka-client
  labels:
    app: strimzi
rules:
  - apiGroups:
      - ""
    resources:
      # The Kafka clients (Connect, Mirror Maker, etc.) require "get" permissions to view the node they are on
      # This information is used to generate a Rack ID (client.rack option) that is used for consuming from the closest
      # replicas when enabled
      - nodes
    verbs:
      - get
ClusterRoleBinding resources

The Cluster Operator uses ClusterRoleBinding and RoleBinding resources to associate its ClusterRole with its ServiceAccount: Cluster role bindings are required by cluster roles containing cluster-scoped resources.

Example ClusterRoleBinding for the Cluster Operator
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: strimzi-cluster-operator
  labels:
    app: strimzi
subjects:
  - kind: ServiceAccount
    name: strimzi-cluster-operator
    namespace: myproject
roleRef:
  kind: ClusterRole
  name: strimzi-cluster-operator-global
  apiGroup: rbac.authorization.k8s.io

Cluster role bindings are also needed for the cluster roles used in delegating privileges:

Example ClusterRoleBinding for the Cluster Operator and Kafka broker rack awareness
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: strimzi-cluster-operator-kafka-broker-delegation
  labels:
    app: strimzi
# The Kafka broker cluster role must be bound to the cluster operator service account so that it can delegate the cluster role to the Kafka brokers.
# This must be done to avoid escalating privileges which would be blocked by Kubernetes.
subjects:
  - kind: ServiceAccount
    name: strimzi-cluster-operator
    namespace: myproject
roleRef:
  kind: ClusterRole
  name: strimzi-kafka-broker
  apiGroup: rbac.authorization.k8s.io
Example ClusterRoleBinding for the Cluster Operator and Kafka client rack awareness
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: strimzi-cluster-operator-kafka-client-delegation
  labels:
    app: strimzi
# The Kafka clients cluster role must be bound to the cluster operator service account so that it can delegate the
# cluster role to the Kafka clients using it for consuming from closest replica.
# This must be done to avoid escalating privileges which would be blocked by Kubernetes.
subjects:
  - kind: ServiceAccount
    name: strimzi-cluster-operator
    namespace: myproject
roleRef:
  kind: ClusterRole
  name: strimzi-kafka-client
  apiGroup: rbac.authorization.k8s.io

Cluster roles containing only namespaced resources are bound using role bindings only.

Example RoleBinding for the Cluster Operator
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: strimzi-cluster-operator
  labels:
    app: strimzi
subjects:
  - kind: ServiceAccount
    name: strimzi-cluster-operator
    namespace: myproject
roleRef:
  kind: ClusterRole
  name: strimzi-cluster-operator-namespaced
  apiGroup: rbac.authorization.k8s.io
Example RoleBinding for the Cluster Operator and Kafka broker rack awareness
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: strimzi-cluster-operator-entity-operator-delegation
  labels:
    app: strimzi
# The Entity Operator cluster role must be bound to the cluster operator service account so that it can delegate the cluster role to the Entity Operator.
# This must be done to avoid escalating privileges which would be blocked by Kubernetes.
subjects:
  - kind: ServiceAccount
    name: strimzi-cluster-operator
    namespace: myproject
roleRef:
  kind: ClusterRole
  name: strimzi-entity-operator
  apiGroup: rbac.authorization.k8s.io

5.2.2. ConfigMap for Cluster Operator logging

Cluster Operator logging is configured through a ConfigMap named strimzi-cluster-operator.

A ConfigMap containing logging configuration is created when installing the Cluster Operator. This ConfigMap is described in the file install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml. You configure Cluster Operator logging by changing the data field log4j2.properties in this ConfigMap.

To update the logging configuration, you can edit the 050-ConfigMap-strimzi-cluster-operator.yaml file and then run the following command:

kubectl create -f install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml

Alternatively, edit the ConfigMap directly:

kubectl edit configmap strimzi-cluster-operator

To change the frequency of the reload interval, set a time in seconds in the monitorInterval option in the created ConfigMap.

If the ConfigMap is missing when the Cluster Operator is deployed, the default logging values are used.

If the ConfigMap is accidentally deleted after the Cluster Operator is deployed, the most recently loaded logging configuration is used. Create a new ConfigMap to load a new logging configuration.

Note
Do not remove the monitorInterval option from the ConfigMap.

5.2.3. Configuring the Cluster Operator with environment variables

You can configure the Cluster Operator using environment variables. The supported environment variables are listed here.

Note
The environment variables relate to the container configuration for the deployment of the Cluster Operator image. For more information on image configuration, see, image.
STRIMZI_NAMESPACE

A comma-separated list of namespaces that the operator operates in. When not set, set to empty string, or set to *, the Cluster Operator operates in all namespaces.

The Cluster Operator deployment might use the downward API to set this automatically to the namespace the Cluster Operator is deployed in.

Example configuration for Cluster Operator namespaces
env:
  - name: STRIMZI_NAMESPACE
    valueFrom:
      fieldRef:
        fieldPath: metadata.namespace
STRIMZI_FULL_RECONCILIATION_INTERVAL_MS

Optional, default is 120000 ms. The interval between periodic reconciliations, in milliseconds.

STRIMZI_OPERATION_TIMEOUT_MS

Optional, default 300000 ms. The timeout for internal operations, in milliseconds. Increase this value when using Strimzi on clusters where regular Kubernetes operations take longer than usual (because of slow downloading of Docker images, for example).

STRIMZI_ZOOKEEPER_ADMIN_SESSION_TIMEOUT_MS

Optional, default 10000 ms. The session timeout for the Cluster Operator’s ZooKeeper admin client, in milliseconds. Increase the value if ZooKeeper requests from the Cluster Operator are regularly failing due to timeout issues. There is a maximum allowed session time set on the ZooKeeper server side via the maxSessionTimeout config. By default, the maximum session timeout value is 20 times the default tickTime (whose default is 2000) at 40000 ms. If you require a higher timeout, change the maxSessionTimeout ZooKeeper server configuration value.

STRIMZI_OPERATIONS_THREAD_POOL_SIZE

Optional, default 10. The worker thread pool size, which is used for various asynchronous and blocking operations that are run by the Cluster Operator.

STRIMZI_OPERATOR_NAME

Optional, defaults to the pod’s hostname. The operator name identifies the Strimzi instance when emitting Kubernetes events.

STRIMZI_OPERATOR_NAMESPACE

The name of the namespace where the Cluster Operator is running. Do not configure this variable manually. Use the downward API.

env:
  - name: STRIMZI_OPERATOR_NAMESPACE
    valueFrom:
      fieldRef:
        fieldPath: metadata.namespace
STRIMZI_OPERATOR_NAMESPACE_LABELS

Optional. The labels of the namespace where the Strimzi Cluster Operator is running. Use namespace labels to configure the namespace selector in network policies. Network policies allow the Strimzi Cluster Operator access only to the operands from the namespace with these labels. When not set, the namespace selector in network policies is configured to allow access to the Cluster Operator from any namespace in the Kubernetes cluster.

env:
  - name: STRIMZI_OPERATOR_NAMESPACE_LABELS
    value: label1=value1,label2=value2
STRIMZI_LABELS_EXCLUSION_PATTERN

Optional, default regex pattern is ^app.kubernetes.io/(?!part-of).*. The regex exclusion pattern used to filter labels propagation from the main custom resource to its subresources. The labels exclusion filter is not applied to labels in template sections such as spec.kafka.template.pod.metadata.labels.

env:
  - name: STRIMZI_LABELS_EXCLUSION_PATTERN
    value: "^key1.*"
STRIMZI_CUSTOM_{COMPONENT_NAME}_LABELS

Optional. One or more custom labels to apply to all the pods created by the {COMPONENT_NAME} custom resource. The Cluster Operator labels the pods when the custom resource is created or is next reconciled.

Labels can be applied to the following components:

  • KAFKA

  • KAFKA_CONNECT

  • KAFKA_CONNECT_BUILD

  • ZOOKEEPER

  • ENTITY_OPERATOR

  • KAFKA_MIRROR_MAKER2

  • KAFKA_MIRROR_MAKER

  • CRUISE_CONTROL

  • KAFKA_BRIDGE

  • KAFKA_EXPORTER

  • JMX_TRANS

STRIMZI_CUSTOM_RESOURCE_SELECTOR

Optional. The label selector to filter the custom resources handled by the Cluster Operator. The operator will operate only on those custom resources that have the specified labels set. Resources without these labels will not be seen by the operator. The label selector applies to Kafka, KafkaConnect, KafkaBridge, KafkaMirrorMaker, and KafkaMirrorMaker2 resources. KafkaRebalance and KafkaConnector resources are operated only when their corresponding Kafka and Kafka Connect clusters have the matching labels.

env:
  - name: STRIMZI_CUSTOM_RESOURCE_SELECTOR
    value: label1=value1,label2=value2
STRIMZI_KAFKA_IMAGES

Required. The mapping from the Kafka version to the corresponding Docker image containing a Kafka broker for that version. The required syntax is whitespace or comma-separated <version>=<image> pairs. For example 3.2.3=quay.io/strimzi/kafka:latest-kafka-3.2.3, 3.3.2=quay.io/strimzi/kafka:latest-kafka-3.3.2. This is used when a Kafka.spec.kafka.version property is specified but not the Kafka.spec.kafka.image in the Kafka resource.

STRIMZI_DEFAULT_KAFKA_INIT_IMAGE

Optional, default quay.io/strimzi/operator:latest. The image name to use as default for the init container if no image is specified as the kafka-init-image in the Kafka resource. The init container is started before the broker for initial configuration work, such as rack support.

STRIMZI_KAFKA_CONNECT_IMAGES

Required. The mapping from the Kafka version to the corresponding Docker image of Kafka Connect for that version. The required syntax is whitespace or comma-separated <version>=<image> pairs. For example 3.2.3=quay.io/strimzi/kafka:latest-kafka-3.2.3, 3.3.2=quay.io/strimzi/kafka:latest-kafka-3.3.2. This is used when a KafkaConnect.spec.version property is specified but not the KafkaConnect.spec.image.

STRIMZI_KAFKA_MIRROR_MAKER_IMAGES

Required. The mapping from the Kafka version to the corresponding Docker image of MirrorMaker for that version. The required syntax is whitespace or comma-separated <version>=<image> pairs. For example 3.2.3=quay.io/strimzi/kafka:latest-kafka-3.2.3, 3.3.2=quay.io/strimzi/kafka:latest-kafka-3.3.2. This is used when a KafkaMirrorMaker.spec.version property is specified but not the KafkaMirrorMaker.spec.image.

STRIMZI_DEFAULT_TOPIC_OPERATOR_IMAGE

Optional, default quay.io/strimzi/operator:latest. The image name to use as the default when deploying the Topic Operator if no image is specified as the Kafka.spec.entityOperator.topicOperator.image in the Kafka resource.

STRIMZI_DEFAULT_USER_OPERATOR_IMAGE

Optional, default quay.io/strimzi/operator:latest. The image name to use as the default when deploying the User Operator if no image is specified as the Kafka.spec.entityOperator.userOperator.image in the Kafka resource.

STRIMZI_DEFAULT_TLS_SIDECAR_ENTITY_OPERATOR_IMAGE

Optional, default quay.io/strimzi/kafka:latest-kafka-3.3.2. The image name to use as the default when deploying the sidecar container for the Entity Operator if no image is specified as the Kafka.spec.entityOperator.tlsSidecar.image in the Kafka resource. The sidecar provides TLS support.

STRIMZI_IMAGE_PULL_POLICY

Optional. The ImagePullPolicy that is applied to containers in all pods managed by the Cluster Operator. The valid values are Always, IfNotPresent, and Never. If not specified, the Kubernetes defaults are used. Changing the policy will result in a rolling update of all your Kafka, Kafka Connect, and Kafka MirrorMaker clusters.

STRIMZI_IMAGE_PULL_SECRETS

Optional. A comma-separated list of Secret names. The secrets referenced here contain the credentials to the container registries where the container images are pulled from. The secrets are specified in the imagePullSecrets property for all pods created by the Cluster Operator. Changing this list results in a rolling update of all your Kafka, Kafka Connect, and Kafka MirrorMaker clusters.

STRIMZI_KUBERNETES_VERSION

Optional. Overrides the Kubernetes version information detected from the API server.

Example configuration for Kubernetes version override
env:
  - name: STRIMZI_KUBERNETES_VERSION
    value: |
           major=1
           minor=16
           gitVersion=v1.16.2
           gitCommit=c97fe5036ef3df2967d086711e6c0c405941e14b
           gitTreeState=clean
           buildDate=2019-10-15T19:09:08Z
           goVersion=go1.12.10
           compiler=gc
           platform=linux/amd64
KUBERNETES_SERVICE_DNS_DOMAIN

Optional. Overrides the default Kubernetes DNS domain name suffix.

By default, services assigned in the Kubernetes cluster have a DNS domain name that uses the default suffix cluster.local.

For example, for broker kafka-0:

<cluster-name>-kafka-0.<cluster-name>-kafka-brokers.<namespace>.svc.cluster.local

The DNS domain name is added to the Kafka broker certificates used for hostname verification.

If you are using a different DNS domain name suffix in your cluster, change the KUBERNETES_SERVICE_DNS_DOMAIN environment variable from the default to the one you are using in order to establish a connection with the Kafka brokers.

STRIMZI_CONNECT_BUILD_TIMEOUT_MS

Optional, default 300000 ms. The timeout for building new Kafka Connect images with additional connectors, in milliseconds. Consider increasing this value when using Strimzi to build container images containing many connectors or using a slow container registry.

STRIMZI_NETWORK_POLICY_GENERATION

Optional, default true. Network policy for resources. Network policies allow connections between Kafka components.

Set this environment variable to false to disable network policy generation. You might do this, for example, if you want to use custom network policies. Custom network policies allow more control over maintaining the connections between components.

STRIMZI_DNS_CACHE_TTL

Optional, default 30. Number of seconds to cache successful name lookups in local DNS resolver. Any negative value means cache forever. Zero means do not cache, which can be useful for avoiding connection errors due to long caching policies being applied.

STRIMZI_POD_SET_RECONCILIATION_ONLY

Optional, default false. When set to true, the Cluster Operator reconciles only the StrimziPodSet resources and any changes to the other custom resources (Kafka, KafkaConnect, and so on) are ignored. This mode is useful for ensuring that your pods are recreated if needed, but no other changes happen to the clusters.

STRIMZI_FEATURE_GATES

Optional. Enables or disables the features and functionality controlled by feature gates.

STRIMZI_POD_SECURITY_PROVIDER_CLASS

Optional. Configuration for the pluggable PodSecurityProvider class, which can be used to provide the security context configuration for Pods and containers.

Leader election environment variables

Use leader election environment variables when running additional Cluster Operator replicas. You might run additional replicas to safeguard against disruption caused by major failure.

STRIMZI_LEADER_ELECTION_ENABLED

Optional, disabled (false) by default. Enables or disables leader election, which allows additional Cluster Operator replicas to run on standby.

Note
Leader election is disabled by default. It is only enabled when applying this environment variable on installation.
STRIMZI_LEADER_ELECTION_LEASE_NAME

Required when leader election is enabled. The name of the Kubernetes Lease resource that is used for the leader election.

STRIMZI_LEADER_ELECTION_LEASE_NAMESPACE

Required when leader election is enabled. The namespace where the Kubernetes Lease resource used for leader election is created. You can use the downward API to configure it to the namespace where the Cluster Operator is deployed.

env:
  - name: STRIMZI_LEADER_ELECTION_LEASE_NAMESPACE
    valueFrom:
      fieldRef:
        fieldPath: metadata.namespace
STRIMZI_LEADER_ELECTION_IDENTITY

Required when leader election is enabled. Configures the identity of a given Cluster Operator instance used during the leader election. The identity must be unique for each operator instance. You can use the downward API to configure it to the name of the pod where the Cluster Operator is deployed.

env:
  - name: STRIMZI_LEADER_ELECTION_IDENTITY
    valueFrom:
      fieldRef:
        fieldPath: metadata.name
STRIMZI_LEADER_ELECTION_LEASE_DURATION_MS

Optional, default 15000 ms. Specifies the duration the acquired lease is valid.

STRIMZI_LEADER_ELECTION_RENEW_DEADLINE_MS

Optional, default 10000 ms. Specifies the period the leader should try to maintain leadership.

STRIMZI_LEADER_ELECTION_RETRY_PERIOD_MS

Optional, default 2000 ms. Specifies the frequency of updates to the lease lock by the leader.

Restricting Cluster Operator access with network policy

Use the STRIMZI_OPERATOR_NAMESPACE_LABELS environment variable to establish network policy for the Cluster Operator using namespace labels.

The Cluster Operator can run in the same namespace as the resources it manages, or in a separate namespace. By default, the STRIMZI_OPERATOR_NAMESPACE environment variable is configured to use the downward API to find the namespace the Cluster Operator is running in. If the Cluster Operator is running in the same namespace as the resources, only local access is required and allowed by Strimzi.

If the Cluster Operator is running in a separate namespace to the resources it manages, any namespace in the Kubernetes cluster is allowed access to the Cluster Operator unless network policy is configured. By adding namespace labels, access to the Cluster Operator is restricted to the namespaces specified.

Network policy configured for the Cluster Operator deployment
#...
env:
  # ...
  - name: STRIMZI_OPERATOR_NAMESPACE_LABELS
    value: label1=value1,label2=value2
  #...
Setting the time interval for periodic reconciliation

Use the STRIMZI_FULL_RECONCILIATION_INTERVAL_MS variable to set the time interval for periodic reconciliations.

The Cluster Operator reacts to all notifications about applicable cluster resources received from the Kubernetes cluster. If the operator is not running, or if a notification is not received for any reason, resources will get out of sync with the state of the running Kubernetes cluster. In order to handle failovers properly, a periodic reconciliation process is executed by the Cluster Operator so that it can compare the state of the resources with the current cluster deployments in order to have a consistent state across all of them.

Additional resources

5.2.4. Configuring the Cluster Operator with default proxy settings

If you are running a Kafka cluster behind a HTTP proxy, you can still pass data in and out of the cluster. For example, you can run Kafka Connect with connectors that push and pull data from outside the proxy. Or you can use a proxy to connect with an authorization server.

Configure the Cluster Operator deployment to specify the proxy environment variables. The Cluster Operator accepts standard proxy configuration (HTTP_PROXY, HTTPS_PROXY and NO_PROXY) as environment variables. The proxy settings are applied to all Strimzi containers.

The format for a proxy address is http://IP-ADDRESS:PORT-NUMBER. To set up a proxy with a name and password, the format is http://USERNAME:PASSWORD@IP-ADDRESS:PORT-NUMBER.

Prerequisites
  • You need an account with permission to create and manage CustomResourceDefinition and RBAC (ClusterRole, and RoleBinding) resources.

Procedure
  1. To add proxy environment variables to the Cluster Operator, update its Deployment configuration (install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml).

    Example proxy configuration for the Cluster Operator
    apiVersion: apps/v1
    kind: Deployment
    spec:
      # ...
      template:
        spec:
          serviceAccountName: strimzi-cluster-operator
          containers:
            # ...
            env:
            # ...
            - name: "HTTP_PROXY"
              value: "http://proxy.com" (1)
            - name: "HTTPS_PROXY"
              value: "https://proxy.com" (2)
            - name: "NO_PROXY"
              value: "internal.com, other.domain.com" (3)
      # ...
    1. Address of the proxy server.

    2. Secure address of the proxy server.

    3. Addresses for servers that are accessed directly as exceptions to the proxy server. The URLs are comma-separated.

    Alternatively, edit the Deployment directly:

    kubectl edit deployment strimzi-cluster-operator
  2. If you updated the YAML file instead of editing the Deployment directly, apply the changes:

    kubectl create -f install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml

5.2.5. Running multiple Cluster Operator replicas with leader election

The default Cluster Operator configuration enables leader election. Use leader election to run multiple parallel replicas of the Cluster Operator. One replica is elected as the active leader and operates the deployed resources. The other replicas run in standby mode. When the leader stops or fails, one of the standby replicas is elected as the new leader and starts operating the deployed resources.

By default, Strimzi runs with a single Cluster Operator replica that is always the leader replica. When a single Cluster Operator replica stops or fails, Kubernetes starts a new replica.

Running the Cluster Operator with multiple replicas is not essential. But it’s useful to have replicas on standby in case of large-scale disruptions. For example, suppose multiple worker nodes or an entire availability zone fails. This failure might cause the Cluster Operator pod and many Kafka pods to go down at the same time. If subsequent pod scheduling causes congestion through lack of resources, this can delay operations when running a single Cluster Operator.

Configuring Cluster Operator replicas

To run additional Cluster Operator replicas in standby mode, you will need to increase the number of replicas and enable leader election. To configure leader election, use the leader election environment variables.

To make the required changes, configure the following Cluster Operator installation files located in install/cluster-operator/:

  • 060-Deployment-strimzi-cluster-operator.yaml

  • 022-ClusterRole-strimzi-cluster-operator-role.yaml

  • 022-RoleBinding-strimzi-cluster-operator.yaml

Leader election has its own ClusterRole and RoleBinding RBAC resources that target the namespace where the Cluster Operator is running, rather than the namespace it is watching.

The default deployment configuration creates a Lease resource called strimzi-cluster-operator in the same namespace as the Cluster Operator. The Cluster Operator uses leases to manage leader election. The RBAC resources provide the permissions to use the Lease resource. If you use a different Lease name or namespace, update the ClusterRole and RoleBinding files accordingly.

Prerequisites
  • You need an account with permission to create and manage CustomResourceDefinition and RBAC (ClusterRole, and RoleBinding) resources.

Procedure

Edit the Deployment resource that is used to deploy the Cluster Operator, which is defined in the 060-Deployment-strimzi-cluster-operator.yaml file.

  1. Change the replicas property from the default (1) to a value that matches the required number of replicas.

    Increasing the number of Cluster Operator replicas
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: strimzi-cluster-operator
      labels:
        app: strimzi
    spec:
      replicas: 3
  2. Check that the leader election env properties are set.

    If they are not set, configure them.

    To enable leader election, STRIMZI_LEADER_ELECTION_ENABLED must be set to true (default).

    In this example, the name of the lease is changed to my-strimzi-cluster-operator.

    Configuring leader election environment variables for the Cluster Operator
    # ...
    spec
      containers:
        - name: strimzi-cluster-operator
          # ...
          env:
            - name: STRIMZI_LEADER_ELECTION_ENABLED
              value: "true"
            - name: STRIMZI_LEADER_ELECTION_LEASE_NAME
              value: "my-strimzi-cluster-operator"
            - name: STRIMZI_LEADER_ELECTION_LEASE_NAMESPACE
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
            - name: STRIMZI_LEADER_ELECTION_IDENTITY
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name

    For a description of the available environment variables, see Leader election environment variables.

    If you specified a different name or namespace for the Lease resource used in leader election, update the RBAC resources.

  3. (optional) Edit the ClusterRole resource in the 022-ClusterRole-strimzi-cluster-operator-role.yaml file.

    Update resourceNames with the name of the Lease resource.

    Updating the ClusterRole references to the lease
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
      name: strimzi-cluster-operator-leader-election
      labels:
        app: strimzi
    rules:
      - apiGroups:
          - coordination.k8s.io
        resourceNames:
          - my-strimzi-cluster-operator
    # ...
  4. (optional) Edit the RoleBinding resource in the 022-RoleBinding-strimzi-cluster-operator.yaml file.

    Update subjects.name and subjects.namespace with the name of the Lease resource and the namespace where it was created.

    Updating the RoleBinding references to the lease
    apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      name: strimzi-cluster-operator-leader-election
      labels:
        app: strimzi
    subjects:
      - kind: ServiceAccount
        name: my-strimzi-cluster-operator
        namespace: myproject
    # ...
  5. Deploy the Cluster Operator:

    kubectl create -f install/cluster-operator -n myproject
  6. Check the status of the deployment:

    kubectl get deployments -n myproject
    Output shows the deployment name and readiness
    NAME                      READY  UP-TO-DATE  AVAILABLE
    strimzi-cluster-operator  3/3    3           3

    READY shows the number of replicas that are ready/expected. The deployment is successful when the AVAILABLE output shows the correct number of replicas.

5.2.6. FIPS support

Federal Information Processing Standards (FIPS) are standards for computer security and interoperability. When running Strimzi on a FIPS-enabled Kubernetes cluster, the OpenJDK used in Strimzi container images automatically switches to FIPS mode. From version 0.33, Strimzi can run on FIPS-enabled Kubernetes clusters without any changes or special configuration. It uses only the FIPS-compliant security libraries from the OpenJDK.

Minimum password length

When running in the FIPS mode, SCRAM-SHA-512 passwords need to be at least 32 characters long. From Strimzi 0.33, the default password length in Strimzi User Operator is set to 32 characters as well. If you have a Kafka cluster with custom configuration that uses a password length that is less than 32 characters, you need to update your configuration. If you have any users with passwords shorter than 32 characters, you need to regenerate a password with the required length. You can do that, for example, by deleting the user secret and waiting for the User Operator to create a new password with the appropriate length.

Disabling FIPS mode

Strimzi automatically switches to FIPS mode when running on a FIPS-enabled Kubernetes cluster. Disable FIPS mode by setting the FIPS_MODE environment variable to disabled in the deployment configuration for the Cluster Operator. With FIPS mode disabled, Strimzi automatically disables FIPS in the OpenJDK for all components. With FIPS mode disabled, Strimzi is not FIPS compliant. The Strimzi operators, as well as all operands, run in the same way as if they were running on an Kubernetes cluster without FIPS enabled.

Procedure
  1. To disable the FIPS mode in the Cluster Operator, update its Deployment configuration (install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml) and add the FIPS_MODE environment variable.

    Example FIPS configuration for the Cluster Operator
    apiVersion: apps/v1
    kind: Deployment
    spec:
      # ...
      template:
        spec:
          serviceAccountName: strimzi-cluster-operator
          containers:
            # ...
            env:
            # ...
            - name: "FIPS_MODE"
              value: "disabled" # (1)
      # ...
    1. Disables the FIPS mode.

    Alternatively, edit the Deployment directly:

    kubectl edit deployment strimzi-cluster-operator
  2. If you updated the YAML file instead of editing the Deployment directly, apply the changes:

    kubectl apply -f install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml

5.3. Using the Topic Operator

When you create, modify or delete a topic using the KafkaTopic resource, the Topic Operator ensures those changes are reflected in the Kafka cluster.

For more information on the KafkaTopic resource, see the KafkaTopic schema reference.

Deploying the Topic Operator

You can deploy the Topic Operator using the Cluster Operator or as a standalone operator. You would use a standalone Topic Operator with a Kafka cluster that is not managed by the Cluster Operator.

For deployment instructions, see the following:

Important

To deploy the standalone Topic Operator, you need to set environment variables to connect to a Kafka cluster. These environment variables do not need to be set if you are deploying the Topic Operator using the Cluster Operator as they will be set by the Cluster Operator.

5.3.1. Kafka topic resource

The KafkaTopic resource is used to configure topics, including the number of partitions and replicas.

The full schema for KafkaTopic is described in KafkaTopic schema reference.

Identifying a Kafka cluster for topic handling

A KafkaTopic resource includes a label that specifies the name of the Kafka cluster (derived from the name of the Kafka resource) to which it belongs.

For example:

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
  name: topic-name-1
  labels:
    strimzi.io/cluster: my-cluster

The label is used by the Topic Operator to identify the KafkaTopic resource and create a new topic, and also in subsequent handling of the topic.

If the label does not match the Kafka cluster, the Topic Operator cannot identify the KafkaTopic and the topic is not created.

Kafka topic usage recommendations

When working with topics, be consistent. Always operate on either KafkaTopic resources or topics directly in Kubernetes. Avoid routinely switching between both methods for a given topic.

Use topic names that reflect the nature of the topic, and remember that names cannot be changed later.

If creating a topic in Kafka, use a name that is a valid Kubernetes resource name, otherwise the Topic Operator will need to create the corresponding KafkaTopic with a name that conforms to the Kubernetes rules.

Note
For information on the requirements for identifiers and names in Kubernetes, refer to Object Names and IDs.
Kafka topic naming conventions

Kafka and Kubernetes impose their own validation rules for the naming of topics in Kafka and KafkaTopic.metadata.name respectively. There are valid names for each which are invalid in the other.

Using the spec.topicName property, it is possible to create a valid topic in Kafka with a name that would be invalid for the Kafka topic in Kubernetes.

The spec.topicName property inherits Kafka naming validation rules:

  • The name must not be longer than 249 characters.

  • Valid characters for Kafka topics are ASCII alphanumerics, ., _, and -.

  • The name cannot be . or .., though . can be used in a name, such as exampleTopic. or .exampleTopic.

spec.topicName must not be changed.

For example:

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
  name: topic-name-1
spec:
  topicName: topicName-1 (1)
  # ...
  1. Upper case is invalid in Kubernetes.

cannot be changed to:

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
  name: topic-name-1
spec:
  topicName: name-2
  # ...
Note

Some Kafka client applications, such as Kafka Streams, can create topics in Kafka programmatically. If those topics have names that are invalid Kubernetes resource names, the Topic Operator gives them a valid metadata.name based on the Kafka name. Invalid characters are replaced and a hash is appended to the name. For example:

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
  name: mytopic---c55e57fe2546a33f9e603caf57165db4072e827e
spec:
  topicName: myTopic
  # ...

5.3.2. Topic Operator topic store

The Topic Operator uses Kafka to store topic metadata describing topic configuration as key-value pairs. The topic store is based on the Kafka Streams key-value mechanism, which uses Kafka topics to persist the state.

Topic metadata is cached in-memory and accessed locally within the Topic Operator. Updates from operations applied to the local in-memory cache are persisted to a backup topic store on disk. The topic store is continually synchronized with updates from Kafka topics or Kubernetes KafkaTopic custom resources. Operations are handled rapidly with the topic store set up this way, but should the in-memory cache crash it is automatically repopulated from the persistent storage.

Internal topic store topics

Internal topics support the handling of topic metadata in the topic store.

__strimzi_store_topic

Input topic for storing the topic metadata

__strimzi-topic-operator-kstreams-topic-store-changelog

Retains a log of compacted topic store values

Warning
Do not delete these topics, as they are essential to the running of the Topic Operator.
Migrating topic metadata from ZooKeeper

In previous releases of Strimzi, topic metadata was stored in ZooKeeper. The new process removes this requirement, bringing the metadata into the Kafka cluster, and under the control of the Topic Operator.

When upgrading to Strimzi latest, the transition to Topic Operator control of the topic store is seamless. Metadata is found and migrated from ZooKeeper, and the old store is deleted.

Downgrading to a Strimzi version that uses ZooKeeper to store topic metadata

If you are reverting back to a version of Strimzi earlier than 0.22, which uses ZooKeeper for the storage of topic metadata, you still downgrade your Cluster Operator to the previous version, then downgrade Kafka brokers and client applications to the previous Kafka version as standard.

However, you must also delete the topics that were created for the topic store using a kafka-admin command, specifying the bootstrap address of the Kafka cluster. For example:

kubectl run kafka-admin -ti --image=quay.io/strimzi/kafka:latest-kafka-3.3.2 --rm=true --restart=Never -- ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi-topic-operator-kstreams-topic-store-changelog --delete && ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi_store_topic --delete

The command must correspond to the type of listener and authentication used to access the Kafka cluster.

The Topic Operator will reconstruct the ZooKeeper topic metadata from the state of the topics in Kafka.

Topic Operator topic replication and scaling

The recommended configuration for topics managed by the Topic Operator is a topic replication factor of 3, and a minimum of 2 in-sync replicas.

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
  name: my-topic
  labels:
    strimzi.io/cluster: my-cluster
spec:
  partitions: 10 (1)
  replicas: 3 (2)
  config:
    min.insync.replicas: 2 (3)
  #...
  1. The number of partitions for the topic.

  2. The number of replica topic partitions. Currently, this cannot be changed in the KafkaTopic resource, but it can be changed using the kafka-reassign-partitions.sh tool.

  3. The minimum number of replica partitions that a message must be successfully written to, or an exception is raised.

Note
In-sync replicas are used in conjunction with the acks configuration for producer applications. The acks configuration determines the number of follower partitions a message must be replicated to before the message is acknowledged as successfully received. The Topic Operator runs with acks=all, whereby messages must be acknowledged by all in-sync replicas.

When scaling Kafka clusters by adding or removing brokers, replication factor configuration is not changed and replicas are not reassigned automatically. However, you can use the kafka-reassign-partitions.sh tool to change the replication factor, and manually reassign replicas to brokers.

Alternatively, though the integration of Cruise Control for Strimzi cannot change the replication factor for topics, the optimization proposals it generates for rebalancing Kafka include commands that transfer partition replicas and change partition leadership.

Handling changes to topics

A fundamental problem that the Topic Operator needs to solve is that there is no single source of truth: both the KafkaTopic resource and the Kafka topic can be modified independently of the Topic Operator. Complicating this, the Topic Operator might not always be able to observe changes at each end in real time. For example, when the Topic Operator is down.

To resolve this, the Topic Operator maintains information about each topic in the topic store. When a change happens in the Kafka cluster or Kubernetes, it looks at both the state of the other system and the topic store in order to determine what needs to change to keep everything in sync. The same thing happens whenever the Topic Operator starts, and periodically while it is running.

For example, suppose the Topic Operator is not running, and a KafkaTopic called my-topic is created. When the Topic Operator starts, the topic store does not contain information on my-topic, so it can infer that the KafkaTopic was created after it was last running. The Topic Operator creates the topic corresponding to my-topic, and also stores metadata for my-topic in the topic store.

If you update Kafka topic configuration or apply a change through the KafkaTopic custom resource, the topic store is updated after the Kafka cluster is reconciled.

The topic store also allows the Topic Operator to manage scenarios where the topic configuration is changed in Kafka topics and updated through Kubernetes KafkaTopic custom resources, as long as the changes are not incompatible. For example, it is possible to make changes to the same topic config key, but to different values. For incompatible changes, the Kafka configuration takes priority, and the KafkaTopic is updated accordingly.

Note
You can also use the KafkaTopic resource to delete topics using a kubectl delete -f KAFKA-TOPIC-CONFIG-FILE command. To be able to do this, delete.topic.enable must be set to true (default) in the spec.kafka.config of the Kafka resource.

5.3.3. Configuring Kafka topics

Use the properties of the KafkaTopic resource to configure Kafka topics.

You can use kubectl apply to create or modify topics, and kubectl delete to delete existing topics.

For example:

  • kubectl apply -f <topic_config_file>

  • kubectl delete KafkaTopic <topic_name>

This procedure shows how to create a topic with 10 partitions and 2 replicas.

Before you start

It is important that you consider the following before making your changes:

  • Kafka does not support decreasing the number of partitions.

  • Increasing spec.partitions for topics with keys will change how records are partitioned, which can be particularly problematic when the topic uses semantic partitioning.

  • Strimzi does not support making the following changes through the KafkaTopic resource:

    • Using spec.replicas to change the number of replicas that were initially specified

    • Changing topic names using spec.topicName

Prerequisites
  • A running Kafka cluster configured with a Kafka broker listener using mTLS authentication and TLS encryption.

  • A running Topic Operator (typically deployed with the Entity Operator).

  • For deleting a topic, delete.topic.enable=true (default) in the spec.kafka.config of the Kafka resource.

Procedure
  1. Configure the KafkaTopic resource.

    Example Kafka topic configuration
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaTopic
    metadata:
      name: orders
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      partitions: 10
      replicas: 2
    Tip
    When modifying a topic, you can get the current version of the resource using kubectl get kafkatopic orders -o yaml.
  2. Create the KafkaTopic resource in Kubernetes.

    kubectl apply -f <topic_config_file>
  3. Wait for the ready status of the topic to change to True:

    kubectl get kafkatopics -o wide -w -n <namespace>
    Kafka topic status
    NAME         CLUSTER     PARTITIONS  REPLICATION FACTOR READY
    my-topic-1   my-cluster  10          3                  True
    my-topic-2   my-cluster  10          3
    my-topic-3   my-cluster  10          3                  True

    Topic creation is successful when the READY output shows True.

  4. If the READY column stays blank, get more details on the status from the resource YAML or from the Topic Operator logs.

    Messages provide details on the reason for the current status.

    oc get kafkatopics my-topic-2 -o yaml
    Details on a topic with a NotReady status
    # ...
    status:
      conditions:
      - lastTransitionTime: "2022-06-13T10:14:43.351550Z"
        message: Number of partitions cannot be decreased
        reason: PartitionDecreaseException
        status: "True"
        type: NotReady

    In this example, the reason the topic is not ready is because the original number of partitions was reduced in the KafkaTopic configuration. Kafka does not support this.

    After resetting the topic configuration, the status shows the topic is ready.

    kubectl get kafkatopics my-topic-2 -o wide -w -n <namespace>
    Status update of the topic
    NAME         CLUSTER     PARTITIONS  REPLICATION FACTOR READY
    my-topic-2   my-cluster  10          3                  True

    Fetching the details shows no messages

    kubectl get kafkatopics my-topic-2 -o yaml
    Details on a topic with a READY status
    # ...
    status:
      conditions:
      - lastTransitionTime: '2022-06-13T10:15:03.761084Z'
        status: 'True'
        type: Ready

5.3.4. Configuring the Topic Operator with resource requests and limits

You can allocate resources, such as CPU and memory, to the Topic Operator and set a limit on the amount of resources it can consume.

Prerequisites
  • The Cluster Operator is running.

Procedure
  1. Update the Kafka cluster configuration in an editor, as required:

    kubectl edit kafka MY-CLUSTER
  2. In the spec.entityOperator.topicOperator.resources property in the Kafka resource, set the resource requests and limits for the Topic Operator.

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      # Kafka and ZooKeeper sections...
      entityOperator:
        topicOperator:
          resources:
            requests:
              cpu: "1"
              memory: 500Mi
            limits:
              cpu: "1"
              memory: 500Mi
  3. Apply the new configuration to create or update the resource.

    kubectl apply -f <kafka_configuration_file>

5.4. Using the User Operator

When you create, modify or delete a user using the KafkaUser resource, the User Operator ensures those changes are reflected in the Kafka cluster.

For more information on the KafkaUser resource, see the KafkaUser schema reference.

Deploying the User Operator

You can deploy the User Operator using the Cluster Operator or as a standalone operator. You would use a standalone User Operator with a Kafka cluster that is not managed by the Cluster Operator.

For deployment instructions, see the following:

Important

To deploy the standalone User Operator, you need to set environment variables to connect to a Kafka cluster. These environment variables do not need to be set if you are deploying the User Operator using the Cluster Operator as they will be set by the Cluster Operator.

5.4.1. Configuring Kafka users

Use the properties of the KafkaUser resource to configure Kafka users.

You can use kubectl apply to create or modify users, and kubectl delete to delete existing users.

For example:

  • kubectl apply -f <user_config_file>

  • kubectl delete KafkaUser <user_name>

Users represent Kafka clients. When you configure Kafka users, you enable the user authentication and authorization mechanisms required by clients to access Kafka. The mechanism used must match the equivalent Kafka configuration. For more information on using Kafka and KafkaUser resources to secure access to Kafka brokers, see Securing access to Kafka brokers.

Prerequisites
  • A running Kafka cluster configured with a Kafka broker listener using mTLS authentication and TLS encryption.

  • A running User Operator (typically deployed with the Entity Operator).

Procedure
  1. Configure the KafkaUser resource.

    This example specifies mTLS authentication and simple authorization using ACLs.

    Example Kafka user configuration
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaUser
    metadata:
      name: my-user
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      authentication:
        type: tls
      authorization:
        type: simple
        acls:
          # Example consumer Acls for topic my-topic using consumer group my-group
          - resource:
              type: topic
              name: my-topic
              patternType: literal
            operations:
              - Describe
              - Read
            host: "*"
          - resource:
              type: group
              name: my-group
              patternType: literal
            operations:
              - Read
            host: "*"
          # Example Producer Acls for topic my-topic
          - resource:
              type: topic
              name: my-topic
              patternType: literal
            operations:
              - Create
              - Describe
              - Write
            host: "*"
  2. Create the KafkaUser resource in Kubernetes.

    kubectl apply -f <user_config_file>
  3. Wait for the ready status of the user to change to True:

    kubectl get kafkausers -o wide -w -n <namespace>
    Kafka user status
    NAME       CLUSTER     AUTHENTICATION  AUTHORIZATION READY
    my-user-1  my-cluster  tls             simple        True
    my-user-2  my-cluster  tls             simple
    my-user-3  my-cluster  tls             simple        True

    User creation is successful when the READY output shows True.

  4. If the READY column stays blank, get more details on the status from the resource YAML or User Operator logs.

    Messages provide details on the reason for the current status.

    kubectl get kafkausers my-user-2 -o yaml
    Details on a user with a NotReady status
    # ...
    status:
      conditions:
      - lastTransitionTime: "2022-06-10T10:07:37.238065Z"
        message: Simple authorization ACL rules are configured but not supported in the
          Kafka cluster configuration.
        reason: InvalidResourceException
        status: "True"
        type: NotReady

    In this example, the reason the user is not ready is because simple authorization is not enabled in the Kafka configuration.

    Kafka configuration for simple authorization
      apiVersion: kafka.strimzi.io/v1beta2
      kind: Kafka
      metadata:
        name: my-cluster
      spec:
        kafka:
          # ...
          authorization:
            type: simple

    After updating the Kafka configuration, the status shows the user is ready.

    kubectl get kafkausers my-user-2 -o wide -w -n <namespace>
    Status update of the user
    NAME       CLUSTER     AUTHENTICATION  AUTHORIZATION READY
    my-user-2  my-cluster  tls             simple        True

    Fetching the details shows no messages.

    kubectl get kafkausers my-user-2 -o yaml
    Details on a user with a READY status
    # ...
    status:
      conditions:
      - lastTransitionTime: "2022-06-10T10:33:40.166846Z"
        status: "True"
        type: Ready

5.4.2. Configuring the User Operator with resource requests and limits

You can allocate resources, such as CPU and memory, to the User Operator and set a limit on the amount of resources it can consume.

Prerequisites
  • The Cluster Operator is running.

Procedure
  1. Update the Kafka cluster configuration in an editor, as required:

    kubectl edit kafka MY-CLUSTER
  2. In the spec.entityOperator.userOperator.resources property in the Kafka resource, set the resource requests and limits for the User Operator.

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    spec:
      # Kafka and ZooKeeper sections...
      entityOperator:
        userOperator:
          resources:
            requests:
              cpu: "1"
              memory: 500Mi
            limits:
              cpu: "1"
              memory: 500Mi

    Save the file and exit the editor. The Cluster Operator applies the changes automatically.

5.5. Configuring feature gates

Strimzi operators support feature gates to enable or disable certain features and functionality. Enabling a feature gate changes the behavior of the relevant operator and introduces the feature to your Strimzi deployment.

Feature gates have a default state of either enabled or disabled.

To modify a feature gate’s default state, use the STRIMZI_FEATURE_GATES environment variable in the operator’s configuration. You can modify multiple feature gates using this single environment variable. Specify a comma-separated list of feature gate names and prefixes. A + prefix enables the feature gate and a - prefix disables it.

Example feature gate configuration that enables FeatureGate1 and disables FeatureGate2
env:
  - name: STRIMZI_FEATURE_GATES
    value: +FeatureGate1,-FeatureGate2

5.5.1. ControlPlaneListener feature gate

The ControlPlaneListener feature gate has moved to GA, which means it is now permanently enabled and cannot be disabled. With ControlPlaneListener enabled, the connections between the Kafka controller and brokers use an internal control plane listener on port 9090. Replication of data between brokers, as well as internal connections from Strimzi operators, Cruise Control, or the Kafka Exporter use the replication listener on port 9091.

Important
With the ControlPlaneListener feature gate permanently enabled, it is no longer possible to upgrade or downgrade directly between Strimzi 0.22 and earlier and Strimzi 0.32 and newer. You have to upgrade or downgrade through one of the Strimzi versions in between.

5.5.2. ServiceAccountPatching feature gate

The ServiceAccountPatching feature gate has moved to GA, which means it is now permanently enabled and cannot be disabled. With ServiceAccountPatching enabled, the Cluster Operator always reconciles service accounts and updates them when needed. For example, when you change service account labels or annotations using the template property of a custom resource, the operator automatically updates them on the existing service account resources.

5.5.3. UseStrimziPodSets feature gate

The UseStrimziPodSets feature gate has a default state of enabled.

The UseStrimziPodSets feature gate introduces a resource for managing pods called StrimziPodSet. When the feature gate is enabled, this resource is used instead of the StatefulSets. Strimzi handles the creation and management of pods instead of Kubernetes. Using StrimziPodSets instead of StatefulSets provides more control over the functionality.

When this feature gate is disabled, Strimzi relies on StatefulSets to create and manage pods for the ZooKeeper and Kafka clusters. Strimzi creates the StatefulSet and Kubernetes creates the pods according to the StatefulSet definition. When a pod is deleted, Kubernetes is responsible for recreating it. The use of StatefulSets has the following limitations:

  • Pods are always created or removed based on their index numbers

  • All pods in the StatefulSet need to have a similar configuration

  • Changing storage configuration for the Pods in the StatefulSet is complicated

Disabling the UseStrimziPodSets feature gate

To disable the UseStrimziPodSets feature gate, specify -UseStrimziPodSets in the STRIMZI_FEATURE_GATES environment variable in the Cluster Operator configuration.

Important
The UseStrimziPodSets feature gate must be disabled when downgrading to Strimzi 0.27 and earlier versions.

5.5.4. (Preview) UseKRaft feature gate

The UseKRaft feature gate has a default state of disabled.

The UseKRaft feature gate deploys the Kafka cluster in the KRaft (Kafka Raft metadata) mode without ZooKeeper. This feature gate is currently intended only for development and testing.

Important
The KRaft mode is not ready for production in Apache Kafka or in Strimzi.

When the UseKRaft feature gate is enabled, the Kafka cluster is deployed without ZooKeeper. The .spec.zookeeper properties in the Kafka custom resource will be ignored, but still need to be present. The UseKRaft feature gate provides an API that configures Kafka cluster nodes and their roles. The API is still in development and is expected to change before the KRaft mode is production-ready.

Currently, the KRaft mode in Strimzi has the following major limitations:

  • Moving from Kafka clusters with ZooKeeper to KRaft clusters or the other way around is not supported.

  • Upgrades and downgrades of Apache Kafka versions or the Strimzi operator are not supported. Users might need to delete the cluster, upgrade the operator and deploy a new Kafka cluster.

  • The Topic Operator is not supported. The spec.entityOperator.topicOperator property must be removed from the Kafka custom resource.

  • SCRAM-SHA-512 authentication is not supported.

  • JBOD storage is not supported. The type: jbod storage can be used, but the JBOD array can contain only one disk.

  • All Kafka nodes have both the controller and broker KRaft roles. Kafka clusters with separate controller and broker nodes are not supported.

Enabling the UseStrimziPodSets feature gate

To enable the UseKRaft feature gate, specify +UseKRaft in the STRIMZI_FEATURE_GATES environment variable in the Cluster Operator configuration.

Important
The UseKRaft feature gate depends on the UseStrimziPodSets feature gate. When enabling the UseKRaft feature gate, make sure that the USeStrimziPodSets feature gate is enabled as well.

5.5.5. Feature gate releases

Feature gates have three stages of maturity:

  • Alpha — typically disabled by default

  • Beta — typically enabled by default

  • General Availability (GA) — typically always enabled

Alpha stage features might be experimental or unstable, subject to change, or not sufficiently tested for production use. Beta stage features are well tested and their functionality is not likely to change. GA stage features are stable and should not change in the future. Alpha and beta stage features are removed if they do not prove to be useful.

  • The ControlPlaneListener feature gate moved to GA stage in Strimzi 0.32. It is now permanently enabled and cannot be disabled.

  • The ServiceAccountPatching feature gate moved to GA stage in Strimzi 0.30. It is now permanently enabled and cannot be disabled.

  • The UseStrimziPodSets feature gate moved to beta stage in Strimzi 0.30. It moves to GA in Strimzi 0.35 when the support for StatefulSets is completely removed.

  • The UseKRaft feature gate is available for development only and does not currently have a planned release for moving to the beta phase.

Note
Feature gates might be removed when they reach GA. This means that the feature was incorporated into the Strimzi core features and can no longer be disabled.
Table 9. Feature gates and the Strimzi versions when they moved to alpha, beta, or GA
Feature gate Alpha Beta GA

ControlPlaneListener

0.23

0.27

0.32

ServiceAccountPatching

0.24

0.27

0.30

UseStrimziPodSets

0.28

0.30

0.35 (planned)

UseKRaft

0.29

-

-

If a feature gate is enabled, you may need to disable it before upgrading or downgrading from a specific Strimzi version. The following table shows which feature gates you need to disable when upgrading or downgrading Strimzi versions.

Table 10. Feature gates to disable when upgrading or downgrading Strimzi
Disable Feature gate Upgrading from Strimzi version Downgrading to Strimzi version

ControlPlaneListener

0.22 and earlier

0.22 and earlier

UseStrimziPodSets

-

0.27 and earlier

5.6. Monitoring operators using Prometheus metrics

Strimzi operators expose Prometheus metrics. The metrics are automatically enabled and contain information about:

  • Number of reconciliations

  • Number of Custom Resources the operator is processing

  • Duration of reconciliations

  • JVM metrics from the operators

Additionally, we provide an example Grafana dashboard.

For more information about Prometheus, see the Introducing Metrics to Kafka in the Deploying and Upgrading Strimzi guide.

6. Cruise Control for cluster rebalancing

Cruise Control is an open source system that supports the following Kafka operations:

  • Monitoring cluster workload

  • Rebalancing a cluster based on predefined constraints

The operations help with running a more balanced Kafka cluster that uses broker pods more efficiently.

A typical cluster can become unevenly loaded over time. Partitions that handle large amounts of message traffic might not be evenly distributed across the available brokers. To rebalance the cluster, administrators must monitor the load on brokers and manually reassign busy partitions to brokers with spare capacity.

Cruise Control automates the cluster rebalancing process. It constructs a workload model of resource utilization for the cluster—​based on CPU, disk, and network load—​and generates optimization proposals (that you can approve or reject) for more balanced partition assignments. A set of configurable optimization goals is used to calculate these proposals.

You can generate optimization proposals in specific modes. The default full mode rebalances partitions across all brokers. You can also use the add-brokers and remove-brokers modes to accommodate changes when scaling a cluster up or down.

When you approve an optimization proposal, Cruise Control applies it to your Kafka cluster. You configure and generate optimization proposals using a KafkaRebalance resource. You can configure the resource using an annotation so that optimization proposals are approved automatically or manually.

6.1. Cruise Control components and features

Cruise Control consists of four main components—​the Load Monitor, the Analyzer, the Anomaly Detector, and the Executor—​and a REST API for client interactions. Strimzi utilizes the REST API to support the following Cruise Control features:

  • Generating optimization proposals from optimization goals.

  • Rebalancing a Kafka cluster based on an optimization proposal.

Optimization goals

An optimization goal describes a specific objective to achieve from a rebalance. For example, a goal might be to distribute topic replicas across brokers more evenly. You can change what goals to include through configuration. A goal is defined as a hard goal or soft goal. You can add hard goals through Cruise Control deployment configuration. You also have main, default, and user-provided goals that fit into each of these categories.

  • Hard goals are preset and must be satisfied for an optimization proposal to be successful.

  • Soft goals do not need to be satisfied for an optimization proposal to be successful. They can be set aside if it means that all hard goals are met.

  • Main goals are inherited from Cruise Control. Some are preset as hard goals. Main goals are used in optimization proposals by default.

  • Default goals are the same as the main goals by default. You can specify your own set of default goals.

  • User-provided goals are a subset of default goals that are configured for generating a specific optimization proposal.

Optimization proposals

Optimization proposals comprise the goals you want to achieve from a rebalance. You generate an optimization proposal to create a summary of proposed changes and the results that are possible with the rebalance. The goals are assessed in a specific order of priority. You can then choose to approve or reject the proposal. You can reject the proposal to run it again with an adjusted set of goals.

You can generate an optimization proposal in one of three modes.

  • full is the default mode and runs a full rebalance.

  • add-brokers is the mode you use after adding brokers when scaling up a Kafka cluster.

  • remove-brokers is the mode you use before removing brokers when scaling down a Kafka cluster.

Other Cruise Control features are not currently supported, including self healing, notifications, write-your-own goals, and changing the topic replication factor.

Additional resources

6.2. Optimization goals overview

Optimization goals are constraints on workload redistribution and resource utilization across a Kafka cluster. To rebalance a Kafka cluster, Cruise Control uses optimization goals to generate optimization proposals, which you can approve or reject.

6.2.1. Goals order of priority

Strimzi supports most of the optimization goals developed in the Cruise Control project. The supported goals, in the default descending order of priority, are as follows:

  1. Rack-awareness

  2. Minimum number of leader replicas per broker for a set of topics

  3. Replica capacity

  4. Capacity goals

    • Disk capacity

    • Network inbound capacity

    • Network outbound capacity

    • CPU capacity

  5. Replica distribution

  6. Potential network output

  7. Resource distribution goals

    • Disk utilization distribution

    • Network inbound utilization distribution

    • Network outbound utilization distribution

    • CPU utilization distribution

  8. Leader bytes-in rate distribution

  9. Topic replica distribution

  10. Leader replica distribution

  11. Preferred leader election

  12. Intra-broker disk capacity

  13. Intra-broker disk usage distribution

For more information on each optimization goal, see Goals in the Cruise Control Wiki.

Note
"Write your own" goals and Kafka assigner goals are not yet supported.

6.2.2. Goals configuration in Strimzi custom resources

You configure optimization goals in Kafka and KafkaRebalance custom resources. Cruise Control has configurations for hard optimization goals that must be satisfied, as well as main, default, and user-provided optimization goals.

You can specify optimization goals in the following configuration:

  • Main goals — Kafka.spec.cruiseControl.config.goals

  • Hard goals — Kafka.spec.cruiseControl.config.hard.goals

  • Default goals — Kafka.spec.cruiseControl.config.default.goals

  • User-provided goals — KafkaRebalance.spec.goals

Note

Resource distribution goals are subject to capacity limits on broker resources.

6.2.3. Hard and soft optimization goals

Hard goals are goals that must be satisfied in optimization proposals. Goals that are not configured as hard goals are known as soft goals. You can think of soft goals as best effort goals: they do not need to be satisfied in optimization proposals, but are included in optimization calculations. An optimization proposal that violates one or more soft goals, but satisfies all hard goals, is valid.

Cruise Control will calculate optimization proposals that satisfy all the hard goals and as many soft goals as possible (in their priority order). An optimization proposal that does not satisfy all the hard goals is rejected by Cruise Control and not sent to the user for approval.

Note
For example, you might have a soft goal to distribute a topic’s replicas evenly across the cluster (the topic replica distribution goal). Cruise Control will ignore this goal if doing so enables all the configured hard goals to be met.

In Cruise Control, the following main optimization goals are preset as hard goals:

RackAwareGoal; MinTopicLeadersPerBrokerGoal; ReplicaCapacityGoal; DiskCapacityGoal; NetworkInboundCapacityGoal; NetworkOutboundCapacityGoal; CpuCapacityGoal

You configure hard goals in the Cruise Control deployment configuration, by editing the hard.goals property in Kafka.spec.cruiseControl.config.

  • To inherit the preset hard goals from Cruise Control, do not specify the hard.goals property in Kafka.spec.cruiseControl.config

  • To change the preset hard goals, specify the desired goals in the hard.goals property, using their fully-qualified domain names.

Example Kafka configuration for hard optimization goals
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
  zookeeper:
    # ...
  entityOperator:
    topicOperator: {}
    userOperator: {}
  cruiseControl:
    brokerCapacity:
      inboundNetwork: 10000KB/s
      outboundNetwork: 10000KB/s
    config:
      hard.goals: >
        com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkInboundCapacityGoal,
        com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkOutboundCapacityGoal
      # ...

Increasing the number of configured hard goals will reduce the likelihood of Cruise Control generating valid optimization proposals.

If skipHardGoalCheck: true is specified in the KafkaRebalance custom resource, Cruise Control does not check that the list of user-provided optimization goals (in KafkaRebalance.spec.goals) contains all the configured hard goals (hard.goals). Therefore, if some, but not all, of the user-provided optimization goals are in the hard.goals list, Cruise Control will still treat them as hard goals even if skipHardGoalCheck: true is specified.

6.2.4. Main optimization goals

The main optimization goals are available to all users. Goals that are not listed in the main optimization goals are not available for use in Cruise Control operations.

Unless you change the Cruise Control deployment configuration, Strimzi will inherit the following main optimization goals from Cruise Control, in descending priority order:

RackAwareGoal; ReplicaCapacityGoal; DiskCapacityGoal; NetworkInboundCapacityGoal; NetworkOutboundCapacityGoal; CpuCapacityGoal; ReplicaDistributionGoal; PotentialNwOutGoal; DiskUsageDistributionGoal; NetworkInboundUsageDistributionGoal; NetworkOutboundUsageDistributionGoal; CpuUsageDistributionGoal; TopicReplicaDistributionGoal; LeaderReplicaDistributionGoal; LeaderBytesInDistributionGoal; PreferredLeaderElectionGoal

Some of these goals are preset as hard goals.

To reduce complexity, we recommend that you use the inherited main optimization goals, unless you need to completely exclude one or more goals from use in KafkaRebalance resources. The priority order of the main optimization goals can be modified, if desired, in the configuration for default optimization goals.

You configure main optimization goals, if necessary, in the Cruise Control deployment configuration: Kafka.spec.cruiseControl.config.goals

  • To accept the inherited main optimization goals, do not specify the goals property in Kafka.spec.cruiseControl.config.

  • If you need to modify the inherited main optimization goals, specify a list of goals, in descending priority order, in the goals configuration option.

Note
If you change the inherited main optimization goals, you must ensure that the hard goals, if configured in the hard.goals property in Kafka.spec.cruiseControl.config, are a subset of the main optimization goals that you configured. Otherwise, errors will occur when generating optimization proposals.

6.2.5. Default optimization goals

Cruise Control uses the default optimization goals to generate the cached optimization proposal. For more information about the cached optimization proposal, see Optimization proposals overview.

You can override the default optimization goals by setting user-provided optimization goals in a KafkaRebalance custom resource.

Unless you specify default.goals in the Cruise Control deployment configuration, the main optimization goals are used as the default optimization goals. In this case, the cached optimization proposal is generated using the main optimization goals.

  • To use the main optimization goals as the default goals, do not specify the default.goals property in Kafka.spec.cruiseControl.config.

  • To modify the default optimization goals, edit the default.goals property in Kafka.spec.cruiseControl.config. You must use a subset of the main optimization goals.

Example Kafka configuration for default optimization goals
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
  zookeeper:
    # ...
  entityOperator:
    topicOperator: {}
    userOperator: {}
  cruiseControl:
    brokerCapacity:
      inboundNetwork: 10000KB/s
      outboundNetwork: 10000KB/s
    config:
      default.goals: >
        com.linkedin.kafka.cruisecontrol.analyzer.goals.RackAwareGoal,
        com.linkedin.kafka.cruisecontrol.analyzer.goals.ReplicaCapacityGoal,
        com.linkedin.kafka.cruisecontrol.analyzer.goals.DiskCapacityGoal
      # ...

If no default optimization goals are specified, the cached proposal is generated using the main optimization goals.

6.2.6. User-provided optimization goals

User-provided optimization goals narrow down the configured default goals for a particular optimization proposal. You can set them, as required, in spec.goals in a KafkaRebalance custom resource:

KafkaRebalance.spec.goals

User-provided optimization goals can generate optimization proposals for different scenarios. For example, you might want to optimize leader replica distribution across the Kafka cluster without considering disk capacity or disk utilization. So, you create a KafkaRebalance custom resource containing a single user-provided goal for leader replica distribution.

User-provided optimization goals must:

  • Include all configured hard goals, or an error occurs

  • Be a subset of the main optimization goals

To ignore the configured hard goals when generating an optimization proposal, add the skipHardGoalCheck: true property to the KafkaRebalance custom resource. See Generating optimization proposals.

Additional resources

6.3. Optimization proposals overview

Configure a KafkaRebalance resource to generate optimization proposals and apply the suggested changes. An optimization proposal is a summary of proposed changes that would produce a more balanced Kafka cluster, with partition workloads distributed more evenly among the brokers.

Each optimization proposal is based on the set of optimization goals that was used to generate it, subject to any configured capacity limits on broker resources.

All optimization proposals are estimates of the impact of a proposed rebalance. You can approve or reject a proposal. You cannot approve a cluster rebalance without first generating the optimization proposal.

You can run optimization proposals in one of the following rebalancing modes:

  • full

  • add-brokers

  • remove-brokers

6.3.1. Rebalancing modes

You specify a rebalancing mode using the spec.mode property of the KafkaRebalance custom resource.

full

The full mode runs a full rebalance by moving replicas across all the brokers in the cluster. This is the default mode if the spec.mode property is not defined in the KafkaRebalance custom resource.

add-brokers

The add-brokers mode is used after scaling up a Kafka cluster by adding one or more brokers. Normally, after scaling up a Kafka cluster, new brokers are used to host only the partitions of newly created topics. If no new topics are created, the newly added brokers are not used and the existing brokers remain under the same load. By using the add-brokers mode immediately after adding brokers to the cluster, the rebalancing operation moves replicas from existing brokers to the newly added brokers. You specify the new brokers as a list using the spec.brokers property of the KafkaRebalance custom resource.

remove-brokers

The remove-brokers mode is used before scaling down a Kafka cluster by removing one or more brokers. If you scale down a Kafka cluster, brokers are shut down even if they host replicas. This can lead to under-replicated partitions and possibly result in some partitions being under their minimum ISR (in-sync replicas). To avoid this potential problem, the remove-brokers mode moves replicas off the brokers that are going to be removed. When these brokers are not hosting replicas anymore, you can safely run the scaling down operation. You specify the brokers you’re removing as a list in the spec.brokers property in the KafkaRebalance custom resource.

In general, use the full rebalance mode to rebalance a Kafka cluster by spreading the load across brokers. Use the add-brokers and remove-brokers modes only if you want to scale your cluster up or down and rebalance the replicas accordingly.

The procedure to run a rebalance is actually the same across the three different modes. The only difference is with specifying a mode through the spec.mode property and, if needed, listing brokers that have been added or will be removed through the spec.brokers property.

6.3.2. The results of an optimization proposal

When an optimization proposal is generated, a summary and broker load is returned.

Summary

The summary is contained in the KafkaRebalance resource. The summary provides an overview of the proposed cluster rebalance and indicates the scale of the changes involved. A summary of a successfully generated optimization proposal is contained in the Status.OptimizationResult property of the KafkaRebalance resource. The information provided is a summary of the full optimization proposal.

Broker load

The broker load is stored in a ConfigMap that contains data as a JSON string. The broker load shows before and after values for the proposed rebalance, so you can see the impact on each of the brokers in the cluster.

6.3.3. Manually approving or rejecting an optimization proposal

An optimization proposal summary shows the proposed scope of changes.

You can use the name of the KafkaRebalance resource to return a summary from the command line.

Returning an optimization proposal summary
kubectl describe kafkarebalance <kafka_rebalance_resource_name> -n <namespace>

You can also use the jq command line JSON parser tool.

Returning an optimization proposal summary using jq
kubectl get kafkarebalance -o json | jq <jq_query>.

Use the summary to decide whether to approve or reject an optimization proposal.

Approving an optimization proposal

You approve the optimization proposal by setting the strimzi.io/rebalance annotation of the KafkaRebalance resource to approve. Cruise Control applies the proposal to the Kafka cluster and starts a cluster rebalance operation.

Rejecting an optimization proposal

If you choose not to approve an optimization proposal, you can change the optimization goals or update any of the rebalance performance tuning options, and then generate another proposal. You can use the strimzi.io/refresh annotation to generate a new optimization proposal for a KafkaRebalance resource.

Use optimization proposals to assess the movements required for a rebalance. For example, a summary describes inter-broker and intra-broker movements. Inter-broker rebalancing moves data between separate brokers. Intra-broker rebalancing moves data between disks on the same broker when you are using a JBOD storage configuration. Such information can be useful even if you don’t go ahead and approve the proposal.

You might reject an optimization proposal, or delay its approval, because of the additional load on a Kafka cluster when rebalancing.

In the following example, the proposal suggests the rebalancing of data between separate brokers. The rebalance involves the movement of 55 partition replicas, totaling 12MB of data, across the brokers. Though the inter-broker movement of partition replicas has a high impact on performance, the total amount of data is not large. If the total data was much larger, you could reject the proposal, or time when to approve the rebalance to limit the impact on the performance of the Kafka cluster.

Rebalance performance tuning options can help reduce the impact of data movement. If you can extend the rebalance period, you can divide the rebalance into smaller batches. Fewer data movements at a single time reduces the load on the cluster.

Example optimization proposal summary
Name:         my-rebalance
Namespace:    myproject
Labels:       strimzi.io/cluster=my-cluster
Annotations:  API Version:  kafka.strimzi.io/v1alpha1
Kind:         KafkaRebalance
Metadata:
# ...
Status:
  Conditions:
    Last Transition Time:  2022-04-05T14:36:11.900Z
    Status:                ProposalReady
    Type:                  State
  Observed Generation:     1
  Optimization Result:
    Data To Move MB:  0
    Excluded Brokers For Leadership:
    Excluded Brokers For Replica Move:
    Excluded Topics:
    Intra Broker Data To Move MB:         12
    Monitored Partitions Percentage:      100
    Num Intra Broker Replica Movements:   0
    Num Leader Movements:                 24
    Num Replica Movements:                55
    On Demand Balancedness Score After:   82.91290759174306
    On Demand Balancedness Score Before:  78.01176356230222
    Recent Windows:                       5
  Session Id:                             a4f833bd-2055-4213-bfdd-ad21f95bf184

The proposal will also move 24 partition leaders to different brokers. This requires a change to the ZooKeeper configuration, which has a low impact on performance.

The balancedness scores are measurements of the overall balance of the Kafka cluster before and after the optimization proposal is approved. A balancedness score is based on optimization goals. If all goals are satisfied, the score is 100. The score is reduced for each goal that will not be met. Compare the balancedness scores to see whether the Kafka cluster is less balanced than it could be following a rebalance.

6.3.4. Automatically approving an optimization proposal

To save time, you can automate the process of approving optimization proposals. With automation, when you generate an optimization proposal it goes straight into a cluster rebalance.

To enable the optimization proposal auto-approval mechanism, create the KafkaRebalance resource with the strimzi.io/rebalance-auto-approval annotation set to true. If the annotation is not set or set to false, the optimization proposal requires manual approval.

Example rebalance request with auto-approval mechanism enabled
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
  name: my-rebalance
  labels:
    strimzi.io/cluster: my-cluster
  annotations:
    strimzi.io/rebalance-auto-approval: "true"
spec:
  mode: # any mode
  # ...

You can still check the status when automatically approving an optimization proposal. The status of the KafkaRebalance resource moves to Ready when the rebalance is complete.

6.3.5. Optimization proposal summary properties

The following table explains the properties contained in the optimization proposal’s summary section.

Table 11. Properties contained in an optimization proposal summary
JSON property Description

numIntraBrokerReplicaMovements

The total number of partition replicas that will be transferred between the disks of the cluster’s brokers.

Performance impact during rebalance operation: Relatively high, but lower than numReplicaMovements.

excludedBrokersForLeadership

Not yet supported. An empty list is returned.

numReplicaMovements

The number of partition replicas that will be moved between separate brokers.

Performance impact during rebalance operation: Relatively high.

onDemandBalancednessScoreBefore, onDemandBalancednessScoreAfter

A measurement of the overall balancedness of a Kafka Cluster, before and after the optimization proposal was generated.

The score is calculated by subtracting the sum of the BalancednessScore of each violated soft goal from 100. Cruise Control assigns a BalancednessScore to every optimization goal based on several factors, including priority—​the goal’s position in the list of default.goals or user-provided goals.

The Before score is based on the current configuration of the Kafka cluster. The After score is based on the generated optimization proposal.

intraBrokerDataToMoveMB

The sum of the size of each partition replica that will be moved between disks on the same broker (see also numIntraBrokerReplicaMovements).

Performance impact during rebalance operation: Variable. The larger the number, the longer the cluster rebalance will take to complete. Moving a large amount of data between disks on the same broker has less impact than between separate brokers (see dataToMoveMB).

recentWindows

The number of metrics windows upon which the optimization proposal is based.

dataToMoveMB

The sum of the size of each partition replica that will be moved to a separate broker (see also numReplicaMovements).

Performance impact during rebalance operation: Variable. The larger the number, the longer the cluster rebalance will take to complete.

monitoredPartitionsPercentage

The percentage of partitions in the Kafka cluster covered by the optimization proposal. Affected by the number of excludedTopics.

excludedTopics

If you specified a regular expression in the spec.excludedTopicsRegex property in the KafkaRebalance resource, all topic names matching that expression are listed here. These topics are excluded from the calculation of partition replica/leader movements in the optimization proposal.

numLeaderMovements

The number of partitions whose leaders will be switched to different replicas. This involves a change to ZooKeeper configuration.

Performance impact during rebalance operation: Relatively low.

excludedBrokersForReplicaMove

Not yet supported. An empty list is returned.

6.3.6. Broker load properties

The broker load is stored in a ConfigMap (with the same name as the KafkaRebalance custom resource) as a JSON formatted string. This JSON string consists of a JSON object with keys for each broker IDs linking to a number of metrics for each broker. Each metric consist of three values. The first is the metric value before the optimization proposal is applied, the second is the expected value of the metric after the proposal is applied, and the third is the difference between the first two values (after minus before).

Note
The ConfigMap appears when the KafkaRebalance resource is in the ProposalReady state and remains after the rebalance is complete.

You can use the name of the ConfigMap to view its data from the command line.

Returning ConfigMap data
kubectl describe configmaps <my_rebalance_configmap_name> -n <namespace>

You can also use the jq command line JSON parser tool to extract the JSON string from the ConfigMap.

Extracting the JSON string from the ConfigMap using jq
kubectl get configmaps <my_rebalance_configmap_name> -o json | jq '.["data"]["brokerLoad.json"]|fromjson|.'

The following table explains the properties contained in the optimization proposal’s broker load ConfigMap:

JSON property Description

leaders

The number of replicas on this broker that are partition leaders.

replicas

The number of replicas on this broker.

cpuPercentage

The CPU utilization as a percentage of the defined capacity.

diskUsedPercentage

The disk utilization as a percentage of the defined capacity.

diskUsedMB

The absolute disk usage in MB.

networkOutRate

The total network output rate for the broker.

leaderNetworkInRate

The network input rate for all partition leader replicas on this broker.

followerNetworkInRate

The network input rate for all follower replicas on this broker.

potentialMaxNetworkOutRate

The hypothetical maximum network output rate that would be realized if this broker became the leader of all the replicas it currently hosts.

6.3.7. Cached optimization proposal

Cruise Control maintains a cached optimization proposal based on the configured default optimization goals. Generated from the workload model, the cached optimization proposal is updated every 15 minutes to reflect the current state of the Kafka cluster. If you generate an optimization proposal using the default optimization goals, Cruise Control returns the most recent cached proposal.

To change the cached optimization proposal refresh interval, edit the proposal.expiration.ms setting in the Cruise Control deployment configuration. Consider a shorter interval for fast changing clusters, although this increases the load on the Cruise Control server.

6.4. Rebalance performance tuning overview

You can adjust several performance tuning options for cluster rebalances. These options control how partition replica and leadership movements in a rebalance are executed, as well as the bandwidth that is allocated to a rebalance operation.

6.4.1. Partition reassignment commands

Optimization proposals are comprised of separate partition reassignment commands. When you approve a proposal, the Cruise Control server applies these commands to the Kafka cluster.

A partition reassignment command consists of either of the following types of operations:

  • Partition movement: Involves transferring the partition replica and its data to a new location. Partition movements can take one of two forms:

    • Inter-broker movement: The partition replica is moved to a log directory on a different broker.

    • Intra-broker movement: The partition replica is moved to a different log directory on the same broker.

  • Leadership movement: This involves switching the leader of the partition’s replicas.

Cruise Control issues partition reassignment commands to the Kafka cluster in batches. The performance of the cluster during the rebalance is affected by the number of each type of movement contained in each batch.

6.4.2. Replica movement strategies

Cluster rebalance performance is also influenced by the replica movement strategy that is applied to the batches of partition reassignment commands. By default, Cruise Control uses the BaseReplicaMovementStrategy, which simply applies the commands in the order they were generated. However, if there are some very large partition reassignments early in the proposal, this strategy can slow down the application of the other reassignments.

Cruise Control provides four alternative replica movement strategies that can be applied to optimization proposals:

  • PrioritizeSmallReplicaMovementStrategy: Order reassignments in order of ascending size.

  • PrioritizeLargeReplicaMovementStrategy: Order reassignments in order of descending size.

  • PostponeUrpReplicaMovementStrategy: Prioritize reassignments for replicas of partitions which have no out-of-sync replicas.

  • PrioritizeMinIsrWithOfflineReplicasStrategy: Prioritize reassignments with (At/Under)MinISR partitions with offline replicas. This strategy will only work if cruiseControl.config.concurrency.adjuster.min.isr.check.enabled is set to true in the Kafka custom resource’s spec.

These strategies can be configured as a sequence. The first strategy attempts to compare two partition reassignments using its internal logic. If the reassignments are equivalent, then it passes them to the next strategy in the sequence to decide the order, and so on.

6.4.3. Intra-broker disk balancing

Moving a large amount of data between disks on the same broker has less impact than between separate brokers. If you are running a Kafka deployment that uses JBOD storage with multiple disks on the same broker, Cruise Control can balance partitions between the disks.

Note
If you are using JBOD storage with a single disk, intra-broker disk balancing will result in a proposal with 0 partition movements since there are no disks to balance between.

To perform an intra-broker disk balance, set rebalanceDisk to true under the KafkaRebalance.spec. When setting rebalanceDisk to true, do not set a goals field in the KafkaRebalance.spec, as Cruise Control will automatically set the intra-broker goals and ignore the inter-broker goals. Cruise Control does not perform inter-broker and intra-broker balancing at the same time.

6.4.4. Rebalance tuning options

Cruise Control provides several configuration options for tuning the rebalance parameters discussed above. You can set these tuning options when configuring and deploying Cruise Control with Kafka or optimization proposal levels:

  • The Cruise Control server setting can be set in the Kafka custom resource under Kafka.spec.cruiseControl.config.

  • The individual rebalance performance configurations can be set under KafkaRebalance.spec.

The relevant configurations are summarized in the following table.

Table 12. Rebalance performance tuning configuration
Cruise Control properties KafkaRebalance properties Default Description

num.concurrent.partition.movements.per.broker

concurrentPartitionMovementsPerBroker

5

The maximum number of inter-broker partition movements in each partition reassignment batch

num.concurrent.intra.broker.partition.movements

concurrentIntraBrokerPartitionMovements

2

The maximum number of intra-broker partition movements in each partition reassignment batch

num.concurrent.leader.movements

concurrentLeaderMovements

1000

The maximum number of partition leadership changes in each partition reassignment batch

default.replication.throttle

replicationThrottle

Null (no limit)

The bandwidth (in bytes per second) to assign to partition reassignment

default.replica.movement.strategies

replicaMovementStrategies

BaseReplicaMovementStrategy

The list of strategies (in priority order) used to determine the order in which partition reassignment commands are executed for generated proposals. For the server setting, use a comma separated string with the fully qualified names of the strategy class (add com.linkedin.kafka.cruisecontrol.executor.strategy. to the start of each class name). For the KafkaRebalance resource setting use a YAML array of strategy class names.

-

rebalanceDisk

false

Enables intra-broker disk balancing, which balances disk space utilization between disks on the same broker. Only applies to Kafka deployments that use JBOD storage with multiple disks.

Changing the default settings affects the length of time that the rebalance takes to complete, as well as the load placed on the Kafka cluster during the rebalance. Using lower values reduces the load but increases the amount of time taken, and vice versa.

6.5. Configuring and deploying Cruise Control with Kafka

Configure a Kafka resource to deploy Cruise Control alongside a Kafka cluster. You can use the cruiseControl properties of the Kafka resource to configure the deployment. Deploy one instance of Cruise Control per Kafka cluster.

Use goals configuration in the Cruise Control config to specify optimization goals for generating optimization proposals. You can use brokerCapacity to change the default capacity limits for goals related to resource distribution. If brokers are running on nodes with heterogeneous network resources, you can use overrides to set network capacity limits for each broker.

If an empty object ({}) is used for the cruiseControl configuration, all properties use their default values.

Prerequisites
  • A Kubernetes cluster

  • A running Cluster Operator

Procedure
  1. Edit the cruiseControl property for the Kafka resource.

    The properties you can configure are shown in this example configuration:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      # ...
      cruiseControl:
        brokerCapacity: # (1)
          inboundNetwork: 10000KB/s
          outboundNetwork: 10000KB/s
          overrides: # (2)
          - brokers: [0]
            inboundNetwork: 20000KiB/s
            outboundNetwork: 20000KiB/s
          - brokers: [1, 2]
            inboundNetwork: 30000KiB/s
            outboundNetwork: 30000KiB/s
          # ...
        config: # (3)
          default.goals: > # (4)
            com.linkedin.kafka.cruisecontrol.analyzer.goals.RackAwareGoal,
            com.linkedin.kafka.cruisecontrol.analyzer.goals.ReplicaCapacityGoal,
            com.linkedin.kafka.cruisecontrol.analyzer.goals.DiskCapacityGoal
            # ...
          hard.goals: >
            com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkInboundCapacityGoal,
            com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkOutboundCapacityGoal
            # ...
          cpu.balance.threshold: 1.1
          metadata.max.age.ms: 300000
          send.buffer.bytes: 131072
          webserver.http.cors.enabled: true # (5)
          webserver.http.cors.origin: "*"
          webserver.http.cors.exposeheaders: "User-Task-ID,Content-Type"
          # ...
        resources: # (6)
          requests:
            cpu: 1
            memory: 512Mi
          limits:
            cpu: 2
            memory: 2Gi
        logging: # (7)
            type: inline
            loggers:
              rootLogger.level: "INFO"
        template: # (8)
          pod:
            metadata:
              labels:
                label1: value1
            securityContext:
              runAsUser: 1000001
              fsGroup: 0
            terminationGracePeriodSeconds: 120
        readinessProbe: # (9)
          initialDelaySeconds: 15
          timeoutSeconds: 5
        livenessProbe:
          initialDelaySeconds: 15
          timeoutSeconds: 5
        metricsConfig: # (10)
          type: jmxPrometheusExporter
          valueFrom:
            configMapKeyRef:
              name: cruise-control-metrics
              key: metrics-config.yml
    # ...
    1. Capacity limits for broker resources.

    2. Overrides set network capacity limits for specific brokers when running on nodes with heterogeneous network resources.

    3. Cruise Control configuration. Standard Cruise Control configuration may be provided, restricted to those properties not managed directly by Strimzi.

    4. Optimization goals configuration, which can include configuration for default optimization goals (default.goals), main optimization goals (goals), and hard goals (hard.goals).

    5. CORS enabled and configured for read-only access to the Cruise Control API.

    6. Requests for reservation of supported resources, currently cpu and memory, and limits to specify the maximum resources that can be consumed.

    7. Cruise Control loggers and log levels added directly (inline) or indirectly (external) through a ConfigMap. A custom ConfigMap must be placed under the log4j.properties key. Cruise Control has a single logger named rootLogger.level. You can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.

    8. Template customization. Here a pod is scheduled with additional security attributes.

    9. Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).

    10. Prometheus metrics enabled. In this example, metrics are configured for the Prometheus JMX Exporter (the default metrics exporter).

  2. Create or update the resource:

    kubectl apply -f <kafka_configuration_file>
  3. Check the status of the deployment:

    kubectl get deployments -n <my_cluster_operator_namespace>
    Output shows the deployment name and readiness
    NAME                      READY  UP-TO-DATE  AVAILABLE
    my-cluster-cruise-control 1/1    1           1

    my-cluster is the name of the Kafka cluster.

    READY shows the number of replicas that are ready/expected. The deployment is successful when the AVAILABLE output shows 1.

Auto-created topics

The following table shows the three topics that are automatically created when Cruise Control is deployed. These topics are required for Cruise Control to work properly and must not be deleted or changed. You can change the name of the topic using the specified configuration option.

Table 13. Auto-created topics
Auto-created topic configuration Default topic name Created by Function

metric.reporter.topic

strimzi.cruisecontrol.metrics

Strimzi Metrics Reporter

Stores the raw metrics from the Metrics Reporter in each Kafka broker.

partition.metric.sample.store.topic

strimzi.cruisecontrol.partitionmetricsamples

Cruise Control

Stores the derived metrics for each partition. These are created by the Metric Sample Aggregator.

broker.metric.sample.store.topic

strimzi.cruisecontrol.modeltrainingsamples

Cruise Control

Stores the metrics samples used to create the Cluster Workload Model.

To prevent the removal of records that are needed by Cruise Control, log compaction is disabled in the auto-created topics.

Note
If the names of the auto-created topics are changed in a Kafka cluster that already has Cruise Control enabled, the old topics will not be deleted and should be manually removed.
What to do next

After configuring and deploying Cruise Control, you can generate optimization proposals.

6.6. Generating optimization proposals

When you create or update a KafkaRebalance resource, Cruise Control generates an optimization proposal for the Kafka cluster based on the configured optimization goals. Analyze the information in the optimization proposal and decide whether to approve it. You can use the results of the optimization proposal to rebalance your Kafka cluster.

You can run the optimization proposal in one of the following modes:

  • full (default)

  • add-brokers

  • remove-brokers

The mode you use depends on whether you are rebalancing across all the brokers already running in the Kafka cluster; or you want to rebalance after scaling up or before scaling down your Kafka cluster. For more information, see Rebalancing modes with broker scaling.

Prerequisites
Procedure
  1. Create a KafkaRebalance resource and specify the appropriate mode.

    full mode (default)

    To use the default optimization goals defined in the Kafka resource, leave the spec property empty. Cruise Control rebalances a Kafka cluster in full mode by default.

    Example configuration with full rebalancing by default
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
    spec: {}

    You can also run a full rebalance by specifying the full mode through the spec.mode property.

    Example configuration specifying full mode
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      mode: full
    add-brokers mode

    If you want to rebalance a Kafka cluster after scaling up, specify the add-brokers mode.

    In this mode, existing replicas are moved to the newly added brokers. You need to specify the brokers as a list.

    Example configuration specifying add-brokers mode
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      mode: add-brokers
      brokers: [3, 4] (1)
    1. List of newly added brokers added by the scale up operation. This property is mandatory.

    remove-brokers mode

    If you want to rebalance a Kafka cluster before scaling down, specify the remove-brokers mode.

    In this mode, replicas are moved off the brokers that are going to be removed. You need to specify the brokers that are being removed as a list.

    Example configuration specifying remove-brokers mode
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      mode: remove-brokers
      brokers: [3, 4] (1)
    1. List of brokers to be removed by the scale down operation. This property is mandatory.

    Note
    The following steps and the steps to approve or stop a rebalance are the same regardless of the rebalance mode you are using.
  2. To configure user-provided optimization goals instead of using the default goals, add the goals property and enter one or more goals.

    In the following example, rack awareness and replica capacity are configured as user-provided optimization goals:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      goals:
        - RackAwareGoal
        - ReplicaCapacityGoal
  3. To ignore the configured hard goals, add the skipHardGoalCheck: true property:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      goals:
        - RackAwareGoal
        - ReplicaCapacityGoal
      skipHardGoalCheck: true
  4. (Optional) To approve the optimization proposal automatically, set the strimzi.io/rebalance-auto-approval annotation to true:

    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaRebalance
    metadata:
      name: my-rebalance
      labels:
        strimzi.io/cluster: my-cluster
      annotations:
        strimzi.io/rebalance-auto-approval: "true"
    spec:
      goals:
        - RackAwareGoal
        - ReplicaCapacityGoal
      skipHardGoalCheck: true
  5. Create or update the resource:

    kubectl apply -f <kafka_rebalance_configuration_file>

    The Cluster Operator requests the optimization proposal from Cruise Control. This might take a few minutes depending on the size of the Kafka cluster.

  6. If you used the automatic approval mechanism, wait for the status of the optimization proposal to change to Ready. If you haven’t enabled the automatic approval mechanism, wait for the status of the optimization proposal to change to ProposalReady:

    kubectl get kafkarebalance -o wide -w -n <namespace>
    PendingProposal

    A PendingProposal status means the rebalance operator is polling the Cruise Control API to check if the optimization proposal is ready.

    ProposalReady

    A ProposalReady status means the optimization proposal is ready for review and approval.

    When the status changes to ProposalReady, the optimization proposal is ready to approve.

  7. Review the optimization proposal.

    The optimization proposal is contained in the Status.Optimization Result property of the KafkaRebalance resource.

    kubectl describe kafkarebalance <kafka_rebalance_resource_name>
    Example optimization proposal
    Status:
      Conditions:
        Last Transition Time:  2020-05-19T13:50:12.533Z
        Status:                ProposalReady
        Type:                  State
      Observed Generation:     1
      Optimization Result:
        Data To Move MB:  0
        Excluded Brokers For Leadership:
        Excluded Brokers For Replica Move:
        Excluded Topics:
        Intra Broker Data To Move MB:         0
        Monitored Partitions Percentage:      100
        Num Intra Broker Replica Movements:   0
        Num Leader Movements:                 0
        Num Replica Movements:                26
        On Demand Balancedness Score After:   81.8666802863978
        On Demand Balancedness Score Before:  78.01176356230222
        Recent Windows:                       1
      Session Id:                             05539377-ca7b-45ef-b359-e13564f1458c

    The properties in the Optimization Result section describe the pending cluster rebalance operation. For descriptions of each property, see Contents of optimization proposals.

Insufficient CPU capacity

If a Kafka cluster is overloaded in terms of CPU utilization, you might see an insufficient CPU capacity error in the KafkaRebalance status. It’s worth noting that this utilization value is unaffected by the excludedTopics configuration. Although optimization proposals will not reassign replicas of excluded topics, their load is still considered in the utilization calculation.

Example CPU utilization error
com.linkedin.kafka.cruisecontrol.exception.OptimizationFailureException:
        [CpuCapacityGoal] Insufficient capacity for cpu (Utilization 615.21,
        Allowed Capacity 420.00, Threshold: 0.70). Add at least 3 brokers with
        the same cpu capacity (100.00) as broker-0. Add at least 3 brokers with
        the same cpu capacity (100.00) as broker-0.
Note

The error shows CPU capacity as a percentage rather than the number of CPU cores. For this reason, it does not directly map to the number of CPUs configured in the Kafka custom resource. It is like having a single virtual CPU per broker, which has the cycles of the CPUs configured in Kafka.spec.kafka.resources.limits.cpu. This has no effect on the rebalance behavior, since the ratio between CPU utilization and capacity remains the same.

Additional resources

6.7. Approving an optimization proposal

You can approve an optimization proposal generated by Cruise Control, if its status is ProposalReady. Cruise Control will then apply the optimization proposal to the Kafka cluster, reassigning partitions to brokers and changing partition leadership.

Caution

This is not a dry run. Before you approve an optimization proposal, you must:

Prerequisites
Procedure

Perform these steps for the optimization proposal that you want to approve.

  1. Unless the optimization proposal is newly generated, check that it is based on current information about the state of the Kafka cluster. To do so, refresh the optimization proposal to make sure it uses the latest cluster metrics:

    1. Annotate the KafkaRebalance resource in Kubernetes with strimzi.io/rebalance=refresh:

      kubectl annotate kafkarebalance <kafka_rebalance_resource_name> strimzi.io/rebalance=refresh
  2. Wait for the status of the optimization proposal to change to ProposalReady:

    kubectl get kafkarebalance -o wide -w -n <namespace>
    PendingProposal

    A PendingProposal status means the rebalance operator is polling the Cruise Control API to check if the optimization proposal is ready.

    ProposalReady

    A ProposalReady status means the optimization proposal is ready for review and approval.

    When the status changes to ProposalReady, the optimization proposal is ready to approve.

  3. Approve the optimization proposal that you want Cruise Control to apply.

    Annotate the KafkaRebalance resource in Kubernetes with strimzi.io/rebalance=approve:

    kubectl annotate kafkarebalance <kafka_rebalance_resource_name> strimzi.io/rebalance=approve
  4. The Cluster Operator detects the annotated resource and instructs Cruise Control to rebalance the Kafka cluster.

  5. Wait for the status of the optimization proposal to change to Ready:

    kubectl get kafkarebalance -o wide -w -n <namespace>
    Rebalancing

    A Rebalancing status means the rebalancing is in progress.

    Ready

    A Ready status means the rebalance is complete.

    NotReady

    A NotReady status means an error occurred—​see Fixing problems with a KafkaRebalance resource.

    When the status changes to Ready, the rebalance is complete.

    To use the same KafkaRebalance custom resource to generate another optimization proposal, apply the refresh annotation to the custom resource. This moves the custom resource to the PendingProposal or ProposalReady state. You can then review the optimization proposal and approve it, if desired.

6.8. Stopping a cluster rebalance

Once started, a cluster rebalance operation might take some time to complete and affect the overall performance of the Kafka cluster.

If you want to stop a cluster rebalance operation that is in progress, apply the stop annotation to the KafkaRebalance custom resource. This instructs Cruise Control to finish the current batch of partition reassignments and then stop the rebalance. When the rebalance has stopped, completed partition reassignments have already been applied; therefore, the state of the Kafka cluster is different when compared to prior to the start of the rebalance operation. If further rebalancing is required, you should generate a new optimization proposal.

Note
The performance of the Kafka cluster in the intermediate (stopped) state might be worse than in the initial state.
Prerequisites
  • You have approved the optimization proposal by annotating the KafkaRebalance custom resource with approve.

  • The status of the KafkaRebalance custom resource is Rebalancing.

Procedure
  1. Annotate the KafkaRebalance resource in Kubernetes:

    kubectl annotate kafkarebalance rebalance-cr-name strimzi.io/rebalance=stop
  2. Check the status of the KafkaRebalance resource:

    kubectl describe kafkarebalance rebalance-cr-name
  3. Wait until the status changes to Stopped.

Additional resources

6.9. Fixing problems with a KafkaRebalance resource

If an issue occurs when creating a KafkaRebalance resource or interacting with Cruise Control, the error is reported in the resource status, along with details of how to fix it. The resource also moves to the NotReady state.

To continue with the cluster rebalance operation, you must fix the problem in the KafkaRebalance resource itself or with the overall Cruise Control deployment. Problems might include the following:

  • A misconfigured parameter in the KafkaRebalance resource.

  • The strimzi.io/cluster label for specifying the Kafka cluster in the KafkaRebalance resource is missing.

  • The Cruise Control server is not deployed as the cruiseControl property in the Kafka resource is missing.

  • The Cruise Control server is not reachable.

After fixing the issue, you need to add the refresh annotation to the KafkaRebalance resource. During a “refresh”, a new optimization proposal is requested from the Cruise Control server.

Prerequisites
Procedure
  1. Get information about the error from the KafkaRebalance status:

    kubectl describe kafkarebalance rebalance-cr-name
  2. Attempt to resolve the issue in the KafkaRebalance resource.

  3. Annotate the KafkaRebalance resource in Kubernetes:

    kubectl annotate kafkarebalance rebalance-cr-name strimzi.io/rebalance=refresh
  4. Check the status of the KafkaRebalance resource:

    kubectl describe kafkarebalance rebalance-cr-name
  5. Wait until the status changes to PendingProposal, or directly to ProposalReady.

Additional resources

7. Managing TLS certificates

Strimzi supports TLS for encrypted communication between Kafka and Strimzi components.

Communication is always encrypted between the following components:

  • Communication between Kafka and ZooKeeper

  • Interbroker communication between Kafka brokers

  • Internodal communication between ZooKeeper nodes

  • Strimzi operator communication with Kafka brokers and ZooKeeper nodes

Communication between Kafka clients and Kafka brokers is encrypted according to how the cluster is configured. For the Kafka and Strimzi components, TLS certificates are also used for authentication.

The Cluster Operator automatically sets up and renews TLS certificates to enable encryption and authentication within your cluster. It also sets up other TLS certificates if you want to enable encryption or mTLS authentication between Kafka brokers and clients.

CA (certificate authority) certificates are generated by the Cluster Operator to verify the identities of components and clients. If you don’t want to use the CAs generated by the Cluster Operator, you can install your own cluster and clients CA certificates.

You can also provide Kafka listener certificates for TLS listeners or external listeners that have TLS encryption enabled. Use Kafka listener certificates to incorporate the security infrastructure you already have in place.

Note
Any certificates you provide are not renewed by the Cluster Operator.
Secure Communication
Figure 3. Example architecture of the communication secured by TLS

7.1. Internal cluster CA and clients CA

To support encryption, each Strimzi component needs its own private keys and public key certificates. All component certificates are signed by an internal CA (certificate authority) called the cluster CA.

Similarly, each Kafka client application connecting to Strimzi using mTLS needs to use private keys and certificates. A second internal CA, named the clients CA, is used to sign certificates for the Kafka clients.

Both the cluster CA and clients CA have a self-signed public key certificate.

Kafka brokers are configured to trust certificates signed by either the cluster CA or clients CA. Components that clients do not need to connect to, such as ZooKeeper, only trust certificates signed by the cluster CA. Unless TLS encryption for external listeners is disabled, client applications must trust certificates signed by the cluster CA. This is also true for client applications that perform mTLS authentication.

By default, Strimzi automatically generates and renews CA certificates issued by the cluster CA or clients CA. You can configure the management of these CA certificates in the Kafka.spec.clusterCa and Kafka.spec.clientsCa objects.

You can replace the CA certificates for the cluster CA or clients CA with your own. For more information, see Installing your own CA certificates and private keys. If you provide your own CA certificates, you must renew them before they expire.

7.2. Secrets generated by the operators

Secrets are created when custom resources are deployed, such as Kafka and KafkaUser. Strimzi uses these secrets to store private and public key certificates for Kafka clusters, clients, and users. The secrets are used for establishing TLS encrypted connections between Kafka brokers, and between brokers and clients. They are also used for mTLS authentication.

Cluster and clients secrets are always pairs: one contains the public key and one contains the private key.

Cluster secret

A cluster secret contains the cluster CA to sign Kafka broker certificates. Connecting clients use the certificate to establish a TLS encrypted connection with a Kafka cluster. The certificate verifies broker identity.

Client secret

A client secret contains the clients CA for a user to sign its own client certificate. This allows mutual authentication against the Kafka cluster. The broker validates a client’s identity through the certificate.

User secret

A user secret contains a private key and certificate. The secret is created and signed by the clients CA when a new user is created. The key and certificate are used to authenticate and authorize the user when accessing the cluster.

7.2.1. TLS authentication using keys and certificates in PEM or PKCS #12 format

The secrets created by Strimzi provide private keys and certificates in PEM (Privacy Enhanced Mail) and PKCS #12 (Public-Key Cryptography Standards) formats. PEM and PKCS #12 are OpenSSL-generated key formats for TLS communications using the SSL protocol.

You can configure mutual TLS (mTLS) authentication that uses the credentials contained in the secrets generated for a Kafka cluster and user.

To set up mTLS, you must first do the following:

When you deploy a Kafka cluster, a <cluster_name>-cluster-ca-cert secret is created with public key to verify the cluster. You use the public key to configure a truststore for the client.

When you create a KafkaUser, a <kafka_user_name> secret is created with the keys and certificates to verify the user (client). Use these credentials to configure a keystore for the client.

With the Kafka cluster and client set up to use mTLS, you extract credentials from the secrets and add them to your client configuration.

PEM keys and certificates

For PEM, you add the following to your client configuration:

Truststore
  • ca.crt from the <cluster_name>-cluster-ca-cert secret, which is the CA certificate for the cluster.

Keystore
  • user.crt from the <kafka_user_name> secret, which is the public certificate of the user.

  • user.key from the <kafka_user_name> secret, which is the private key of the user.

PKCS #12 keys and certificates

For PKCS #12, you add the following to your client configuration:

Truststore
  • ca.p12 from the <cluster_name>-cluster-ca-cert secret, which is the CA certificate for the cluster.

  • ca.password from the <cluster_name>-cluster-ca-cert secret, which is the password to access the public cluster CA certificate.

Keystore
  • user.p12 from the <kafka_user_name> secret, which is the public key certificate of the user.

  • user.password from the <kafka_user_name> secret, which is the password to access the public key certificate of the Kafka user.

PKCS #12 is supported by Java, so you can add the values of the certificates directly to your Java client configuration. You can also reference the certificates from a secure storage location. With PEM files, you must add the certificates directly to the client configuration in single-line format. Choose a format that’s suitable for establishing TLS connections between your Kafka cluster and client. Use PKCS #12 if you are unfamiliar with PEM.

Note
All keys are 2048 bits in size and, by default, are valid for 365 days from the initial generation. You can change the validity period.

7.2.2. Secrets generated by the Cluster Operator

The Cluster Operator generates the following certificates, which are saved as secrets in the Kubernetes cluster. Strimzi uses these secrets by default.

The cluster CA and clients CA have separate secrets for the private key and public key.

<cluster_name>-cluster-ca

Contains the private key of the cluster CA. Strimzi and Kafka components use the private key to sign server certificates.

<cluster_name>-cluster-ca-cert

Contains the public key of the cluster CA. Kafka clients use the public key to verify the identity of the Kafka brokers they are connecting to with TLS server authentication.

<cluster_name>-clients-ca

Contains the private key of the clients CA. Kafka clients use the private key to sign new user certificates for mTLS authentication when connecting to Kafka brokers.

<cluster_name>-clients-ca-cert

Contains the public key of the clients CA. Kafka brokers use the public key to verify the identity of clients accessing the Kafka brokers when mTLS authentication is used.

Secrets for communication between Strimzi components contain a private key and a public key certificate signed by the cluster CA.

<cluster_name>-kafka-brokers

Contains the private and public keys for Kafka brokers.

<cluster_name>-zookeeper-nodes

Contains the private and public keys for ZooKeeper nodes.

<cluster_name>-cluster-operator-certs

Contains the private and public keys for encrypting communication between the Cluster Operator and Kafka or ZooKeeper.

<cluster_name>-entity-topic-operator-certs

Contains the private and public keys for encrypting communication between the Topic Operator and Kafka or ZooKeeper.

<cluster_name>-entity-user-operator-certs

Contains the private and public keys for encrypting communication between the User Operator and Kafka or ZooKeeper.

<cluster_name>-cruise-control-certs

Contains the private and public keys for encrypting communication between Cruise Control and Kafka or ZooKeeper.

<cluster_name>-kafka-exporter-certs

Contains the private and public keys for encrypting communication between Kafka Exporter and Kafka or ZooKeeper.

Note
You can provide your own server certificates and private keys to connect to Kafka brokers using Kafka listener certificates rather than certificates signed by the cluster CA.

7.2.3. Cluster CA secrets

Cluster CA secrets are managed by the Cluster Operator in a Kafka cluster.

Only the <cluster_name>-cluster-ca-cert secret is required by clients. All other cluster secrets are accessed by Strimzi components. You can enforce this using Kubernetes role-based access controls, if necessary.

Note
The CA certificates in <cluster_name>-cluster-ca-cert must be trusted by Kafka client applications so that they validate the Kafka broker certificates when connecting to Kafka brokers over TLS.
Table 14. Fields in the <cluster_name>-cluster-ca secret
Field Description

ca.key

The current private key for the cluster CA.

Table 15. Fields in the <cluster_name>-cluster-ca-cert secret
Field Description

ca.p12

PKCS #12 store for storing certificates and keys.

ca.password

Password for protecting the PKCS #12 store.

ca.crt

The current certificate for the cluster CA.

Table 16. Fields in the <cluster_name>-kafka-brokers secret
Field Description

<cluster_name>-kafka-<num>.p12

PKCS #12 store for storing certificates and keys.

<cluster_name>-kafka-<num>.password

Password for protecting the PKCS #12 store.

<cluster_name>-kafka-<num>.crt

Certificate for a Kafka broker pod <num>. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

<cluster_name>-kafka-<num>.key

Private key for a Kafka broker pod <num>.

Table 17. Fields in the <cluster_name>-zookeeper-nodes secret
Field Description

<cluster_name>-zookeeper-<num>.p12

PKCS #12 store for storing certificates and keys.

<cluster_name>-zookeeper-<num>.password

Password for protecting the PKCS #12 store.

<cluster_name>-zookeeper-<num>.crt

Certificate for ZooKeeper node <num>. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

<cluster_name>-zookeeper-<num>.key

Private key for ZooKeeper pod <num>.

Table 18. Fields in the <cluster_name>-cluster-operator-certs secret
Field Description

cluster-operator.p12

PKCS #12 store for storing certificates and keys.

cluster-operator.password

Password for protecting the PKCS #12 store.

cluster-operator.crt

Certificate for mTLS communication between the Cluster Operator and Kafka or ZooKeeper. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

cluster-operator.key

Private key for mTLS communication between the Cluster Operator and Kafka or ZooKeeper.

Table 19. Fields in the <cluster_name>-entity-topic-operator-certs secret
Field Description

entity-operator.p12

PKCS #12 store for storing certificates and keys.

entity-operator.password

Password for protecting the PKCS #12 store.

entity-operator.crt

Certificate for mTLS communication between the Topic Operator and Kafka or ZooKeeper. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

entity-operator.key

Private key for mTLS communication between the Topic Operator and Kafka or ZooKeeper.

Table 20. Fields in the <cluster_name>-entity-user-operator-certs secret
Field Description

entity-operator.p12

PKCS #12 store for storing certificates and keys.

entity-operator.password

Password for protecting the PKCS #12 store.

entity-operator.crt

Certificate for mTLS communication between the User Operator and Kafka or ZooKeeper. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

entity-operator.key

Private key for mTLS communication between the User Operator and Kafka or ZooKeeper.

Table 21. Fields in the <cluster_name>-cruise-control-certs secret
Field Description

cruise-control.p12

PKCS #12 store for storing certificates and keys.

cruise-control.password

Password for protecting the PKCS #12 store.

cruise-control.crt

Certificate for mTLS communication between Cruise Control and Kafka or ZooKeeper. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

cruise-control.key

Private key for mTLS communication between the Cruise Control and Kafka or ZooKeeper.

Table 22. Fields in the <cluster_name>-kafka-exporter-certs secret
Field Description

kafka-exporter.p12

PKCS #12 store for storing certificates and keys.

kafka-exporter.password

Password for protecting the PKCS #12 store.

kafka-exporter.crt

Certificate for mTLS communication between Kafka Exporter and Kafka or ZooKeeper. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca.

kafka-exporter.key

Private key for mTLS communication between the Kafka Exporter and Kafka or ZooKeeper.

7.2.4. Clients CA secrets

Clients CA secrets are managed by the Cluster Operator in a Kafka cluster.

The certificates in <cluster_name>-clients-ca-cert are those which the Kafka brokers trust.

The <cluster_name>-clients-ca secret is used to sign the certificates of client applications. This secret must be accessible to the Strimzi components and for administrative access if you are intending to issue application certificates without using the User Operator. You can enforce this using Kubernetes role-based access controls, if necessary.

Table 23. Fields in the <cluster_name>-clients-ca secret
Field Description

ca.key

The current private key for the clients CA.

Table 24. Fields in the <cluster_name>-clients-ca-cert secret
Field Description

ca.p12

PKCS #12 store for storing certificates and keys.

ca.password

Password for protecting the PKCS #12 store.

ca.crt

The current certificate for the clients CA.

7.2.5. User secrets generated by the User Operator

User secrets are managed by the User Operator.

When a user is created using the User Operator, a secret is generated using the name of the user.

Table 25. Fields in the user_name secret
Secret name Field within secret Description

<user_name>

user.p12

PKCS #12 store for storing certificates and keys.

user.password

Password for protecting the PKCS #12 store.

user.crt

Certificate for the user, signed by the clients CA

user.key

Private key for the user

7.2.6. Adding labels and annotations to cluster CA secrets

By configuring the clusterCaCert template property in the Kafka custom resource, you can add custom labels and annotations to the Cluster CA secrets created by the Cluster Operator. Labels and annotations are useful for identifying objects and adding contextual information. You configure template properties in Strimzi custom resources.

Example template customization to add labels and annotations to secrets
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    template:
      clusterCaCert:
        metadata:
          labels:
            label1: value1
            label2: value2
          annotations:
            annotation1: value1
            annotation2: value2
    # ...

For more information on configuring template properties, see Customizing Kubernetes resources.

7.2.7. Disabling ownerReference in the CA secrets

By default, the cluster and clients CA secrets are created with an ownerReference property that is set to the Kafka custom resource. This means that, when the Kafka custom resource is deleted, the CA secrets are also deleted (garbage collected) by Kubernetes.

If you want to reuse the CA for a new cluster, you can disable the ownerReference by setting the generateSecretOwnerReference property for the cluster and clients CA secrets to false in the Kafka configuration. When the ownerReference is disabled, CA secrets are not deleted by Kubernetes when the corresponding Kafka custom resource is deleted.

Example Kafka configuration with disabled ownerReference for cluster and clients CAs
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
# ...
spec:
# ...
  clusterCa:
    generateSecretOwnerReference: false
  clientsCa:
    generateSecretOwnerReference: false
# ...

7.3. Certificate renewal and validity periods

Cluster CA and clients CA certificates are only valid for a limited time period, known as the validity period. This is usually defined as a number of days since the certificate was generated.

For CA certificates automatically created by the Cluster Operator, you can configure the validity period of:

  • Cluster CA certificates in Kafka.spec.clusterCa.validityDays

  • Clients CA certificates in Kafka.spec.clientsCa.validityDays

The default validity period for both certificates is 365 days. Manually-installed CA certificates should have their own validity periods defined.

When a CA certificate expires, components and clients that still trust that certificate will not accept connections from peers whose certificates were signed by the CA private key. The components and clients need to trust the new CA certificate instead.

To allow the renewal of CA certificates without a loss of service, the Cluster Operator initiates certificate renewal before the old CA certificates expire.

You can configure the renewal period of the certificates created by the Cluster Operator:

  • Cluster CA certificates in Kafka.spec.clusterCa.renewalDays

  • Clients CA certificates in Kafka.spec.clientsCa.renewalDays

The default renewal period for both certificates is 30 days.

The renewal period is measured backwards, from the expiry date of the current certificate.

Validity period against renewal period
Not Before                                     Not After
    |                                              |
    |<--------------- validityDays --------------->|
                              <--- renewalDays --->|

To make a change to the validity and renewal periods after creating the Kafka cluster, you configure and apply the Kafka custom resource, and manually renew the CA certificates. If you do not manually renew the certificates, the new periods will be used the next time the certificate is renewed automatically.

Example Kafka configuration for certificate validity and renewal periods
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
# ...
spec:
# ...
  clusterCa:
    renewalDays: 30
    validityDays: 365
    generateCertificateAuthority: true
  clientsCa:
    renewalDays: 30
    validityDays: 365
    generateCertificateAuthority: true
# ...

The behavior of the Cluster Operator during the renewal period depends on the settings for the generateCertificateAuthority certificate generation properties for the cluster CA and clients CA.

true

If the properties are set to true, a CA certificate is generated automatically by the Cluster Operator, and renewed automatically within the renewal period.

false

If the properties are set to false, a CA certificate is not generated by the Cluster Operator. Use this option if you are installing your own certificates.

7.3.1. Renewal process with automatically generated CA certificates

The Cluster Operator performs the following processes in this order when renewing CA certificates:

  1. Generates a new CA certificate, but retains the existing key.

    The new certificate replaces the old one with the name ca.crt within the corresponding Secret.

  2. Generates new client certificates (for ZooKeeper nodes, Kafka brokers, and the Entity Operator).

    This is not strictly necessary because the signing key has not changed, but it keeps the validity period of the client certificate in sync with the CA certificate.

  3. Restarts ZooKeeper nodes so that they will trust the new CA certificate and use the new client certificates.

  4. Restarts Kafka brokers so that they will trust the new CA certificate and use the new client certificates.

  5. Restarts the Topic and User Operators so that they will trust the new CA certificate and use the new client certificates.

    User certificates are signed by the clients CA. User certificates generated by the User Operator are renewed when the clients CA is renewed.

7.3.2. Client certificate renewal

The Cluster Operator is not aware of the client applications using the Kafka cluster.

When connecting to the cluster, and to ensure they operate correctly, client applications must:

  • Trust the cluster CA certificate published in the <cluster>-cluster-ca-cert Secret.

  • Use the credentials published in their <user-name> Secret to connect to the cluster.

    The User Secret provides credentials in PEM and PKCS #12 format, or it can provide a password when using SCRAM-SHA authentication. The User Operator creates the user credentials when a user is created.

You must ensure clients continue to work after certificate renewal. The renewal process depends on how the clients are configured.

If you are provisioning client certificates and keys manually, you must generate new client certificates and ensure the new certificates are used by clients within the renewal period. Failure to do this by the end of the renewal period could result in client applications being unable to connect to the cluster.

Note
For workloads running inside the same Kubernetes cluster and namespace, Secrets can be mounted as a volume so the client Pods construct their keystores and truststores from the current state of the Secrets. For more details on this procedure, see Configuring internal clients to trust the cluster CA.

7.3.3. Manually renewing the CA certificates generated by the Cluster Operator

Cluster and clients CA certificates generated by the Cluster Operator auto-renew at the start of their respective certificate renewal periods. However, you can use the strimzi.io/force-renew annotation to manually renew one or both of these certificates before the certificate renewal period starts. You might do this for security reasons, or if you have changed the renewal or validity periods for the certificates.

A renewed certificate uses the same private key as the old certificate.

Note
If you are using your own CA certificates, the force-renew annotation cannot be used. Instead, follow the procedure for renewing your own CA certificates.
Prerequisites
  • The Cluster Operator is running.

  • A Kafka cluster in which CA certificates and private keys are installed.

Procedure
  1. Apply the strimzi.io/force-renew annotation to the Secret that contains the CA certificate that you want to renew.

    Table 26. Annotation for the Secret that forces renewal of certificates
    Certificate Secret Annotate command

    Cluster CA

    KAFKA-CLUSTER-NAME-cluster-ca-cert

    kubectl annotate secret KAFKA-CLUSTER-NAME-cluster-ca-cert strimzi.io/force-renew=true

    Clients CA

    KAFKA-CLUSTER-NAME-clients-ca-cert

    kubectl annotate secret KAFKA-CLUSTER-NAME-clients-ca-cert strimzi.io/force-renew=true

    At the next reconciliation the Cluster Operator will generate a new CA certificate for the Secret that you annotated. If maintenance time windows are configured, the Cluster Operator will generate the new CA certificate at the first reconciliation within the next maintenance time window.

    Client applications must reload the cluster and clients CA certificates that were renewed by the Cluster Operator.

  2. Check the period the CA certificate is valid:

    For example, using an openssl command:

    kubectl get secret CA-CERTIFICATE-SECRET -o 'jsonpath={.data.CA-CERTIFICATE}' | base64 -d | openssl x509 -subject -issuer -startdate -enddate -noout

    CA-CERTIFICATE-SECRET is the name of the Secret, which is KAFKA-CLUSTER-NAME-cluster-ca-cert for the cluster CA certificate and KAFKA-CLUSTER-NAME-clients-ca-cert for the clients CA certificate.

    CA-CERTIFICATE is the name of the CA certificate, such as jsonpath={.data.ca\.crt}.

    The command returns a notBefore and notAfter date, which is the validity period for the CA certificate.

    For example, for a cluster CA certificate:

    subject=O = io.strimzi, CN = cluster-ca v0
    issuer=O = io.strimzi, CN = cluster-ca v0
    notBefore=Jun 30 09:43:54 2020 GMT
    notAfter=Jun 30 09:43:54 2021 GMT
  3. Delete old certificates from the Secret.

    When components are using the new certificates, older certificates might still be active. Delete the old certificates to remove any potential security risk.

7.3.4. Replacing private keys used by the CA certificates generated by the Cluster Operator

You can replace the private keys used by the cluster CA and clients CA certificates generated by the Cluster Operator. When a private key is replaced, the Cluster Operator generates a new CA certificate for the new private key.

Note
If you are using your own CA certificates, the force-replace annotation cannot be used. Instead, follow the procedure for renewing your own CA certificates.
Prerequisites
  • The Cluster Operator is running.

  • A Kafka cluster in which CA certificates and private keys are installed.

Procedure
  • Apply the strimzi.io/force-replace annotation to the Secret that contains the private key that you want to renew.

    Table 27. Commands for replacing private keys
    Private key for Secret Annotate command

    Cluster CA

    CLUSTER-NAME-cluster-ca

    kubectl annotate secret CLUSTER-NAME-cluster-ca strimzi.io/force-replace=true

    Clients CA

    CLUSTER-NAME-clients-ca

    kubectl annotate secret CLUSTER-NAME-clients-ca strimzi.io/force-replace=true

At the next reconciliation the Cluster Operator will:

  • Generate a new private key for the Secret that you annotated

  • Generate a new CA certificate

If maintenance time windows are configured, the Cluster Operator will generate the new private key and CA certificate at the first reconciliation within the next maintenance time window.

Client applications must reload the cluster and clients CA certificates that were renewed by the Cluster Operator.

7.4. TLS connections

7.4.1. ZooKeeper communication

Communication between the ZooKeeper nodes on all ports, as well as between clients and ZooKeeper, is encrypted using TLS.

Communication between Kafka brokers and ZooKeeper nodes is also encrypted.

7.4.2. Kafka inter-broker communication

Communication between Kafka brokers is always encrypted using TLS. The connections between the Kafka controller and brokers use an internal control plane listener on port 9090. Replication of data between brokers, as well as internal connections from Strimzi operators, Cruise Control, or the Kafka Exporter use the replication listener on port 9091. These internal listeners are not available to Kafka clients.

7.4.3. Topic and User Operators

All Operators use encryption for communication with both Kafka and ZooKeeper. In Topic and User Operators, a TLS sidecar is used when communicating with ZooKeeper.

7.4.4. Cruise Control

Cruise Control uses encryption for communication with both Kafka and ZooKeeper. A TLS sidecar is used when communicating with ZooKeeper.

7.4.5. Kafka Client connections

Encrypted or unencrypted communication between Kafka brokers and clients is configured using the tls property for spec.kafka.listeners.

7.5. Configuring internal clients to trust the cluster CA

This procedure describes how to configure a Kafka client that resides inside the Kubernetes cluster — connecting to a TLS listener — to trust the cluster CA certificate.

The easiest way to achieve this for an internal client is to use a volume mount to access the Secrets containing the necessary certificates and keys.

Follow the steps to configure trust certificates that are signed by the cluster CA for Java-based Kafka Producer, Consumer, and Streams APIs.

Choose the steps to follow according to the certificate format of the cluster CA: PKCS #12 (.p12) or PEM (.crt).

The steps describe how to mount the Cluster Secret that verifies the identity of the Kafka cluster to the client pod.

Prerequisites
  • The Cluster Operator must be running.

  • There needs to be a Kafka resource within the Kubernetes cluster.

  • You need a Kafka client application inside the Kubernetes cluster that will connect using TLS, and needs to trust the cluster CA certificate.

  • The client application must be running in the same namespace as the Kafka resource.

Using PKCS #12 format (.p12)
  1. Mount the cluster Secret as a volume when defining the client pod.

    For example:

    kind: Pod
    apiVersion: v1
    metadata:
      name: client-pod
    spec:
      containers:
      - name: client-name
        image: client-name
        volumeMounts:
        - name: secret-volume
          mountPath: /data/p12
        env:
        - name: SECRET_PASSWORD
          valueFrom:
            secretKeyRef:
              name: my-secret
              key: my-password
      volumes:
      - name: secret-volume
        secret:
          secretName: my-cluster-cluster-ca-cert

    Here we’re mounting the following:

    • The PKCS #12 file into an exact path, which can be configured

    • The password into an environment variable, where it can be used for Java configuration

  2. Configure the Kafka client with the following properties:

    • A security protocol option:

      • security.protocol: SSL when using TLS for encryption (with or without mTLS authentication).

      • security.protocol: SASL_SSL when using SCRAM-SHA authentication over TLS.

    • ssl.truststore.location with the truststore location where the certificates were imported.

    • ssl.truststore.password with the password for accessing the truststore.

    • ssl.truststore.type=PKCS12 to identify the truststore type.

Using PEM format (.crt)
  1. Mount the cluster Secret as a volume when defining the client pod.

    For example:

    kind: Pod
    apiVersion: v1
    metadata:
      name: client-pod
    spec:
      containers:
      - name: client-name
        image: client-name
        volumeMounts:
        - name: secret-volume
          mountPath: /data/crt
      volumes:
      - name: secret-volume
        secret:
          secretName: my-cluster-cluster-ca-cert
  2. Use the extracted certificate to configure a TLS connection in clients that use certificates in X.509 format.

7.6. Configuring external clients to trust the cluster CA

This procedure describes how to configure a Kafka client that resides outside the Kubernetes cluster – connecting to an external listener – to trust the cluster CA certificate. Follow this procedure when setting up the client and during the renewal period, when the old clients CA certificate is replaced.

Follow the steps to configure trust certificates that are signed by the cluster CA for Java-based Kafka Producer, Consumer, and Streams APIs.

Choose the steps to follow according to the certificate format of the cluster CA: PKCS #12 (.p12) or PEM (.crt).

The steps describe how to obtain the certificate from the Cluster Secret that verifies the identity of the Kafka cluster.

Important
The <cluster_name>-cluster-ca-cert secret contains more than one CA certificate during the CA certificate renewal period. Clients must add all of them to their truststores.
Prerequisites
  • The Cluster Operator must be running.

  • There needs to be a Kafka resource within the Kubernetes cluster.

  • You need a Kafka client application outside the Kubernetes cluster that will connect using TLS, and needs to trust the cluster CA certificate.

Using PKCS #12 format (.p12)
  1. Extract the cluster CA certificate and password from the <cluster_name>-cluster-ca-cert Secret of the Kafka cluster.

    kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.p12}' | base64 -d > ca.p12
    kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.password}' | base64 -d > ca.password

    Replace <cluster_name> with the name of the Kafka cluster.

  2. Configure the Kafka client with the following properties:

    • A security protocol option:

      • security.protocol: SSL when using TLS.

      • security.protocol: SASL_SSL when using SCRAM-SHA authentication over TLS.

    • ssl.truststore.location with the truststore location where the certificates were imported.

    • ssl.truststore.password with the password for accessing the truststore. This property can be omitted if it is not needed by the truststore.

    • ssl.truststore.type=PKCS12 to identify the truststore type.

Using PEM format (.crt)
  1. Extract the cluster CA certificate from the <cluster_name>-cluster-ca-cert secret of the Kafka cluster.

    kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
  2. Use the extracted certificate to configure a TLS connection in clients that use certificates in X.509 format.

7.7. Using your own CA certificates and private keys

Install and use your own CA certificates and private keys instead of using the defaults generated by the Cluster Operator. You can replace the cluster and clients CA certificates and private keys.

You can switch to using your own CA certificates and private keys in the following ways:

  • Install your own CA certificates and private keys before deploying your Kafka cluster

  • Replace the default CA certificates and private keys with your own after deploying a Kafka cluster

The steps to replace the default CA certificates and private keys after deploying a Kafka cluster are the same as those used to renew your own CA certificates and private keys.

If you use your own certificates, they won’t be renewed automatically. You need to renew the CA certificates and private keys before they expire.

Renewal options:

  • Renew the CA certificates only

  • Renew CA certificates and private keys (or replace the defaults)

7.7.1. Installing your own CA certificates and private keys

Install your own CA certificates and private keys instead of using the cluster and clients CA certificates and private keys generated by the Cluster Operator.

By default, Strimzi uses the following cluster CA and clients CA secrets, which are renewed automatically.

  • Cluster CA secrets

    • <cluster_name>-cluster-ca

    • <cluster_name>-cluster-ca-cert

  • Clients CA secrets

    • <cluster_name>-clients-ca

    • <cluster_name>-clients-ca-cert

To install your own certificates, use the same names.

Prerequisites
  • The Cluster Operator is running.

  • A Kafka cluster is not yet deployed.

    If you have already deployed a Kafka cluster, you can replace the default CA certificates with your own.

  • Your own X.509 certificates and keys in PEM format for the cluster CA or clients CA.

    • If you want to use a cluster or clients CA which is not a Root CA, you have to include the whole chain in the certificate file. The chain should be in the following order:

      1. The cluster or clients CA

      2. One or more intermediate CAs

      3. The root CA

    • All CAs in the chain should be configured using the X509v3 Basic Constraints extension. Basic Constraints limit the path length of a certificate chain.

  • The OpenSSL TLS management tool for converting certificates.

Before you begin

The Cluster Operator generates keys and certificates in PEM (Privacy Enhanced Mail) and PKCS #12 (Public-Key Cryptography Standards) formats. You can add your own certificates in either format.

Some applications cannot use PEM certificates and support only PKCS #12 certificates. If you don’t have a cluster certificate in PKCS #12 format, use the OpenSSL TLS management tool to generate one from your ca.crt file.

Example certificate generation command
openssl pkcs12 -export -in ca.crt -nokeys -out ca.p12 -password pass:<P12_password> -caname ca.crt

Replace <P12_password> with your own password.

Procedure
  1. Create a new secret that contains the CA certificate.

    Client secret creation with a certificate in PEM format only
    kubectl create secret generic <cluster_name>-clients-ca-cert --from-file=ca.crt=ca.crt
    Cluster secret creation with certificates in PEM and PKCS #12 format
    kubectl create secret generic <cluster_name>-cluster-ca-cert \
      --from-file=ca.crt=ca.crt \
      --from-file=ca.p12=ca.p12 \
      --from-literal=ca.password=P12-PASSWORD

    Replace <cluster_name> with the name of your Kafka cluster.

  2. Create a new secret that contains the private key.

    kubectl create secret generic CA-KEY-SECRET --from-file=ca.key=ca.key
  3. Label the secrets.

    kubectl label secret CA-CERTIFICATE-SECRET strimzi.io/kind=Kafka strimzi.io/cluster=<cluster_name>
    kubectl label secret CA-KEY-SECRET strimzi.io/kind=Kafka strimzi.io/cluster=<cluster_name>
    • Label strimzi.io/kind=Kafka identifies the Kafka custom resource.

    • Label strimzi.io/cluster=<cluster_name> identifies the Kafka cluster.

  4. Annotate the secrets

    kubectl annotate secret CA-CERTIFICATE-SECRET strimzi.io/ca-cert-generation=CA-CERTIFICATE-GENERATION
    kubectl annotate secret CA-KEY-SECRET strimzi.io/ca-key-generation=CA-KEY-GENERATION
    • Annotation strimzi.io/ca-cert-generation=CA-CERTIFICATE-GENERATION defines the generation of a new CA certificate.

    • Annotation strimzi.io/ca-key-generation=CA-KEY-GENERATION defines the generation of a new CA key.

      Start from 0 (zero) as the incremental value (strimzi.io/ca-cert-generation=0) for your own CA certificate. Set a higher incremental value when you renew the certificates.

  5. Create the Kafka resource for your cluster, configuring either the Kafka.spec.clusterCa or the Kafka.spec.clientsCa object to not use generated CAs.

    Example fragment Kafka resource configuring the cluster CA to use certificates you supply for yourself
    kind: Kafka
    version: kafka.strimzi.io/v1beta2
    spec:
      # ...
      clusterCa:
        generateCertificateAuthority: false

7.7.2. Renewing your own CA certificates

If you are using your own CA certificates, you need to renew them manually. The Cluster Operator will not renew them automatically. Renew the CA certificates in the renewal period before they expire.

Perform the steps in this procedure when you are renewing CA certificates and continuing with the same private key. If you are renewing your own CA certificates and private keys, see Renewing or replacing CA certificates and private keys with your own.

The procedure describes the renewal of CA certificates in PEM format.

Prerequisites
  • The Cluster Operator is running.

  • You have new cluster or clients X.509 certificates in PEM format.

Procedure
  1. Update the Secret for the CA certificate.

    Edit the existing secret to add the new CA certificate and update the certificate generation annotation value.

    kubectl edit secret <ca_certificate_secret_name>

    <ca_certificate_secret_name> is the name of the Secret, which is <kafka_cluster_name>-cluster-ca-cert for the cluster CA certificate and <kafka_cluster_name>-clients-ca-cert for the clients CA certificate.

    The following example shows a secret for a cluster CA certificate that’s associated with a Kafka cluster named my-cluster.

    Example secret configuration for a cluster CA certificate
    apiVersion: v1
    kind: Secret
    data:
      ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0F... (1)
    metadata:
      annotations:
        strimzi.io/ca-cert-generation: "0" (2)
      labels:
        strimzi.io/cluster: my-cluster
        strimzi.io/kind: Kafka
      name: my-cluster-cluster-ca-cert
      #...
    type: Opaque
    1. Current base64-encoded CA certificate

    2. Current CA certificate generation annotation value

  2. Encode your new CA certificate into base64.

    cat <path_to_new_certificate> | base64
  3. Update the CA certificate.

    Copy the base64-encoded CA certificate from the previous step as the value for the ca.crt property under data.

  4. Increase the value of the CA certificate generation annotation.

    Update the strimzi.io/ca-cert-generation annotation with a higher incremental value. For example, change strimzi.io/ca-cert-generation=0 to strimzi.io/ca-cert-generation=1. If the Secret is missing the annotation, the value is treated as 0, so add the annotation with a value of 1.

    When Strimzi generates certificates, the certificate generation annotation is automatically incremented by the Cluster Operator. For your own CA certificates, set the annotations with a higher incremental value. The annotation needs a higher value than the one from the current secret so that the Cluster Operator can roll the pods and update the certificates. The strimzi.io/ca-cert-generation has to be incremented on each CA certificate renewal.

  5. Save the secret with the new CA certificate and certificate generation annotation value.

    Example secret configuration updated with a new CA certificate
    apiVersion: v1
    kind: Secret
    data:
      ca.crt: GCa6LS3RTHeKFiFDGBOUDYFAZ0F... (1)
    metadata:
      annotations:
        strimzi.io/ca-cert-generation: "1" (2)
      labels:
        strimzi.io/cluster: my-cluster
        strimzi.io/kind: Kafka
      name: my-cluster-cluster-ca-cert
      #...
    type: Opaque
    1. New base64-encoded CA certificate

    2. New CA certificate generation annotation value

On the next reconciliation, the Cluster Operator performs a rolling update of ZooKeeper, Kafka, and other components to trust the new CA certificate.

If maintenance time windows are configured, the Cluster Operator will roll the pods at the first reconciliation within the next maintenance time window.

7.7.3. Renewing or replacing CA certificates and private keys with your own

If you are using your own CA certificates and private keys, you need to renew them manually. The Cluster Operator will not renew them automatically. Renew the CA certificates in the renewal period before they expire. You can also use the same procedure to replace the CA certificates and private keys generated by the Strimzi operators with your own.

Perform the steps in this procedure when you are renewing or replacing CA certificates and private keys. If you are only renewing your own CA certificates, see Renewing your own CA certificates.

The procedure describes the renewal of CA certificates and private keys in PEM format.

Before going through the following steps, make sure that the CN (Common Name) of the new CA certificate is different from the current one. For example, when the Cluster Operator renews certificates automatically it adds a v<version_number> suffix to identify a version. Do the same with your own CA certificate by adding a different suffix on each renewal. By using a different key to generate a new CA certificate, you retain the current CA certificate stored in the Secret.

Prerequisites
  • The Cluster Operator is running.

  • You have new cluster or clients X.509 certificates and keys in PEM format.

Procedure
  1. Pause the reconciliation of the Kafka custom resource.

    1. Annotate the custom resource in Kubernetes, setting the pause-reconciliation annotation to true:

      kubectl annotate Kafka <name_of_custom_resource> strimzi.io/pause-reconciliation="true"

      For example, for a Kafka custom resource named my-cluster:

      kubectl annotate Kafka my-cluster strimzi.io/pause-reconciliation="true"
    2. Check that the status conditions of the custom resource show a change to ReconciliationPaused:

      kubectl describe Kafka <name_of_custom_resource>

      The type condition changes to ReconciliationPaused at the lastTransitionTime.

  2. Update the Secret for the CA certificate.

    1. Edit the existing secret to add the new CA certificate and update the certificate generation annotation value.

      kubectl edit secret <ca_certificate_secret_name>

      <ca_certificate_secret_name> is the name of the Secret, which is KAFKA-CLUSTER-NAME-cluster-ca-cert for the cluster CA certificate and KAFKA-CLUSTER-NAME-clients-ca-cert for the clients CA certificate.

      The following example shows a secret for a cluster CA certificate that’s associated with a Kafka cluster named my-cluster.

      Example secret configuration for a cluster CA certificate
      apiVersion: v1
      kind: Secret
      data:
        ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0F... (1)
      metadata:
        annotations:
          strimzi.io/ca-cert-generation: "0" (2)
        labels:
          strimzi.io/cluster: my-cluster
          strimzi.io/kind: Kafka
        name: my-cluster-cluster-ca-cert
        #...
      type: Opaque
      1. Current base64-encoded CA certificate

      2. Current CA certificate generation annotation value

    2. Rename the current CA certificate to retain it.

      Rename the current ca.crt property under data as ca-<date>.crt, where <date> is the certificate expiry date in the format YEAR-MONTH-DAYTHOUR-MINUTE-SECONDZ. For example ca-2022-01-26T17-32-00Z.crt:. Leave the value for the property as it is to retain the current CA certificate.

    3. Encode your new CA certificate into base64.

      cat <path_to_new_certificate> | base64
    4. Update the CA certificate.

      Create a new ca.crt property under data and copy the base64-encoded CA certificate from the previous step as the value for ca.crt property.

    5. Increase the value of the CA certificate generation annotation.

      Update the strimzi.io/ca-cert-generation annotation with a higher incremental value. For example, change strimzi.io/ca-cert-generation=0 to strimzi.io/ca-cert-generation=1. If the Secret is missing the annotation, the value is treated as 0, so add the annotation with a value of 1.

      When Strimzi generates certificates, the certificate generation annotation is automatically incremented by the Cluster Operator. For your own CA certificates, set the annotations with a higher incremental value. The annotation needs a higher value than the one from the current secret so that the Cluster Operator can roll the pods and update the certificates. The strimzi.io/ca-cert-generation has to be incremented on each CA certificate renewal.

    6. Save the secret with the new CA certificate and certificate generation annotation value.

      Example secret configuration updated with a new CA certificate
      apiVersion: v1
      kind: Secret
      data:
        ca.crt: GCa6LS3RTHeKFiFDGBOUDYFAZ0F... (1)
        ca-2022-01-26T17-32-00Z.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0F... (2)
      metadata:
        annotations:
          strimzi.io/ca-cert-generation: "1" (3)
        labels:
          strimzi.io/cluster: my-cluster
          strimzi.io/kind: Kafka
        name: my-cluster-cluster-ca-cert
        #...
      type: Opaque
      1. New base64-encoded CA certificate

      2. Old base64-encoded CA certificate

      3. New CA certificate generation annotation value

  3. Update the Secret for the CA key used to sign your new CA certificate.

    1. Edit the existing secret to add the new CA key and update the key generation annotation value.

      kubectl edit secret <ca_key_name>

      <ca_key_name> is the name of CA key, which is <kafka_cluster_name>-cluster-ca for the cluster CA key and <kafka_cluster_name>-clients-ca for the clients CA key.

      The following example shows a secret for a cluster CA key that’s associated with a Kafka cluster named my-cluster.

      Example secret configuration for a cluster CA key
      apiVersion: v1
      kind: Secret
      data:
        ca.key: SA1cKF1GFDzOIiPOIUQBHDNFGDFS... (1)
      metadata:
        annotations:
          strimzi.io/ca-key-generation: "0" (2)
        labels:
          strimzi.io/cluster: my-cluster
          strimzi.io/kind: Kafka
        name: my-cluster-cluster-ca
        #...
      type: Opaque
      1. Current base64-encoded CA key

      2. Current CA key generation annotation value

    2. Encode the CA key into base64.

      cat <path_to_new_key> | base64
    3. Update the CA key.

      Copy the base64-encoded CA key from the previous step as the value for the ca.key property under data.

    4. Increase the value of the CA key generation annotation.

      Update the strimzi.io/ca-key-generation annotation with a higher incremental value. For example, change strimzi.io/ca-key-generation=0 to strimzi.io/ca-key-generation=1. If the Secret is missing the annotation, it is treated as 0, so add the annotation with a value of 1.

      When Strimzi generates certificates, the key generation annotation is automatically incremented by the Cluster Operator. For your own CA certificates together with a new CA key, set the annotation with a higher incremental value. The annotation needs a higher value than the one from the current secret so that the Cluster Operator can roll the pods and update the certificates and keys. The strimzi.io/ca-key-generation has to be incremented on each CA certificate renewal.

  4. Save the secret with the new CA key and key generation annotation value.

    Example secret configuration updated with a new CA key
    apiVersion: v1
    kind: Secret
    data:
      ca.key: AB0cKF1GFDzOIiPOIUQWERZJQ0F... (1)
    metadata:
      annotations:
        strimzi.io/ca-key-generation: "1" (2)
      labels:
        strimzi.io/cluster: my-cluster
        strimzi.io/kind: Kafka
      name: my-cluster-cluster-ca
      #...
    type: Opaque
    1. New base64-encoded CA key

    2. New CA key generation annotation value

  5. Resume from the pause.

    To resume the Kafka custom resource reconciliation, set the pause-reconciliation annotation to false.

    kubectl annotate --overwrite Kafka <name_of_custom_resource> strimzi.io/pause-reconciliation="false"

    You can also do the same by removing the pause-reconciliation annotation.

    kubectl annotate Kafka <name_of_custom_resource> strimzi.io/pause-reconciliation-

On the next reconciliation, the Cluster Operator performs a rolling update of ZooKeeper, Kafka, and other components to trust the new CA certificate. When the rolling update is complete, the Cluster Operator will start a new one to generate new server certificates signed by the new CA key.

If maintenance time windows are configured, the Cluster Operator will roll the pods at the first reconciliation within the next maintenance time window.

8. Managing Strimzi

This chapter covers tasks to maintain a deployment of Strimzi.

8.1. Working with custom resources

You can use kubectl commands to retrieve information and perform other operations on Strimzi custom resources.

Using kubectl with the status subresource of a custom resource allows you to get the information about the resource.

8.1.1. Performing kubectl operations on custom resources

Use kubectl commands, such as get, describe, edit, or delete, to perform operations on resource types. For example, kubectl get kafkatopics retrieves a list of all Kafka topics and kubectl get kafkas retrieves all deployed Kafka clusters.

When referencing resource types, you can use both singular and plural names: kubectl get kafkas gets the same results as kubectl get kafka.

You can also use the short name of the resource. Learning short names can save you time when managing Strimzi. The short name for Kafka is k, so you can also run kubectl get k to list all Kafka clusters.

kubectl get k

NAME         DESIRED KAFKA REPLICAS   DESIRED ZK REPLICAS
my-cluster   3                        3
Table 28. Long and short names for each Strimzi resource
Strimzi resource Long name Short name

Kafka

kafka

k

Kafka Topic

kafkatopic

kt

Kafka User

kafkauser

ku

Kafka Connect

kafkaconnect

kc

Kafka Connector

kafkaconnector

kctr

Kafka Mirror Maker

kafkamirrormaker

kmm

Kafka Mirror Maker 2

kafkamirrormaker2

kmm2

Kafka Bridge

kafkabridge

kb

Kafka Rebalance

kafkarebalance

kr

Resource categories

Categories of custom resources can also be used in kubectl commands.

All Strimzi custom resources belong to the category strimzi, so you can use strimzi to get all the Strimzi resources with one command.

For example, running kubectl get strimzi lists all Strimzi custom resources in a given namespace.

kubectl get strimzi

NAME                                   DESIRED KAFKA REPLICAS DESIRED ZK REPLICAS
kafka.kafka.strimzi.io/my-cluster      3                      3

NAME                                   PARTITIONS REPLICATION FACTOR
kafkatopic.kafka.strimzi.io/kafka-apps 3          3

NAME                                   AUTHENTICATION AUTHORIZATION
kafkauser.kafka.strimzi.io/my-user     tls            simple

The kubectl get strimzi -o name command returns all resource types and resource names. The -o name option fetches the output in the type/name format

kubectl get strimzi -o name

kafka.kafka.strimzi.io/my-cluster
kafkatopic.kafka.strimzi.io/kafka-apps
kafkauser.kafka.strimzi.io/my-user

You can combine this strimzi command with other commands. For example, you can pass it into a kubectl delete command to delete all resources in a single command.

kubectl delete $(kubectl get strimzi -o name)

kafka.kafka.strimzi.io "my-cluster" deleted
kafkatopic.kafka.strimzi.io "kafka-apps" deleted
kafkauser.kafka.strimzi.io "my-user" deleted

Deleting all resources in a single operation might be useful, for example, when you are testing new Strimzi features.

Querying the status of sub-resources

There are other values you can pass to the -o option. For example, by using -o yaml you get the output in YAML format. Using -o json will return it as JSON.

You can see all the options in kubectl get --help.

One of the most useful options is the JSONPath support, which allows you to pass JSONPath expressions to query the Kubernetes API. A JSONPath expression can extract or navigate specific parts of any resource.

For example, you can use the JSONPath expression {.status.listeners[?(@.name=="tls")].bootstrapServers} to get the bootstrap address from the status of the Kafka custom resource and use it in your Kafka clients.

Here, the command finds the bootstrapServers value of the listener named tls:

kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="tls")].bootstrapServers}{"\n"}'

my-cluster-kafka-bootstrap.myproject.svc:9093

By changing the name condition you can also get the address of the other Kafka listeners.

You can use jsonpath to extract any other property or group of properties from any custom resource.

8.1.2. Strimzi custom resource status information

Status properties provide status information for certain custom resources.

The following table lists the custom resources that provide status information (when deployed) and the schemas that define the status properties.

Table 29. Custom resources that provide status information
Strimzi resource Schema reference Publishes status information on…​

Kafka

KafkaStatus schema reference

The Kafka cluster

KafkaTopic

KafkaTopicStatus schema reference

Kafka topics in the Kafka cluster

KafkaUser

KafkaUserStatus schema reference

Kafka users in the Kafka cluster

KafkaConnect

KafkaConnectStatus schema reference

The Kafka Connect cluster

KafkaConnector

KafkaConnectorStatus schema reference

KafkaConnector resources

KafkaMirrorMaker2

KafkaMirrorMaker2Status schema reference

The Kafka MirrorMaker 2.0 cluster

KafkaMirrorMaker

KafkaMirrorMakerStatus schema reference

The Kafka MirrorMaker cluster

KafkaBridge

KafkaBridgeStatus schema reference

The Strimzi Kafka Bridge

KafkaRebalance

KafkaRebalance schema reference

The status and results of a rebalance

The status property of a resource provides information on the state of the resource. The status.conditions and status.observedGeneration properties are common to all resources.

status.conditions

Status conditions describe the current state of a resource. Status condition properties are useful for tracking progress related to the resource achieving its desired state, as defined by the configuration specified in its spec. Status condition properties provide the time and reason the state of the resource changed, and details of events preventing or delaying the operator from realizing the desired state.

status.observedGeneration

Last observed generation denotes the latest reconciliation of the resource by the Cluster Operator. If the value of observedGeneration is different from the value of metadata.generation ((the current version of the deployment), the operator has not yet processed the latest update to the resource. If these values are the same, the status information reflects the most recent changes to the resource.

The status properties also provide resource-specific information. For example, KafkaStatus provides information on listener addresses, and the ID of the Kafka cluster.

Strimzi creates and maintains the status of custom resources, periodically evaluating the current state of the custom resource and updating its status accordingly. When performing an update on a custom resource using kubectl edit, for example, its status is not editable. Moreover, changing the status would not affect the configuration of the Kafka cluster.

Here we see the status properties for a Kafka custom resource.

Kafka custom resource status
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
spec:
  # ...
status:
  clusterId: XP9FP2P-RByvEy0W4cOEUA # (1)
  conditions: # (2)
    - lastTransitionTime: '2023-01-20T17:56:29.396588Z'
      status: 'True'
      type: Ready # (3)
  listeners: # (4)
    - addresses:
        - host: my-cluster-kafka-bootstrap.prm-project.svc
          port: 9092
      bootstrapServers: 'my-cluster-kafka-bootstrap.prm-project.svc:9092'
      name: plain
      type: plain
    - addresses:
        - host: my-cluster-kafka-bootstrap.prm-project.svc
          port: 9093
      bootstrapServers: 'my-cluster-kafka-bootstrap.prm-project.svc:9093'
      certificates:
        - |
          -----BEGIN CERTIFICATE-----

          -----END CERTIFICATE-----
      name: tls
      type: tls
    - addresses:
        - host: >-
            2054284155.us-east-2.elb.amazonaws.com
          port: 9095
      bootstrapServers: >-
        2054284155.us-east-2.elb.amazonaws.com:9095
      certificates:
        - |
          -----BEGIN CERTIFICATE-----

          -----END CERTIFICATE-----
      name: external2
      type: external2
    - addresses:
        - host: ip-10-0-172-202.us-east-2.compute.internal
          port: 31644
      bootstrapServers: 'ip-10-0-172-202.us-east-2.compute.internal:31644'
      certificates:
        - |
          -----BEGIN CERTIFICATE-----

          -----END CERTIFICATE-----
      name: external1
      type: external1
  observedGeneration: 3 # (5)
  1. The Kafka cluster ID.

  2. Status conditions describe the current state of the Kafka cluster.

  3. The Ready condition indicates that the Cluster Operator considers the Kafka cluster able to handle traffic.

  4. The listeners describe Kafka bootstrap addresses by type.

  5. The observedGeneration value indicates the last reconciliation of the Kafka custom resource by the Cluster Operator.

Note
The Kafka bootstrap addresses listed in the status do not signify that those endpoints or the Kafka cluster is in a Ready state.
Accessing status information

You can access status information for a resource from the command line. For more information, see Finding the status of a custom resource.

8.1.3. Finding the status of a custom resource

This procedure describes how to find the status of a custom resource.

Prerequisites
  • A Kubernetes cluster.

  • The Cluster Operator is running.

Procedure
  • Specify the custom resource and use the -o jsonpath option to apply a standard JSONPath expression to select the status property:

    kubectl get kafka <kafka_resource_name> -o jsonpath='{.status}'

    This expression returns all the status information for the specified custom resource. You can use dot notation, such as status.listeners or status.observedGeneration, to fine-tune the status information you wish to see.

Additional resources

8.2. Pausing reconciliation of custom resources

Sometimes it is useful to pause the reconciliation of custom resources managed by Strimzi Operators, so that you can perform fixes or make updates. If reconciliations are paused, any changes made to custom resources are ignored by the Operators until the pause ends.

If you want to pause reconciliation of a custom resource, set the strimzi.io/pause-reconciliation annotation to true in its configuration. This instructs the appropriate Operator to pause reconciliation of the custom resource. For example, you can apply the annotation to the KafkaConnect resource so that reconciliation by the Cluster Operator is paused.

You can also create a custom resource with the pause annotation enabled. The custom resource is created, but it is ignored.

Prerequisites
  • The Strimzi Operator that manages the custom resource is running.

Procedure
  1. Annotate the custom resource in Kubernetes, setting pause-reconciliation to true:

    kubectl annotate <kind_of_custom_resource> <name_of_custom_resource> strimzi.io/pause-reconciliation="true"

    For example, for the KafkaConnect custom resource:

    kubectl annotate KafkaConnect my-connect strimzi.io/pause-reconciliation="true"
  2. Check that the status conditions of the custom resource show a change to ReconciliationPaused:

    kubectl describe <kind_of_custom_resource> <name_of_custom_resource>

    The type condition changes to ReconciliationPaused at the lastTransitionTime.

    Example custom resource with a paused reconciliation condition type
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaConnect
    metadata:
      annotations:
        strimzi.io/pause-reconciliation: "true"
        strimzi.io/use-connector-resources: "true"
      creationTimestamp: 2021-03-12T10:47:11Z
      #...
    spec:
      # ...
    status:
      conditions:
      - lastTransitionTime: 2021-03-12T10:47:41.689249Z
        status: "True"
        type: ReconciliationPaused
Resuming from pause
  • To resume reconciliation, you can set the annotation to false, or remove the annotation.

8.3. Evicting pods with the Strimzi Drain Cleaner

Kafka and ZooKeeper pods might be evicted during Kubernetes upgrades, maintenance, or pod rescheduling. If your Kafka broker and ZooKeeper pods were deployed by Strimzi, you can use the Strimzi Drain Cleaner tool to handle the pod evictions. The Strimzi Drain Cleaner handles the eviction instead of Kubernetes. You must set the podDisruptionBudget for your Kafka deployment to 0 (zero). Kubernetes will then no longer be allowed to evict the pod automatically.

By deploying the Strimzi Drain Cleaner, you can use the Cluster Operator to move Kafka pods instead of Kubernetes. The Cluster Operator ensures that topics are never under-replicated. Kafka can remain operational during the eviction process. The Cluster Operator waits for topics to synchronize, as the Kubernetes worker nodes drain consecutively.

An admission webhook notifies the Strimzi Drain Cleaner of pod eviction requests to the Kubernetes API. The Strimzi Drain Cleaner then adds a rolling update annotation to the pods to be drained. This informs the Cluster Operator to perform a rolling update of an evicted pod.

Note
If you are not using the Strimzi Drain Cleaner, you can add pod annotations to perform rolling updates manually.
Webhook configuration

The Strimzi Drain Cleaner deployment files include a ValidatingWebhookConfiguration resource file. The resource provides the configuration for registering the webhook with the Kubernetes API.

The configuration defines the rules for the Kubernetes API to follow in the event of a pod eviction request. The rules specify that only CREATE operations related to pods/eviction sub-resources are intercepted. If these rules are met, the API forwards the notification.

The clientConfig points to the Strimzi Drain Cleaner service and /drainer endpoint that exposes the webhook. The webhook uses a secure TLS connection, which requires authentication. The caBundle property specifies the certificate chain to validate HTTPS communication. Certificates are encoded in Base64.

Webhook configuration for pod eviction notifications
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
# ...
webhooks:
  - name: strimzi-drain-cleaner.strimzi.io
    rules:
      - apiGroups:   [""]
        apiVersions: ["v1"]
        operations:  ["CREATE"]
        resources:   ["pods/eviction"]
        scope:       "Namespaced"
    clientConfig:
      service:
        namespace: "strimzi-drain-cleaner"
        name: "strimzi-drain-cleaner"
        path: /drainer
        port: 443
        caBundle: Cg==
    # ...

8.3.1. Downloading the Strimzi Drain Cleaner deployment files

To deploy and use the Strimzi Drain Cleaner, you need to download the deployment files.

The Strimzi Drain Cleaner deployment files are available from the GitHub releases page.

8.3.2. Deploying the Strimzi Drain Cleaner using installation files

Deploy the Strimzi Drain Cleaner to the Kubernetes cluster where the Cluster Operator and Kafka cluster are running.

Prerequisites
  • You have downloaded the Strimzi Drain Cleaner deployment files.

  • You have a highly available Kafka cluster deployment running with Kubernetes worker nodes that you would like to update.

  • Topics are replicated for high availability.

    Topic configuration specifies a replication factor of at least 3 and a minimum number of in-sync replicas to 1 less than the replication factor.

    Kafka topic replicated for high availability
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaTopic
    metadata:
      name: my-topic
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      partitions: 1
      replicas: 3
      config:
        # ...
        min.insync.replicas: 2
        # ...
Excluding Kafka or ZooKeeper

If you don’t want to include Kafka or ZooKeeper pods in Drain Cleaner operations, change the default environment variables in the Drain Cleaner Deployment configuration file.

  • Set STRIMZI_DRAIN_KAFKA to false to exclude Kafka pods

  • Set STRIMZI_DRAIN_ZOOKEEPER to false to exclude ZooKeeper pods

Example configuration to exclude ZooKeeper pods
apiVersion: apps/v1
kind: Deployment
spec:
  # ...
  template:
    spec:
      serviceAccountName: strimzi-drain-cleaner
      containers:
        - name: strimzi-drain-cleaner
          # ...
          env:
            - name: STRIMZI_DRAIN_KAFKA
              value: "true"
            - name: STRIMZI_DRAIN_ZOOKEEPER
              value: "false"
          # ...
Procedure
  1. Configure a pod disruption budget of 0 (zero) for your Kafka deployment using template settings in the Kafka resource.

    Specifying a pod disruption budget
    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
      namespace: myproject
    spec:
      kafka:
        template:
          podDisruptionBudget:
            maxUnavailable: 0
    
      # ...
      zookeeper:
        template:
          podDisruptionBudget:
            maxUnavailable: 0
      # ...

    Reducing the maximum pod disruption budget to zero prevents Kubernetes from automatically evicting the pods in case of voluntary disruptions, leaving the Strimzi Drain Cleaner and Strimzi Cluster Operator to roll the pod which will be scheduled by Kubernetes on a different worker node.

    Add the same configuration for ZooKeeper if you want to use Strimzi Drain Cleaner to drain ZooKeeper nodes.

  2. Update the Kafka resource:

    kubectl apply -f <kafka_configuration_file>
  3. Deploy the Strimzi Drain Cleaner.

    • If you are using cert-manager with Kubernetes, apply the resources in the /install/drain-cleaner/certmanager directory.

      kubectl apply -f ./install/drain-cleaner/certmanager

      The TLS certificates for the webhook are generated automatically and injected into the webhook configuration.

    • If you are not using cert-manager with Kubernetes, do the following:

      1. Add TLS certificates to use in the deployment.

        Any certificates you add must be renewed before they expire.

      2. Apply the resources in the /install/drain-cleaner/kubernetes directory.

        kubectl apply -f ./install/drain-cleaner/kubernetes
    • To run the Drain Cleaner on OpenShift, apply the resources in the /install/drain-cleaner/openshift directory.

      kubectl apply -f ./install/drain-cleaner/openshift

8.3.3. Deploying the Strimzi Drain Cleaner using Helm

Helm charts are used to package, configure, and deploy Kubernetes resources. Strimzi provides a Helm chart to deploy the Strimzi Drain Cleaner.

The Drain Cleaner is deployed on the Kubernetes cluster with the default chart configuration, which assumes that cert-manager issues the TLS certificates required by the Drain Cleaner.

You can install the Drain Cleaner with cert-manager support or provide your own TLS certificates.

Prerequisites
Default configuration values

Default configuration values are passed into the chart using parameters defined in a values.yaml file. If you don’t want to use the default configuration, you can override the defaults when you install the chart using the --set argument. You specify values in the format --set key=value[,key=value]. The values.yaml file supplied with the Helm deployment files describes the available configuration parameters, including those shown in the following table.

You can override the default image settings. You can also set secret.create as true and add your own TLS certificates instead of using cert-manager to generate the certificates. For information on using OpenSSL to generate certificates, see Adding or renewing the TLS certificates used by the Strimzi Drain Cleaner.

Any certificates you add must be renewed before they expire. You can use the configuration to control how certificates are watched for updates using environment variables. For more information on how the environment variables work, see Watching the TLS certificates used by the Strimzi Drain Cleaner.

Table 30. Chart configuration options
Parameter Description Default

replicaCount

Number of replicas of the Drain Cleaner webhook

1

image.registry

Drain Cleaner image registry

quay.io

image.repository

Drain Cleaner image repository

strimzi

image.name

Drain Cleaner image name

drain-cleaner

image.tag

Drain Cleaner image tag

latest

image.imagePullPolicy

Image pull policy for all pods deployed by the Drain Cleaner

nil

secret.create

Set to true and add certificates when not using cert-manager

false

namespace.name

Default namespace for the Drain Cleaner deployment.

strimzi-drain-cleaner

resources

Configures resources for the Drain Cleaner pod

[]

nodeSelector

Add a node selector to the Drain Cleaner pod

{}

tolerations

Add tolerations to the Drain Cleaner pod

[]

topologySpreadConstraints

Add topology spread constraints to the Drain Cleaner pod

{}

affinity

Add affinities to the Drain Cleaner pod

{}

Procedure
  1. Use the Helm command line tool to add the Strimzi Helm chart repository:

    helm repo add strimzi https://strimzi.io/charts/
  2. Deploy the Drain Cleaner:

    helm install drain-cleaner strimzi/strimzi-drain-cleaner

    Specify any changes to the default configuration as parameter values.

    Example configuration that changes the number of webhook replicas
    helm install drain-cleaner --set replicaCount=2 strimzi/strimzi-drain-cleaner
  3. Verify that the Cluster Operator has been deployed successfully:

    helm ls

8.3.4. Using the Strimzi Drain Cleaner

Use the Strimzi Drain Cleaner in combination with the Cluster Operator to move Kafka broker or ZooKeeper pods from nodes that are being drained. When you run the Strimzi Drain Cleaner, it annotates pods with a rolling update pod annotation. The Cluster Operator performs rolling updates based on the annotation.

Prerequisites
Procedure
  1. Drain a specified Kubernetes node hosting the Kafka broker or ZooKeeper pods.

    kubectl get nodes
    kubectl drain <name-of-node> --delete-emptydir-data --ignore-daemonsets --timeout=6000s --force
  2. Check the eviction events in the Strimzi Drain Cleaner log to verify that the pods have been annotated for restart.

    Strimzi Drain Cleaner log show annotations of pods
    INFO ... Received eviction webhook for Pod my-cluster-zookeeper-2 in namespace my-project
    INFO ... Pod my-cluster-zookeeper-2 in namespace my-project will be annotated for restart
    INFO ... Pod my-cluster-zookeeper-2 in namespace my-project found and annotated for restart
    
    INFO ... Received eviction webhook for Pod my-cluster-kafka-0 in namespace my-project
    INFO ... Pod my-cluster-kafka-0 in namespace my-project will be annotated for restart
    INFO ... Pod my-cluster-kafka-0 in namespace my-project found and annotated for restart
  3. Check the reconciliation events in the Cluster Operator log to verify the rolling updates.

    Cluster Operator log shows rolling updates
    INFO  PodOperator:68 - Reconciliation #13(timer) Kafka(my-project/my-cluster): Rolling Pod my-cluster-zookeeper-2
    INFO  PodOperator:68 - Reconciliation #13(timer) Kafka(my-project/my-cluster): Rolling Pod my-cluster-kafka-0
    INFO  AbstractOperator:500 - Reconciliation #13(timer) Kafka(my-project/my-cluster): reconciled

8.3.5. Adding or renewing the TLS certificates used by the Strimzi Drain Cleaner

The Drain Cleaner uses a webhook to receive eviction notifications from the Kubernetes API. The webhook uses a secure TLS connection and authenticates using TLS certificates. If you are not deploying the Drain Cleaner using the cert-manager or on Openshift, you must create and renew the TLS certificates. You must then add them to the files used to deploy the Drain Cleaner. The certificates must also be renewed before they expire. To renew the certificates, you repeat the steps used to generate and add the certificates to the initial deployment of the Drain Cleaner.

Generate and add certificates to the standard installation files or your Helm configuration when deploying the Drain Cleaner on Kubernetes without cert-manager.

Note
If you are using cert-manager to deploy the Drain Cleaner, you don’t need to add or renew TLS certificates. The same applies when deploying the Drain Cleaner on OpenShift, as OpenShift injects the certificates. In both cases, TLS certificates are added and renewed automatically.
Prerequisites
  • The OpenSSL TLS management tool for generating certificates.

    Use openssl help for command-line descriptions of the options used.

Generating and renewing TLS certificates
  1. From the command line, create a directory called tls-certificate:

    mkdir tls-certificate
    cd tls-certificate

    Now use OpenSSL to create the certificates in the tls-certificate directory.

  2. Generate a CA (Certificate Authority) public certificate and private key:

    openssl req -nodes -new -x509 -keyout ca.key -out ca.crt -subj "/CN=Strimzi Drain Cleaner CA"

    A ca.crt and ca.key file are created.

  3. Generate a private key for the Drain Cleaner:

    openssl genrsa -out tls.key 2048

    A tls.key file is created.

  4. Generate a CSR (Certificate Signing Request) and sign it by adding the CA public certificate (ca.crt) you generated:

    openssl req -new -key tls.key -subj "/CN=strimzi-drain-cleaner.strimzi-drain-cleaner.svc" \
      | openssl x509 -req -CA ca.crt -CAkey ca.key -CAcreateserial -extfile <(printf "subjectAltName=DNS:strimzi-drain-cleaner.strimzi-drain-cleaner.svc") -out tls.crt

    A tls.crt file is created.

    Note
    If you change the name of the Strimzi Drain Cleaner service or install it into a different namespace, you must change the SAN (Subject Alternative Name) of the certificate, following the format <service_name>.<namespace_name>.svc.
  5. Encode the CA public certificate into base64.

    base64 tls-certificate/ca.crt

    With the certificates generated, add them to the installation files or to your Helm configuration depending on your deployment method.

Adding the TLS certificates to the Drain Cleaner installation files
  1. Copy the base64-encoded CA public certificate as the value for the caBundle property of the 070-ValidatingWebhookConfiguration.yaml installation file:

    # ...
    clientConfig:
      service:
        namespace: "strimzi-drain-cleaner"
        name: "strimzi-drain-cleaner"
        path: /drainer
        port: 443
      caBundle: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0...
    # ...
  2. Create a namespace called strimzi-drain-cleaner in your Kubernetes cluster:

    kubectl create ns strimzi-drain-cleaner
  3. Create a secret named strimzi-drain-cleaner with the tls.crt and tls.key files you generated:

    kubectl create secret tls strimzi-drain-cleaner \
      -n strimzi-drain-cleaner  \
      --cert=tls-certificate/tls.crt \
      --key=tls-certificate/tls.key

    The secret is used in the Drain Cleaner deployment.

    Example secret for the Drain Cleaner deployment
    apiVersion: v1
    kind: Secret
    metadata:
      # ...
      name: strimzi-drain-cleaner
      namespace: strimzi-drain-cleaner
    # ...
    data:
      tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS...
      tls.key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLR...

    You can now use the certificates and updated installation files to deploy the Drain Cleaner using installation files.

Adding the TLS certificates to a Helm deployment
  1. Edit the values.yaml configuration file used in the Helm deployment.

  2. Set the certManager.create parameter to false.

  3. Set the secret.create parameter to true.

  4. Copy the certificates as secret parameters.

    Example secret configuration for the Drain Cleaner deployment
    # ...
    certManager:
      create: false
    
    secret:
      create: true
      tls_crt: "Cg==" # (1)
      tls_key: "Cg==" # (2)
      ca_bundle: "Cg==" # (3)
    1. The public key (tls.crt) signed by the CA public certificate.

    2. The private key (tls.key).

    3. The base-64 encoded CA public certificate (ca.crt).

You can now use the certificates and updated configuration file to deploy the Drain Cleaner using Helm.

8.3.6. Watching the TLS certificates used by the Strimzi Drain Cleaner

By default, the Drain Cleaner deployment watches the secret containing the TLS certificates its uses for authentication. The Drain Cleaner watches for changes, such as certificate renewals. If it detects a change, it restarts to reload the TLS certificates. The Drain Cleaner installation files enable this behavior by default. But you can disable the watching of certificates by setting the STRIMZI_CERTIFICATE_WATCH_ENABLED environment variable to false in the Deployment configuration (060-Deployment.yaml) of the Drain Cleaner installation files.

With STRIMZI_CERTIFICATE_WATCH_ENABLED enabled, you can also use the following environment variables for watching TLS certificates.

Table 31. Drain Cleaner environment variables for watching TLS certificates
Environment Variable Description Default

STRIMZI_CERTIFICATE_WATCH_ENABLED

Enables or disables the certificate watch

false

STRIMZI_CERTIFICATE_WATCH_NAMESPACE

The namespace where the Drain Cleaner is deployed and where the certificate secret exists

strimzi-drain-cleaner

STRIMZI_CERTIFICATE_WATCH_POD_NAME

The Drain Cleaner pod name

-

STRIMZI_CERTIFICATE_WATCH_SECRET_NAME

The name of the secret containing TLS certificates

strimzi-drain-cleaner

STRIMZI_CERTIFICATE_WATCH_SECRET_KEYS

The list of fields inside the secret that contain the TLS certificates

tls.crt, tls.key

Example environment variable configuration to control watch operations
apiVersion: apps/v1
kind: Deployment
metadata:
  name: strimzi-drain-cleaner
  labels:
    app: strimzi-drain-cleaner
  namespace: strimzi-drain-cleaner
spec:
  # ...
    spec:
      serviceAccountName: strimzi-drain-cleaner
      containers:
        - name: strimzi-drain-cleaner
          # ...
          env:
            - name: STRIMZI_DRAIN_KAFKA
              value: "true"
            - name: STRIMZI_DRAIN_ZOOKEEPER
              value: "true"
            - name: STRIMZI_CERTIFICATE_WATCH_ENABLED
              value: "true"
            - name: STRIMZI_CERTIFICATE_WATCH_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: STRIMZI_CERTIFICATE_WATCH_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
              # ...
Tip
Use the Downward API mechanism to configure STRIMZI_CERTIFICATE_WATCH_NAMESPACE and STRIMZI_CERTIFICATE_WATCH_POD_NAME.

8.4. Manually starting rolling updates of Kafka and ZooKeeper clusters

Strimzi supports the use of annotations on resources to manually trigger a rolling update of Kafka and ZooKeeper clusters through the Cluster Operator. Rolling updates restart the pods of the resource with new ones.

Manually performing a rolling update on a specific pod or set of pods is usually only required in exceptional circumstances. However, rather than deleting the pods directly, if you perform the rolling update through the Cluster Operator you ensure the following:

  • The manual deletion of the pod does not conflict with simultaneous Cluster Operator operations, such as deleting other pods in parallel.

  • The Cluster Operator logic handles the Kafka configuration specifications, such as the number of in-sync replicas.

8.4.1. Prerequisites

To perform a manual rolling update, you need a running Cluster Operator and Kafka cluster.

See the Deploying and Upgrading Strimzi guide for instructions on running a:

8.4.2. Performing a rolling update using a pod management annotation

This procedure describes how to trigger a rolling update of a Kafka cluster or ZooKeeper cluster.

To trigger the update, you add an annotation to the resource you are using to manage the pods running on the cluster. You annotate the StatefulSet or StrimziPodSet resource (if you enabled the UseStrimziPodSets feature gate).

Procedure
  1. Find the name of the resource that controls the Kafka or ZooKeeper pods you want to manually update.

    For example, if your Kafka cluster is named my-cluster, the corresponding names are my-cluster-kafka and my-cluster-zookeeper.

  2. Use kubectl annotate to annotate the appropriate resource in Kubernetes.

    Annotating a StatefulSet
    kubectl annotate statefulset <cluster_name>-kafka strimzi.io/manual-rolling-update=true
    
    kubectl annotate statefulset <cluster_name>-zookeeper strimzi.io/manual-rolling-update=true
    Annotating a StrimziPodSet
    kubectl annotate strimzipodset <cluster_name>-kafka strimzi.io/manual-rolling-update=true
    
    kubectl annotate strimzipodset <cluster_name>-zookeeper strimzi.io/manual-rolling-update=true
  3. Wait for the next reconciliation to occur (every two minutes by default). A rolling update of all pods within the annotated resource is triggered, as long as the annotation was detected by the reconciliation process. When the rolling update of all the pods is complete, the annotation is removed from the resource.

8.4.3. Performing a rolling update using a Pod annotation

This procedure describes how to manually trigger a rolling update of an existing Kafka cluster or ZooKeeper cluster using a Kubernetes Pod annotation. When multiple pods are annotated, consecutive rolling updates are performed within the same reconciliation run.

Prerequisites

You can perform a rolling update on a Kafka cluster regardless of the topic replication factor used. But for Kafka to stay operational during the update, you’ll need the following:

  • A highly available Kafka cluster deployment running with nodes that you wish to update.

  • Topics replicated for high availability.

    Topic configuration specifies a replication factor of at least 3 and a minimum number of in-sync replicas to 1 less than the replication factor.

    Kafka topic replicated for high availability
    apiVersion: kafka.strimzi.io/v1beta2
    kind: KafkaTopic
    metadata:
      name: my-topic
      labels:
        strimzi.io/cluster: my-cluster
    spec:
      partitions: 1
      replicas: 3
      config:
        # ...
        min.insync.replicas: 2
        # ...
Procedure
  1. Find the name of the Kafka or ZooKeeper Pod you want to manually update.

    For example, if your Kafka cluster is named my-cluster, the corresponding Pod names are my-cluster-kafka-index and my-cluster-zookeeper-index. The index starts at zero and ends at the total number of replicas minus one.

  2. Annotate the Pod resource in Kubernetes.

    Use kubectl annotate:

    kubectl annotate pod cluster-name-kafka-index strimzi.io/manual-rolling-update=true
    
    kubectl annotate pod cluster-name-zookeeper-index strimzi.io/manual-rolling-update=true
  3. Wait for the next reconciliation to occur (every two minutes by default). A rolling update of the annotated Pod is triggered, as long as the annotation was detected by the reconciliation process. When the rolling update of a pod is complete, the annotation is removed from the Pod.

8.5. Discovering services using labels and annotations

Service discovery makes it easier for client applications running in the same Kubernetes cluster as Strimzi to interact with a Kafka cluster.

A service discovery label and annotation is generated for services used to access the Kafka cluster:

  • Internal Kafka bootstrap service

  • HTTP Bridge service

The label helps to make the service discoverable, and the annotation provides connection details that a client application can use to make the connection.

The service discovery label, strimzi.io/discovery, is set as true for the Service resources. The service discovery annotation has the same key, providing connection details in JSON format for each service.

Example internal Kafka bootstrap service

apiVersion: v1
kind: Service
metadata:
  annotations:
    strimzi.io/discovery: |-
      [ {
        "port" : 9092,
        "tls" : false,
        "protocol" : "kafka",
        "auth" : "scram-sha-512"
      }, {
        "port" : 9093,
        "tls" : true,
        "protocol" : "kafka",
        "auth" : "tls"
      } ]
  labels:
    strimzi.io/cluster: my-cluster
    strimzi.io/discovery: "true"
    strimzi.io/kind: Kafka
    strimzi.io/name: my-cluster-kafka-bootstrap
  name: my-cluster-kafka-bootstrap
spec:
  #...

Example HTTP Bridge service

apiVersion: v1
kind: Service
metadata:
  annotations:
    strimzi.io/discovery: |-
      [ {
        "port" : 8080,
        "tls" : false,
        "auth" : "none",
        "protocol" : "http"
      } ]
  labels:
    strimzi.io/cluster: my-bridge
    strimzi.io/discovery: "true"
    strimzi.io/kind: KafkaBridge
    strimzi.io/name: my-bridge-bridge-service

8.5.1. Returning connection details on services

You can find the services by specifying the discovery label when fetching services from the command line or a corresponding API call.

kubectl get service -l strimzi.io/discovery=true

The connection details are returned when retrieving the service discovery label.

8.6. Recovering a cluster from persistent volumes

You can recover a Kafka cluster from persistent volumes (PVs) if they are still present.

You might want to do this, for example, after:

  • A namespace was deleted unintentionally

  • A whole Kubernetes cluster is lost, but the PVs remain in the infrastructure

8.6.1. Recovery from namespace deletion

Recovery from namespace deletion is possible because of the relationship between persistent volumes and namespaces. A PersistentVolume (PV) is a storage resource that lives outside of a namespace. A PV is mounted into a Kafka pod using a PersistentVolumeClaim (PVC), which lives inside a namespace.

The reclaim policy for a PV tells a cluster how to act when a namespace is deleted. If the reclaim policy is set as:

  • Delete (default), PVs are deleted when PVCs are deleted within a namespace

  • Retain, PVs are not deleted when a namespace is deleted

To ensure that you can recover from a PV if a namespace is deleted unintentionally, the policy must be reset from Delete to Retain in the PV specification using the persistentVolumeReclaimPolicy property:

apiVersion: v1
kind: PersistentVolume
# ...
spec:
  # ...
  persistentVolumeReclaimPolicy: Retain

Alternatively, PVs can inherit the reclaim policy of an associated storage class. Storage classes are used for dynamic volume allocation.

By configuring the reclaimPolicy property for the storage class, PVs that use the storage class are created with the appropriate reclaim policy. The storage class is configured for the PV using the storageClassName property.

apiVersion: v1
kind: StorageClass
metadata:
  name: gp2-retain
parameters:
  # ...
# ...
reclaimPolicy: Retain
apiVersion: v1
kind: PersistentVolume
# ...
spec:
  # ...
  storageClassName: gp2-retain
Note
If you are using Retain as the reclaim policy, but you want to delete an entire cluster, you need to delete the PVs manually. Otherwise they will not be deleted, and may cause unnecessary expenditure on resources.

8.6.2. Recovery from loss of a Kubernetes cluster

When a cluster is lost, you can use the data from disks/volumes to recover the cluster if they were preserved within the infrastructure. The recovery procedure is the same as with namespace deletion, assuming PVs can be recovered and they were created manually.

8.6.3. Recovering a deleted cluster from persistent volumes

This procedure describes how to recover a deleted cluster from persistent volumes (PVs).

In this situation, the Topic Operator identifies that topics exist in Kafka, but the KafkaTopic resources do not exist.

When you get to the step to recreate your cluster, you have two options:

  1. Use Option 1 when you can recover all KafkaTopic resources.

    The KafkaTopic resources must therefore be recovered before the cluster is started so that the corresponding topics are not deleted by the Topic Operator.

  2. Use Option 2 when you are unable to recover all KafkaTopic resources.

    In this case, you deploy your cluster without the Topic Operator, delete the Topic Operator topic store metadata, and then redeploy the Kafka cluster with the Topic Operator so it can recreate the KafkaTopic resources from the corresponding topics.

Note
If the Topic Operator is not deployed, you only need to recover the PersistentVolumeClaim (PVC) resources.
Before you begin

In this procedure, it is essential that PVs are mounted into the correct PVC to avoid data corruption. A volumeName is specified for the PVC and this must match the name of the PV.

For more information, see:

Note
The procedure does not include recovery of KafkaUser resources, which must be recreated manually. If passwords and certificates need to be retained, secrets must be recreated before creating the KafkaUser resources.
Procedure
  1. Check information on the PVs in the cluster:

    kubectl get pv

    Information is presented for PVs with data.

    Example output showing columns important to this procedure:

    NAME                                         RECLAIMPOLICY CLAIM
    pvc-5e9c5c7f-3317-11ea-a650-06e1eadd9a4c ... Retain ...    myproject/data-my-cluster-zookeeper-1
    pvc-5e9cc72d-3317-11ea-97b0-0aef8816c7ea ... Retain ...    myproject/data-my-cluster-zookeeper-0
    pvc-5ead43d1-3317-11ea-97b0-0aef8816c7ea ... Retain ...    myproject/data-my-cluster-zookeeper-2
    pvc-7e1f67f9-3317-11ea-a650-06e1eadd9a4c ... Retain ...    myproject/data-0-my-cluster-kafka-0
    pvc-7e21042e-3317-11ea-9786-02deaf9aa87e ... Retain ...    myproject/data-0-my-cluster-kafka-1
    pvc-7e226978-3317-11ea-97b0-0aef8816c7ea ... Retain ...    myproject/data-0-my-cluster-kafka-2
    • NAME shows the name of each PV.

    • RECLAIM POLICY shows that PVs are retained.

    • CLAIM shows the link to the original PVCs.

  2. Recreate the original namespace:

    kubectl create namespace myproject
  3. Recreate the original PVC resource specifications, linking the PVCs to the appropriate PV:

    For example:

    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      name: data-0-my-cluster-kafka-0
    spec:
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 100Gi
      storageClassName: gp2-retain
      volumeMode: Filesystem
      volumeName: pvc-7e1f67f9-3317-11ea-a650-06e1eadd9a4c
  4. Edit the PV specifications to delete the claimRef properties that bound the original PVC.

    For example:

    apiVersion: v1
    kind: PersistentVolume
    metadata:
      annotations:
        kubernetes.io/createdby: aws-ebs-dynamic-provisioner
        pv.kubernetes.io/bound-by-controller: "yes"
        pv.kubernetes.io/provisioned-by: kubernetes.io/aws-ebs
      creationTimestamp: "<date>"
      finalizers:
      - kubernetes.io/pv-protection
      labels:
        failure-domain.beta.kubernetes.io/region: eu-west-1
        failure-domain.beta.kubernetes.io/zone: eu-west-1c
      name: pvc-7e226978-3317-11ea-97b0-0aef8816c7ea
      resourceVersion: "39431"
      selfLink: /api/v1/persistentvolumes/pvc-7e226978-3317-11ea-97b0-0aef8816c7ea
      uid: 7efe6b0d-3317-11ea-a650-06e1eadd9a4c
    spec:
      accessModes:
      - ReadWriteOnce
      awsElasticBlockStore:
        fsType: xfs
        volumeID: aws://eu-west-1c/vol-09db3141656d1c258
      capacity:
        storage: 100Gi
      claimRef:
        apiVersion: v1
        kind: PersistentVolumeClaim
        name: data-0-my-cluster-kafka-2
        namespace: myproject
        resourceVersion: "39113"
        uid: 54be1c60-3319-11ea-97b0-0aef8816c7ea
      nodeAffinity:
        required:
          nodeSelectorTerms:
          - matchExpressions:
            - key: failure-domain.beta.kubernetes.io/zone
              operator: In
              values:
              - eu-west-1c
            - key: failure-domain.beta.kubernetes.io/region
              operator: In
              values:
              - eu-west-1
      persistentVolumeReclaimPolicy: Retain
      storageClassName: gp2-retain
      volumeMode: Filesystem

    In the example, the following properties are deleted:

    claimRef:
      apiVersion: v1
      kind: PersistentVolumeClaim
      name: data-0-my-cluster-kafka-2
      namespace: myproject
      resourceVersion: "39113"
      uid: 54be1c60-3319-11ea-97b0-0aef8816c7ea
  5. Deploy the Cluster Operator.

    kubectl create -f install/cluster-operator -n my-project
  6. Recreate your cluster.

    Follow the steps depending on whether or not you have all the KafkaTopic resources needed to recreate your cluster.

    Option 1: If you have all the KafkaTopic resources that existed before you lost your cluster, including internal topics such as committed offsets from __consumer_offsets:

    1. Recreate all KafkaTopic resources.

      It is essential that you recreate the resources before deploying the cluster, or the Topic Operator will delete the topics.

    2. Deploy the Kafka cluster.

      For example:

      kubectl apply -f kafka.yaml

    Option 2: If you do not have all the KafkaTopic resources that existed before you lost your cluster:

    1. Deploy the Kafka cluster, as with the first option, but without the Topic Operator by removing the topicOperator property from the Kafka resource before deploying.

      If you include the Topic Operator in the deployment, the Topic Operator will delete all the topics.

    2. Delete the internal topic store topics from the Kafka cluster:

      kubectl run kafka-admin -ti --image=quay.io/strimzi/kafka:latest-kafka-3.3.2 --rm=true --restart=Never -- ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi-topic-operator-kstreams-topic-store-changelog --delete && ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi_store_topic --delete

      The command must correspond to the type of listener and authentication used to access the Kafka cluster.

    3. Enable the Topic Operator by redeploying the Kafka cluster with the topicOperator property to recreate the KafkaTopic resources.

      For example:

      apiVersion: kafka.strimzi.io/v1beta2
      kind: Kafka
      metadata:
        name: my-cluster
      spec:
        #...
        entityOperator:
          topicOperator: {} (1)
          #...
    1. Here we show the default configuration, which has no additional properties. You specify the required configuration using the properties described in EntityTopicOperatorSpec schema reference.

  7. Verify the recovery by listing the KafkaTopic resources:

    kubectl get KafkaTopic

8.7. Setting limits on brokers using the Kafka Static Quota plugin

Use the Kafka Static Quota plugin to set throughput and storage limits on brokers in your Kafka cluster. You enable the plugin and set limits by configuring the Kafka resource. You can set a byte-rate threshold and storage quotas to put limits on the clients interacting with your brokers.

You can set byte-rate thresholds for producer and consumer bandwidth. The total limit is distributed across all clients accessing the broker. For example, you can set a byte-rate threshold of 40 MBps for producers. If two producers are running, they are each limited to a throughput of 20 MBps.

Storage quotas throttle Kafka disk storage limits between a soft limit and hard limit. The limits apply to all available disk space. Producers are slowed gradually between the soft and hard limit. The limits prevent disks filling up too quickly and exceeding their capacity. Full disks can lead to issues that are hard to rectify. The hard limit is the maximum storage limit.

Note
For JBOD storage, the limit applies across all disks. If a broker is using two 1 TB disks and the quota is 1.1 TB, one disk might fill and the other disk will be almost empty.
Prerequisites
  • The Cluster Operator that manages the Kafka cluster is running.

Procedure
  1. Add the plugin properties to the config of the Kafka resource.

    The plugin properties are shown in this example configuration.

    Example Kafka Static Quota plugin configuration
    apiVersion: kafka.strimzi.io/v1beta2
    kind: Kafka
    metadata:
      name: my-cluster
    spec:
      kafka:
        # ...
        config:
          client.quota.callback.class: io.strimzi.kafka.quotas.StaticQuotaCallback (1)
          client.quota.callback.static.produce: 1000000 (2)
          client.quota.callback.static.fetch: 1000000 (3)
          client.quota.callback.static.storage.soft: 400000000000 (4)
          client.quota.callback.static.storage.hard: 500000000000 (5)
          client.quota.callback.static.storage.check-interval: 5 (6)
    1. Loads the Kafka Static Quota plugin.

    2. Sets the producer byte-rate threshold. 1 MBps in this example.

    3. Sets the consumer byte-rate threshold. 1 MBps in this example.

    4. Sets the lower soft limit for storage. 400 GB in this example.

    5. Sets the higher hard limit for storage. 500 GB in this example.

    6. Sets the interval in seconds between checks on storage. 5 seconds in this example. You can set this to 0 to disable the check.

  2. Update the resource.

    kubectl apply -f <kafka_configuration_file>
Additional resources

8.8. Frequently asked questions

Why do I need cluster administrator privileges to install Strimzi?

To install Strimzi, you need to be able to create the following cluster-scoped resources:

  • Custom Resource Definitions (CRDs) to instruct Kubernetes about resources that are specific to Strimzi, such as Kafka and KafkaConnect

  • ClusterRoles and ClusterRoleBindings

Cluster-scoped resources, which are not scoped to a particular Kubernetes namespace, typically require cluster administrator privileges to install.

As a cluster administrator, you can inspect all the resources being installed (in the /install/ directory) to ensure that the ClusterRoles do not grant unnecessary privileges.

After installation, the Cluster Operator runs as a regular Deployment, so any standard (non-admin) Kubernetes user with privileges to access the Deployment can configure it. The cluster administrator can grant standard users the privileges necessary to manage Kafka custom resources.

See also:

Why does the Cluster Operator need to create ClusterRoleBindings?

Kubernetes has built-in privilege escalation prevention, which means that the Cluster Operator cannot grant privileges it does not have itself, specifically, it cannot grant such privileges in a namespace it cannot access. Therefore, the Cluster Operator must have the privileges necessary for all the components it orchestrates.

The Cluster Operator needs to be able to grant access so that:

  • The Topic Operator can manage KafkaTopics, by creating Roles and RoleBindings in the namespace that the operator runs in

  • The User Operator can manage KafkaUsers, by creating Roles and RoleBindings in the namespace that the operator runs in

  • The failure domain of a Node is discovered by Strimzi, by creating a ClusterRoleBinding

When using rack-aware partition assignment, the broker pod needs to be able to get information about the Node it is running on, for example, the Availability Zone in Amazon AWS. A Node is a cluster-scoped resource, so access to it can only be granted through a ClusterRoleBinding, not a namespace-scoped RoleBinding.

Can standard Kubernetes users create Kafka custom resources?

By default, standard Kubernetes users will not have the privileges necessary to manage the custom resources handled by the Cluster Operator. The cluster administrator can grant a user the necessary privileges using Kubernetes RBAC resources.

For more information, see Designating Strimzi administrators in the Deploying and Upgrading Strimzi guide.

What do the failed to acquire lock warnings in the log mean?

For each cluster, the Cluster Operator executes only one operation at a time. The Cluster Operator uses locks to make sure that there are never two parallel operations running for the same cluster. Other operations must wait until the current operation completes before the lock is released.

INFO

Examples of cluster operations include cluster creation, rolling update, scale down , and scale up.

If the waiting time for the lock takes too long, the operation times out and the following warning message is printed to the log:

2018-03-04 17:09:24 WARNING AbstractClusterOperations:290 - Failed to acquire lock for kafka cluster lock::kafka::myproject::my-cluster

Depending on the exact configuration of STRIMZI_FULL_RECONCILIATION_INTERVAL_MS and STRIMZI_OPERATION_TIMEOUT_MS, this warning message might appear occasionally without indicating any underlying issues. Operations that time out are picked up in the next periodic reconciliation, so that the operation can acquire the lock and execute again.

Should this message appear periodically, even in situations when there should be no other operations running for a given cluster, it might indicate that the lock was not properly released due to an error. If this is the case, try restarting the Cluster Operator.

Why is hostname verification failing when connecting to NodePorts using TLS?

Currently, off-cluster access using NodePorts with TLS encryption enabled does not support TLS hostname verification. As a result, the clients that verify the hostname will fail to connect. For example, the Java client will fail with the following exception:

Caused by: java.security.cert.CertificateException: No subject alternative names matching IP address 168.72.15.231 found
 at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:168)
 at sun.security.util.HostnameChecker.match(HostnameChecker.java:94)
 at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:455)
 at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:436)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:252)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136)
 at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1501)
 ... 17 more

To connect, you must disable hostname verification. In the Java client, you can do this by setting the configuration option ssl.endpoint.identification.algorithm to an empty string.

When configuring the client using a properties file, you can do it this way:

ssl.endpoint.identification.algorithm=

When configuring the client directly in Java, set the configuration option to an empty string:

props.put("ssl.endpoint.identification.algorithm", "");

9. Custom resource API reference

9.1. Common configuration properties

Common configuration properties apply to more than one resource.

9.1.1. replicas

Use the replicas property to configure replicas.

The type of replication depends on the resource.

  • KafkaTopic uses a replication factor to configure the number of replicas of each partition within a Kafka cluster.

  • Kafka components use replicas to configure the number of pods in a deployment to provide better availability and scalability.

Note
When running a Kafka component on Kubernetes it may not be necessary to run multiple replicas for high availability. When the node where the component is deployed crashes, Kubernetes will automatically reschedule the Kafka component pod to a different node. However, running Kafka components with multiple replicas can provide faster failover times as the other nodes will be up and running.

9.1.2. bootstrapServers

Use the bootstrapServers property to configure a list of bootstrap servers.

The bootstrap server lists can refer to Kafka clusters that are not deployed in the same Kubernetes cluster. They can also refer to a Kafka cluster not deployed by Strimzi.

If on the same Kubernetes cluster, each list must ideally contain the Kafka cluster bootstrap service which is named CLUSTER-NAME-kafka-bootstrap and a port number. If deployed by Strimzi but on different Kubernetes clusters, the list content depends on the approach used for exposing the clusters (routes, ingress, nodeports or loadbalancers).

When using Kafka with a Kafka cluster not managed by Strimzi, you can specify the bootstrap servers list according to the configuration of the given cluster.

9.1.3. ssl

Use the three allowed ssl configuration options for client connection using a specific cipher suite for a TLS version. A cipher suite combines algorithms for secure connection and data transfer.

You can also configure the ssl.endpoint.identification.algorithm property to enable or disable hostname verification.

Example SSL configuration
# ...
spec:
  config:
    ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" (1)
    ssl.enabled.protocols: "TLSv1.2" (2)
    ssl.protocol: "TLSv1.2" (3)
    ssl.endpoint.identification.algorithm: HTTPS (4)
# ...
  1. The cipher suite for TLS using a combination of ECDHE key exchange mechanism, RSA authentication algorithm, AES bulk encyption algorithm and SHA384 MAC algorithm.

  2. The SSl protocol TLSv1.2 is enabled.

  3. Specifies the TLSv1.2 protocol to generate the SSL context. Allowed values are TLSv1.1 and TLSv1.2.

  4. Hostname verification is enabled by setting to HTTPS. An empty string disables the verification.

9.1.4. trustedCertificates

Having set tls to configure TLS encryption, use the trustedCertificates property to provide a list of secrets with key names under which the certificates are stored in X.509 format.

You can use the secrets created by the Cluster Operator for the Kafka cluster, or you can create your own TLS certificate file, then create a Secret from the file:

kubectl create secret generic MY-SECRET \
--from-file=MY-TLS-CERTIFICATE-FILE.crt
Example TLS encryption configuration
tls:
  trustedCertificates:
    - secretName: my-cluster-cluster-cert
      certificate: ca.crt
    - secretName: my-cluster-cluster-cert
      certificate: ca2.crt

If certificates are stored in the same secret, it can be listed multiple times.

If you want to enable TLS encryption, but use the default set of public certification authorities shipped with Java, you can specify trustedCertificates as an empty array:

Example of enabling TLS with the default Java certificates
tls:
  trustedCertificates: []

For information on configuring mTLS authentication, see the KafkaClientAuthenticationTls schema reference.

9.1.5. resources

Configure resource requests and limits to control resources for Strimzi containers. You can specify requests and limits for memory and cpu resources. The requests should be enough to ensure a stable performance of Kafka.

How you configure resources in a production environment depends on a number of factors. For example, applications are likely to be sharing resources in your Kubernetes cluster.

For Kafka, the following aspects of a deployment can impact the resources you need:

  • Throughput and size of messages

  • The number of network threads handling messages

  • The number of producers and consumers

  • The number of topics and partitions

The values specified for resource requests are reserved and always available to the container. Resource limits specify the maximum resources that can be consumed by a given container. The amount between the request and limit is not reserved and might not be always available. A container can use the resources up to the limit only when they are available. Resource limits are temporary and can be reallocated.

Resource requests and limits

Boundaries of a resource requests and limits

If you set limits without requests or vice versa, Kubernetes uses the same value for both. Setting equal requests and limits for resources guarantees quality of service, as Kubernetes will not kill containers unless they exceed their limits.

You can configure resource requests and limits for one or more supported resources.

Example resource configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    #...
    resources:
      requests:
        memory: 64Gi
        cpu: "8"
      limits:
        memory: 64Gi
        cpu: "12"
  entityOperator:
    #...
    topicOperator:
      #...
      resources:
        requests:
          memory: 512Mi
          cpu: "1"
        limits:
          memory: 512Mi
          cpu: "1"

Resource requests and limits for the Topic Operator and User Operator are set in the Kafka resource.

If the resource request is for more than the available free resources in the Kubernetes cluster, the pod is not scheduled.

Note
Strimzi uses the Kubernetes syntax for specifying memory and cpu resources. For more information about managing computing resources on Kubernetes, see Managing Compute Resources for Containers.
Memory resources

When configuring memory resources, consider the total requirements of the components.

Kafka runs inside a JVM and uses an operating system page cache to store message data before writing to disk. The memory request for Kafka should fit the JVM heap and page cache. You can configure the jvmOptions property to control the minimum and maximum heap size.

Other components don’t rely on the page cache. You can configure memory resources without configuring the jvmOptions to control the heap size.

Memory requests and limits are specified in megabytes, gigabytes, mebibytes, and gibibytes. Use the following suffixes in the specification:

  • M for megabytes

  • G for gigabytes

  • Mi for mebibytes

  • Gi for gibibytes

Example resources using different memory units
# ...
resources:
  requests:
    memory: 512Mi
  limits:
    memory: 2Gi
# ...

For more details about memory specification and additional supported units, see Meaning of memory.

CPU resources

A CPU request should be enough to give a reliable performance at any time. CPU requests and limits are specified as cores or millicpus/millicores.

CPU cores are specified as integers (5 CPU core) or decimals (2.5 CPU core). 1000 millicores is the same as 1 CPU core.

Example CPU units
# ...
resources:
  requests:
    cpu: 500m
  limits:
    cpu: 2.5
# ...

The computing power of 1 CPU core may differ depending on the platform where Kubernetes is deployed.

For more information on CPU specification, see Meaning of CPU.

9.1.6. image

Use the image property to configure the container image used by the component.

Overriding container images is recommended only in special situations where you need to use a different container registry or a customized image.

For example, if your network does not allow access to the container repository used by Strimzi, you can copy the Strimzi images or build them from the source. However, if the configured image is not compatible with Strimzi images, it might not work properly.

A copy of the container image might also be customized and used for debugging.

You can specify which container image to use for a component using the image property in the following resources:

  • Kafka.spec.kafka

  • Kafka.spec.zookeeper

  • Kafka.spec.entityOperator.topicOperator

  • Kafka.spec.entityOperator.userOperator

  • Kafka.spec.entityOperator.tlsSidecar

  • Kafka.spec.jmxTrans

  • KafkaConnect.spec

  • KafkaMirrorMaker.spec

  • KafkaMirrorMaker2.spec

  • KafkaBridge.spec

Configuring the image property for Kafka, Kafka Connect, and Kafka MirrorMaker

Kafka, Kafka Connect, and Kafka MirrorMaker support multiple versions of Kafka. Each component requires its own image. The default images for the different Kafka versions are configured in the following environment variables:

  • STRIMZI_KAFKA_IMAGES

  • STRIMZI_KAFKA_CONNECT_IMAGES

  • STRIMZI_KAFKA_MIRROR_MAKER_IMAGES

These environment variables contain mappings between the Kafka versions and their corresponding images. The mappings are used together with the image and version properties:

  • If neither image nor version are given in the custom resource then the version will default to the Cluster Operator’s default Kafka version, and the image will be the one corresponding to this version in the environment variable.

  • If image is given but version is not, then the given image is used and the version is assumed to be the Cluster Operator’s default Kafka version.

  • If version is given but image is not, then the image that corresponds to the given version in the environment variable is used.

  • If both version and image are given, then the given image is used. The image is assumed to contain a Kafka image with the given version.

The image and version for the different components can be configured in the following properties:

  • For Kafka in spec.kafka.image and spec.kafka.version.

  • For Kafka Connect and Kafka MirrorMaker in spec.image and spec.version.

Warning
It is recommended to provide only the version and leave the image property unspecified. This reduces the chance of making a mistake when configuring the custom resource. If you need to change the images used for different versions of Kafka, it is preferable to configure the Cluster Operator’s environment variables.

Configuring the image property in other resources

For the image property in the other custom resources, the given value will be used during deployment. If the image property is missing, the image specified in the Cluster Operator configuration will be used. If the image name is not defined in the Cluster Operator configuration, then the default value will be used.

  • For Topic Operator:

    1. Container image specified in the STRIMZI_DEFAULT_TOPIC_OPERATOR_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/operator:latest container image.

  • For User Operator:

    1. Container image specified in the STRIMZI_DEFAULT_USER_OPERATOR_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/operator:latest container image.

  • For Entity Operator TLS sidecar:

    1. Container image specified in the STRIMZI_DEFAULT_TLS_SIDECAR_ENTITY_OPERATOR_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/kafka:latest-kafka-3.3.2 container image.

  • For Kafka Exporter:

    1. Container image specified in the STRIMZI_DEFAULT_KAFKA_EXPORTER_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/kafka:latest-kafka-3.3.2 container image.

  • For Kafka Bridge:

    1. Container image specified in the STRIMZI_DEFAULT_KAFKA_BRIDGE_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/kafka-bridge:0.24.0 container image.

  • For Kafka broker initializer:

    1. Container image specified in the STRIMZI_DEFAULT_KAFKA_INIT_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/operator:latest container image.

  • For Kafka jmxTrans:

    1. Container image specified in the STRIMZI_DEFAULT_JMXTRANS_IMAGE environment variable from the Cluster Operator configuration.

    2. quay.io/strimzi/jmxtrans:latest container image.

Example container image configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    image: my-org/my-image:latest
    # ...
  zookeeper:
    # ...

9.1.7. livenessProbe and readinessProbe healthchecks

Use the livenessProbe and readinessProbe properties to configure healthcheck probes supported in Strimzi.

Healthchecks are periodical tests which verify the health of an application. When a Healthcheck probe fails, Kubernetes assumes that the application is not healthy and attempts to fix it.

For more details about the probes, see Configure Liveness and Readiness Probes.

Both livenessProbe and readinessProbe support the following options:

  • initialDelaySeconds

  • timeoutSeconds

  • periodSeconds

  • successThreshold

  • failureThreshold

Example of liveness and readiness probe configuration
# ...
readinessProbe:
  initialDelaySeconds: 15
  timeoutSeconds: 5
livenessProbe:
  initialDelaySeconds: 15
  timeoutSeconds: 5
# ...

For more information about the livenessProbe and readinessProbe options, see the Probe schema reference.

9.1.8. metricsConfig

Use the metricsConfig property to enable and configure Prometheus metrics.

The metricsConfig property contains a reference to a ConfigMap that has additional configurations for the Prometheus JMX Exporter. Strimzi supports Prometheus metrics using Prometheus JMX exporter to convert the JMX metrics supported by Apache Kafka and ZooKeeper to Prometheus metrics.

To enable Prometheus metrics export without further configuration, you can reference a ConfigMap containing an empty file under metricsConfig.valueFrom.configMapKeyRef.key. When referencing an empty file, all metrics are exposed as long as they have not been renamed.

Example ConfigMap with metrics configuration for Kafka
kind: ConfigMap
apiVersion: v1
metadata:
  name: my-configmap
data:
  my-key: |
    lowercaseOutputName: true
    rules:
    # Special cases and very specific rules
    - pattern: kafka.server<type=(.+), name=(.+), clientId=(.+), topic=(.+), partition=(.*)><>Value
      name: kafka_server_$1_$2
      type: GAUGE
      labels:
       clientId: "$3"
       topic: "$4"
       partition: "$5"
    # further configuration
Example metrics configuration for Kafka
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    metricsConfig:
      type: jmxPrometheusExporter
      valueFrom:
        configMapKeyRef:
          name: my-config-map
          key: my-key
    # ...
  zookeeper:
    # ...

When metrics are enabled, they are exposed on port 9404.

When the metricsConfig (or deprecated metrics) property is not defined in the resource, the Prometheus metrics are disabled.

For more information about setting up and deploying Prometheus and Grafana, see Introducing Metrics to Kafka in the Deploying and Upgrading Strimzi guide.

9.1.9. jvmOptions

The following Strimzi components run inside a Java Virtual Machine (JVM):

  • Apache Kafka

  • Apache ZooKeeper

  • Apache Kafka Connect

  • Apache Kafka MirrorMaker

  • Strimzi Kafka Bridge

To optimize their performance on different platforms and architectures, you configure the jvmOptions property in the following resources:

  • Kafka.spec.kafka

  • Kafka.spec.zookeeper

  • Kafka.spec.entityOperator.userOperator

  • Kafka.spec.entityOperator.topicOperator

  • Kafka.spec.cruiseControl

  • KafkaConnect.spec

  • KafkaMirrorMaker.spec

  • KafkaMirrorMaker2.spec

  • KafkaBridge.spec

You can specify the following options in your configuration:

-Xms

Minimum initial allocation heap size when the JVM starts

-Xmx

Maximum heap size

-XX

Advanced runtime options for the JVM

javaSystemProperties

Additional system properties

gcLoggingEnabled

Enables garbage collector logging

Note
The units accepted by JVM settings, such as -Xmx and -Xms, are the same units accepted by the JDK java binary in the corresponding image. Therefore, 1g or 1G means 1,073,741,824 bytes, and Gi is not a valid unit suffix. This is different from the units used for memory requests and limits, which follow the Kubernetes convention where 1G means 1,000,000,000 bytes, and 1Gi means 1,073,741,824 bytes.
-Xms and -Xmx options

In addition to setting memory request and limit values for your containers, you can use the -Xms and -Xmx JVM options to set specific heap sizes for your JVM. Use the -Xms option to set an initial heap size and the -Xmx option to set a maximum heap size.

Specify heap size to have more control over the memory allocated to your JVM. Heap sizes should make the best use of a container’s memory limit (and request) without exceeding it. Heap size and any other memory requirements need to fit within a specified memory limit. If you don’t specify heap size in your configuration, but you configure a memory resource limit (and request), the Cluster Operator imposes default heap sizes automatically. The Cluster Operator sets default maximum and minimum heap values based on a percentage of the memory resource configuration.

The following table shows the default heap values.

Table 32. Default heap settings for components
Component Percent of available memory allocated to the heap Maximum limit

Kafka

50%

5 GB

ZooKeeper

75%

2 GB

Kafka Connect

75%

None

MirrorMaker 2.0

75%

None

MirrorMaker

75%

None

Cruise Control

75%

None

Kafka Bridge

50%

31 Gi

If a memory limit (and request) is not specified, a JVM’s minimum heap size is set to 128M. The JVM’s maximum heap size is not defined to allow the memory to increase as needed. This is ideal for single node environments in test and development.

Setting an appropriate memory request can prevent the following:

  • Kubernetes killing a container if there is pressure on memory from other pods running on the node.

  • Kubernetes scheduling a container to a node with insufficient memory. If -Xms is set to -Xmx, the container will crash immediately; if not, the container will crash at a later time.

In this example, the JVM uses 2 GiB (=2,147,483,648 bytes) for its heap. Total JVM memory usage can be a lot more than the maximum heap size.

Example -Xmx and -Xms configuration
# ...
jvmOptions:
  "-Xmx": "2g"
  "-Xms": "2g"
# ...

Setting the same value for initial (-Xms) and maximum (-Xmx) heap sizes avoids the JVM having to allocate memory after startup, at the cost of possibly allocating more heap than is really needed.

Important
Containers performing lots of disk I/O, such as Kafka broker containers, require available memory for use as an operating system page cache. For such containers, the requested memory should be significantly higher than the memory used by the JVM.
-XX option

-XX options are used to configure the KAFKA_JVM_PERFORMANCE_OPTS option of Apache Kafka.

Example -XX configuration
jvmOptions:
  "-XX":
    "UseG1GC": true
    "MaxGCPauseMillis": 20
    "InitiatingHeapOccupancyPercent": 35
    "ExplicitGCInvokesConcurrent": true
JVM options resulting from the -XX configuration
-XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:+ExplicitGCInvokesConcurrent -XX:-UseParNewGC
Note
When no -XX options are specified, the default Apache Kafka configuration of KAFKA_JVM_PERFORMANCE_OPTS is used.
javaSystemProperties

javaSystemProperties are used to configure additional Java system properties, such as debugging utilities.

Example javaSystemProperties configuration
jvmOptions:
  javaSystemProperties:
    - name: javax.net.debug
      value: ssl

For more information about the jvmOptions, see the JvmOptions schema reference.

9.1.10. Garbage collector logging

The jvmOptions property also allows you to enable and disable garbage collector (GC) logging. GC logging is disabled by default. To enable it, set the gcLoggingEnabled property as follows:

Example GC logging configuration
# ...
jvmOptions:
  gcLoggingEnabled: true
# ...

9.2. Schema properties

9.2.1. Kafka schema reference

Property Description

spec

The specification of the Kafka and ZooKeeper clusters, and Topic Operator.

KafkaSpec

status

The status of the Kafka and ZooKeeper clusters, and Topic Operator.

KafkaStatus

9.2.2. KafkaSpec schema reference

Used in: Kafka

Property Description

kafka

Configuration of the Kafka cluster.

KafkaClusterSpec

zookeeper

Configuration of the ZooKeeper cluster.

ZookeeperClusterSpec

entityOperator

Configuration of the Entity Operator.

EntityOperatorSpec

clusterCa

Configuration of the cluster certificate authority.

CertificateAuthority

clientsCa

Configuration of the clients certificate authority.

CertificateAuthority

cruiseControl

Configuration for Cruise Control deployment. Deploys a Cruise Control instance when specified.

CruiseControlSpec

jmxTrans

The jmxTrans property has been deprecated. JMXTrans is deprecated and will be removed in Strimzi 0.35.0 Configuration for JmxTrans. When the property is present a JmxTrans deployment is created for gathering JMX metrics from each Kafka broker. For more information see JmxTrans GitHub.

JmxTransSpec

kafkaExporter

Configuration of the Kafka Exporter. Kafka Exporter can provide additional metrics, for example lag of consumer group at topic/partition.

KafkaExporterSpec

maintenanceTimeWindows

A list of time windows for maintenance tasks (that is, certificates renewal). Each time window is defined by a cron expression.

string array

9.2.3. KafkaClusterSpec schema reference

Used in: KafkaSpec

Configures a Kafka cluster.

listeners

Use the listeners property to configure listeners to provide access to Kafka brokers.

Example configuration of a plain (unencrypted) listener without authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
  kafka:
    # ...
    listeners:
      - name: plain
        port: 9092
        type: internal
        tls: false
    # ...
  zookeeper:
    # ...
config

Use the config properties to configure Kafka broker options as keys.

Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.

Configuration options that cannot be configured relate to:

  • Security (Encryption, Authentication, and Authorization)

  • Listener configuration

  • Broker ID configuration

  • Configuration of log data directories

  • Inter-broker communication

  • ZooKeeper connectivity

The values can be one of the following JSON types:

  • String

  • Number

  • Boolean

You can specify and configure the options listed in the Apache Kafka documentation with the exception of those options that are managed directly by Strimzi. Specifically, all configuration options with keys equal to or starting with one of the following strings are forbidden:

  • listeners

  • advertised.

  • broker.

  • listener.

  • host.name

  • port

  • inter.broker.listener.name

  • sasl.

  • ssl.

  • security.

  • password.

  • principal.builder.class

  • log.dir

  • zookeeper.connect

  • zookeeper.set.acl

  • authorizer.

  • super.user

When a forbidden option is present in the config property, it is ignored and a warning message is printed to the Cluster Operator log file. All other supported options are passed to Kafka.

There are exceptions to the forbidden options. For client connection using a specific cipher suite for a TLS version, you can configure allowed ssl properties. You can also configure the zookeeper.connection.timeout.ms property to set the maximum time allowed for establishing a ZooKeeper connection.

Example Kafka broker configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    config:
      num.partitions: 1
      num.recovery.threads.per.data.dir: 1
      default.replication.factor: 3
      offsets.topic.replication.factor: 3
      transaction.state.log.replication.factor: 3
      transaction.state.log.min.isr: 1
      log.retention.hours: 168
      log.segment.bytes: 1073741824
      log.retention.check.interval.ms: 300000
      num.network.threads: 3
      num.io.threads: 8
      socket.send.buffer.bytes: 102400
      socket.receive.buffer.bytes: 102400
      socket.request.max.bytes: 104857600
      group.initial.rebalance.delay.ms: 0
      ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
      ssl.enabled.protocols: "TLSv1.2"
      ssl.protocol: "TLSv1.2"
      zookeeper.connection.timeout.ms: 6000
    # ...
brokerRackInitImage

When rack awareness is enabled, Kafka broker pods use init container to collect the labels from the Kubernetes cluster nodes. The container image used for this container can be configured using the brokerRackInitImage property. When the brokerRackInitImage field is missing, the following images are used in order of priority:

  1. Container image specified in STRIMZI_DEFAULT_KAFKA_INIT_IMAGE environment variable in the Cluster Operator configuration.

  2. quay.io/strimzi/operator:latest container image.

Example brokerRackInitImage configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    rack:
      topologyKey: topology.kubernetes.io/zone
    brokerRackInitImage: my-org/my-image:latest
    # ...
Note
Overriding container images is recommended only in special situations, where you need to use a different container registry. For example, because your network does not allow access to the container registry used by Strimzi. In this case, you should either copy the Strimzi images or build them from the source. If the configured image is not compatible with Strimzi images, it might not work properly.
logging

Kafka has its own configurable loggers:

  • log4j.logger.org.I0Itec.zkclient.ZkClient

  • log4j.logger.org.apache.zookeeper

  • log4j.logger.kafka

  • log4j.logger.org.apache.kafka

  • log4j.logger.kafka.request.logger

  • log4j.logger.kafka.network.Processor

  • log4j.logger.kafka.server.KafkaApis

  • log4j.logger.kafka.network.RequestChannel$

  • log4j.logger.kafka.controller

  • log4j.logger.kafka.log.LogCleaner

  • log4j.logger.state.change.logger

  • log4j.logger.kafka.authorizer.logger

Kafka uses the Apache log4j logger implementation.

Use the logging property to configure loggers and logger levels.

You can set the log levels by specifying the logger and level directly (inline) or use a custom (external) ConfigMap. If a ConfigMap is used, you set logging.valueFrom.configMapKeyRef.name property to the name of the ConfigMap containing the external logging configuration. Inside the ConfigMap, the logging configuration is described using log4j.properties. Both logging.valueFrom.configMapKeyRef.name and logging.valueFrom.configMapKeyRef.key properties are mandatory. A ConfigMap using the exact logging configuration specified is created with the custom resource when the Cluster Operator is running, then recreated after each reconciliation. If you do not specify a custom ConfigMap, default logging settings are used. If a specific logger value is not set, upper-level logger settings are inherited for that logger. For more information about log levels, see Apache logging services.

Here we see examples of inline and external logging.

Inline logging
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
  # ...
  kafka:
    # ...
    logging:
      type: inline
      loggers:
        kafka.root.logger.level: "INFO"
  # ...
External logging
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
  # ...
  logging:
    type: external
    valueFrom:
      configMapKeyRef:
        name: customConfigMap
        key: kafka-log4j.properties
  # ...

Any available loggers that are not configured have their level set to OFF.

If Kafka was deployed using the Cluster Operator, changes to Kafka logging levels are applied dynamically.

If you use external logging, a rolling update is triggered when logging appenders are changed.

Garbage collector (GC)

Garbage collector logging can also be enabled (or disabled) using the jvmOptions property.

KafkaClusterSpec schema properties
Property Description

version

The kafka broker version. Defaults to 3.3.2. Consult the user documentation to understand the process required to upgrade or downgrade the version.

string

replicas

The number of pods in the cluster.

integer

image

The docker image for the pods. The default value depends on the configured Kafka.spec.kafka.version.

string

listeners

Configures listeners of Kafka brokers.

GenericKafkaListener array

config

Kafka broker config properties with the following prefixes cannot be set: listeners, advertised., broker., listener., host.name, port, inter.broker.listener.name, sasl., ssl., security., password., log.dir, zookeeper.connect, zookeeper.set.acl, zookeeper.ssl, zookeeper.clientCnxnSocket, authorizer., super.user, cruise.control.metrics.topic, cruise.control.metrics.reporter.bootstrap.servers,node.id, process.roles, controller. (with the exception of: zookeeper.connection.timeout.ms, sasl.server.max.receive.size,ssl.cipher.suites, ssl.protocol, ssl.enabled.protocols, ssl.secure.random.implementation,cruise.control.metrics.topic.num.partitions, cruise.control.metrics.topic.replication.factor, cruise.control.metrics.topic.retention.ms,cruise.control.metrics.topic.auto.create.retries, cruise.control.metrics.topic.auto.create.timeout.ms,cruise.control.metrics.topic.min.insync.replicas,controller.quorum.election.backoff.max.ms, controller.quorum.election.timeout.ms, controller.quorum.fetch.timeout.ms).

map

storage

Storage configuration (disk). Cannot be updated. The type depends on the value of the storage.type property within the given object, which must be one of [ephemeral, persistent-claim, jbod].

EphemeralStorage, PersistentClaimStorage, JbodStorage

authorization

Authorization configuration for Kafka brokers. The type depends on the value of the authorization.type property within the given object, which must be one of [simple, opa, keycloak, custom].

KafkaAuthorizationSimple, KafkaAuthorizationOpa, KafkaAuthorizationKeycloak, KafkaAuthorizationCustom

rack

Configuration of the broker.rack broker config.

Rack

brokerRackInitImage

The image of the init container used for initializing the broker.rack.

string

livenessProbe

Pod liveness checking.

Probe

readinessProbe

Pod readiness checking.

Probe

jvmOptions

JVM Options for pods.

JvmOptions

jmxOptions

JMX Options for Kafka brokers.

KafkaJmxOptions

resources

CPU and memory resources to reserve. For more information, see the external documentation for core/v1 resourcerequirements.

ResourceRequirements

metricsConfig

Metrics configuration. The type depends on the value of the metricsConfig.type property within the given object, which must be one of [jmxPrometheusExporter].

JmxPrometheusExporterMetrics

logging

Logging configuration for Kafka. The type depends on the value of the logging.type property within the given object, which must be one of [inline, external].

InlineLogging, ExternalLogging

template

Template for Kafka cluster resources. The template allows users to specify how the StatefulSet, Pods, and Services are generated.

KafkaClusterTemplate

9.2.4. GenericKafkaListener schema reference

Used in: KafkaClusterSpec

Configures listeners to connect to Kafka brokers within and outside Kubernetes.

You configure the listeners in the Kafka resource.

Example Kafka resource showing listener configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    #...
    listeners:
      - name: plain
        port: 9092
        type: internal
        tls: false
      - name: tls
        port: 9093
        type: internal
        tls: true
        authentication:
          type: tls
      - name: external1
        port: 9094
        type: route
        tls: true
      - name: external2
        port: 9095
        type: ingress
        tls: true
        authentication:
          type: tls
        configuration:
          bootstrap:
            host: bootstrap.myingress.com
          brokers:
          - broker: 0
            host: broker-0.myingress.com
          - broker: 1
            host: broker-1.myingress.com
          - broker: 2
            host: broker-2.myingress.com
    #...
listeners

You configure Kafka broker listeners using the listeners property in the Kafka resource. Listeners are defined as an array.

Example listener configuration
listeners:
  - name: plain
    port: 9092
    type: internal
    tls: false

The name and port must be unique within the Kafka cluster. The name can be up to 25 characters long, comprising lower-case letters and numbers. Allowed port numbers are 9092 and higher with the exception of ports 9404 and 9999, which are already used for Prometheus and JMX.

By specifying a unique name and port for each listener, you can configure multiple listeners.

type

The type is set as internal, or for external listeners, as route, loadbalancer, nodeport, ingress or cluster-ip. You can also configure a cluster-ip listener, a type of internal listener you can use to build custom access mechanisms.

internal

You can configure internal listeners with or without encryption using the tls property.

Example internal listener configuration
#...
spec:
  kafka:
    #...
    listeners:
      #...
      - name: plain
        port: 9092
        type: internal
        tls: false
      - name: tls
        port: 9093
        type: internal
        tls: true
        authentication:
          type: tls
    #...
route

Configures an external listener to expose Kafka using OpenShift Routes and the HAProxy router.

A dedicated Route is created for every Kafka broker pod. An additional Route is created to serve as a Kafka bootstrap address. Kafka clients can use these Routes to connect to Kafka on port 443. The client connects on port 443, the default router port, but traffic is then routed to the port you configure, which is 9094 in this example.

Example route listener configuration
#...
spec:
  kafka:
    #...
    listeners:
      #...
      - name: external1
        port: 9094
        type: route
        tls: true
    #...
ingress

Configures an external listener to expose Kafka using Kubernetes Ingress and the Ingress NGINX Controller for Kubernetes.

A dedicated Ingress resource is created for every Kafka broker pod. An additional Ingress resource is created to serve as a Kafka bootstrap address. Kafka clients can use these Ingress resources to connect to Kafka on port 443. The client connects on port 443, the default controller port, but traffic is then routed to the port you configure, which is 9095 in the following example.

You must specify the hostnames used by the bootstrap and per-broker services using GenericKafkaListenerConfigurationBootstrap and GenericKafkaListenerConfigurationBroker properties.

Example ingress listener configuration
#...
spec:
  kafka:
    #...
    listeners:
      #...
      - name: external2
        port: 9095
        type: ingress
        tls: true
        authentication:
          type: tls
        configuration:
          bootstrap:
            host: bootstrap.myingress.com
          brokers:
          - broker: 0
            host: broker-0.myingress.com
          - broker: 1
            host: broker-1.myingress.com
          - broker: 2
            host: broker-2.myingress.com
  #...
Note
External listeners using Ingress are currently only tested with the Ingress NGINX Controller for Kubernetes.
loadbalancer

Configures an external listener to expose Kafka using a Loadbalancer type Service.

A new loadbalancer service is created for every Kafka broker pod. An additional loadbalancer is created to serve as a Kafka bootstrap address. Loadbalancers listen to the specified port number, which is port 9094 in the following example.

You can use the loadBalancerSourceRanges property to configure source ranges to restrict access to the specified IP addresses.

Example loadbalancer listener configuration
#...
spec:
  kafka:
    #...
    listeners:
      - name: external3
        port: 9094
        type: loadbalancer
        tls: true
        configuration:
          loadBalancerSourceRanges:
            - 10.0.0.0/8
            - 88.208.76.87/32
    #...
nodeport

Configures an external listener to expose Kafka using a NodePort type Service.

Kafka clients connect directly to the nodes of Kubernetes. An additional NodePort type of service is created to serve as a Kafka bootstrap address.

When configuring the advertised addresses for the Kafka broker pods, Strimzi uses the address of the node on which the given pod is running. You can use preferredNodePortAddressType property to configure the first address type checked as the node address.

Example nodeport listener configuration
#...
spec:
  kafka:
    #...
    listeners:
      #...
      - name: external4
        port: 9095
        type: nodeport
        tls: false
        configuration:
          preferredNodePortAddressType: InternalDNS
    #...
Note
TLS hostname verification is not currently supported when exposing Kafka clusters using node ports.
cluster-ip

Configures an internal listener to expose Kafka using a per-broker ClusterIP type Service.

The listener does not use a headless service and its DNS names to route traffic to Kafka brokers. You can use this type of listener to expose a Kafka cluster when using the headless service is unsuitable. You might use it with a custom access mechanism, such as one that uses a specific Ingress controller or the Kubernetes Gateway API.

A new ClusterIP service is created for each Kafka broker pod. The service is assigned a ClusterIP address to serve as a Kafka bootstrap address with a per-broker port number. For example, you can configure the listener to expose a Kafka cluster over an Nginx Ingress Controller with TCP port configuration.

Example cluster-ip listener configuration
#...
spec:
  kafka:
    #...
    listeners:
      - name: external-cluster-ip
        type: cluster-ip
        tls: false
        port: 9096
    #...
port

The port number is the port used in the Kafka cluster, which might not be the same port used for access by a client.

  • loadbalancer listeners use the specified port number, as do internal and cluster-ip listeners

  • ingress and route listeners use port 443 for access

  • nodeport listeners use the port number assigned by Kubernetes

For client connection, use the address and port for the bootstrap service of the listener. You can retrieve this from the status of the Kafka resource.

Example command to retrieve the address and port for client connection
kubectl get kafka <kafka_cluster_name> -o=jsonpath='{.status.listeners[?(@.name=="<listener_name>")].bootstrapServers}{"\n"}'
Note
Listeners cannot be configured to use the ports set aside for interbroker communication (9090 and 9091) and metrics (9404).
tls

The TLS property is required.

By default, TLS encryption is not enabled. To enable it, set the tls property to true.

For route and ingress type listeners, TLS encryption must be enabled.

authentication

Authentication for the listener can be specified as:

  • mTLS (tls)

  • SCRAM-SHA-512 (scram-sha-512)

  • Token-based OAuth 2.0 (oauth)

  • Custom (custom)

networkPolicyPeers

Use networkPolicyPeers to configure network policies that restrict access to a listener at the network level. The following example shows a networkPolicyPeers configuration for a plain and a tls listener.

In the following example:

  • Only application pods matching the labels app: kafka-sasl-consumer and app: kafka-sasl-producer can connect to the plain listener. The application pods must be running in the same namespace as the Kafka broker.

  • Only application pods running in namespaces matching the labels project: myproject and project: myproject2 can connect to the tls listener.

The syntax of the networkPolicyPeers property is the same as the from property in NetworkPolicy resources.

Exanmple network policy configuration
listeners:
  #...
  - name: plain
    port: 9092
    type: internal
    tls: true
    authentication:
      type: scram-sha-512
    networkPolicyPeers:
      - podSelector:
          matchLabels:
            app: kafka-sasl-consumer
      - podSelector:
          matchLabels:
            app: kafka-sasl-producer
  - name: tls
    port: 9093
    type: internal
    tls: true
    authentication:
      type: tls
    networkPolicyPeers:
      - namespaceSelector:
          matchLabels:
            project: myproject
      - namespaceSelector:
          matchLabels:
            project: myproject2
# ...
GenericKafkaListener schema properties
Property Description

name

Name of the listener. The name will be used to identify the listener and the related Kubernetes objects. The name has to be unique within given a Kafka cluster. The name can consist of lowercase characters and numbers and be up to 11 characters long.

string

port

Port number used by the listener inside Kafka. The port number has to be unique within a given Kafka cluster. Allowed port numbers are 9092 and higher with the exception of ports 9404 and 9999, which are already used for Prometheus and JMX. Depending on the listener type, the port number might not be the same as the port number that connects Kafka clients.

integer

type

Type of the listener. Currently the supported types are internal, route, loadbalancer, nodeport and ingress.

  • internal type exposes Kafka internally only within the Kubernetes cluster.

  • route type uses OpenShift Routes to expose Kafka.

  • loadbalancer type uses LoadBalancer type services to expose Kafka.

  • nodeport type uses NodePort type services to expose Kafka.

  • ingress type uses Kubernetes Nginx Ingress to expose Kafka with TLS passthrough.

  • cluster-ip type uses a per-broker ClusterIP service.

string (one of [ingress, internal, route, loadbalancer, cluster-ip, nodeport])

tls

Enables TLS encryption on the listener. This is a required property.

boolean

authentication

Authentication configuration for this listener. The type depends on the value of the authentication.type property within the given object, which must be one of [tls, scram-sha-512, oauth, custom].

KafkaListenerAuthenticationTls, KafkaListenerAuthenticationScramSha512, KafkaListenerAuthenticationOAuth, KafkaListenerAuthenticationCustom

configuration

Additional listener configuration.

GenericKafkaListenerConfiguration

networkPolicyPeers

List of peers which should be able to connect to this listener. Peers in this list are combined using a logical OR operation. If this field is empty or missing, all connections will be allowed for this listener. If this field is present and contains at least one item, the listener only allows the traffic which matches at least one item in this list. For more information, see the external documentation for networking.k8s.io/v1 networkpolicypeer.

NetworkPolicyPeer array

9.2.5. KafkaListenerAuthenticationTls schema reference

The type property is a discriminator that distinguishes use of the KafkaListenerAuthenticationTls type from KafkaListenerAuthenticationScramSha512, KafkaListenerAuthenticationOAuth, KafkaListenerAuthenticationCustom. It must have the value tls for the type KafkaListenerAuthenticationTls.

Property Description

type

Must be tls.

string

9.2.6. KafkaListenerAuthenticationScramSha512 schema reference

The type property is a discriminator that distinguishes use of the KafkaListenerAuthenticationScramSha512 type from KafkaListenerAuthenticationTls, KafkaListenerAuthenticationOAuth, KafkaListenerAuthenticationCustom. It must have the value scram-sha-512 for the type KafkaListenerAuthenticationScramSha512.

Property Description

type

Must be scram-sha-512.

string

9.2.7. KafkaListenerAuthenticationOAuth schema reference

The type property is a discriminator that distinguishes use of the KafkaListenerAuthenticationOAuth type from KafkaListenerAuthenticationTls, KafkaListenerAuthenticationScramSha512, KafkaListenerAuthenticationCustom. It must have the value oauth for the type KafkaListenerAuthenticationOAuth.

Property Description

accessTokenIsJwt

Configure whether the access token is treated as JWT. This must be set to false if the authorization server returns opaque tokens. Defaults to true.

boolean

checkAccessTokenType

Configure whether the access token type check is performed or not. This should be set to false if the authorization server does not include 'typ' claim in JWT token. Defaults to true.

boolean

checkAudience

Enable or disable audience checking. Audience checks identify the recipients of tokens. If audience checking is enabled, the OAuth Client ID also has to be configured using the clientId property. The Kafka broker will reject tokens that do not have its clientId in their aud (audience) claim.Default value is false.

boolean

checkIssuer

Enable or disable issuer checking. By default issuer is checked using the value configured by validIssuerUri. Default value is true.

boolean

clientAudience

The audience to use when making requests to the authorization server’s token endpoint. Used for inter-broker authentication and for configuring OAuth 2.0 over PLAIN using the clientId and secret method.

string

clientId

OAuth Client ID which the Kafka broker can use to authenticate against the authorization server and use the introspect endpoint URI.

string

clientScope

The scope to use when making requests to the authorization server’s token endpoint. Used for inter-broker authentication and for configuring OAuth 2.0 over PLAIN using the clientId and secret method.

string

clientSecret

Link to Kubernetes Secret containing the OAuth client secret which the Kafka broker can use to authenticate against the authorization server and use the introspect endpoint URI.

GenericSecretSource

connectTimeoutSeconds

The connect timeout in seconds when connecting to authorization server. If not set, the effective connect timeout is 60 seconds.

integer

customClaimCheck

JsonPath filter query to be applied to the JWT token or to the response of the introspection endpoint for additional token validation. Not set by default.

string

disableTlsHostnameVerification

Enable or disable TLS hostname verification. Default value is false.

boolean

enableECDSA

The enableECDSA property has been deprecated. Enable or disable ECDSA support by installing BouncyCastle crypto provider. ECDSA support is always enabled. The BouncyCastle libraries are no longer packaged with Strimzi. Value is ignored.

boolean

enableMetrics

Enable or disable OAuth metrics. Default value is false.

boolean

enableOauthBearer

Enable or disable OAuth authentication over SASL_OAUTHBEARER. Default value is true.

boolean

enablePlain

Enable or disable OAuth authentication over SASL_PLAIN. There is no re-authentication support when this mechanism is used. Default value is false.

boolean

failFast

Enable or disable termination of Kafka broker processes due to potentially recoverable runtime errors during startup. Default value is true.

boolean

fallbackUserNameClaim

The fallback username claim to be used for the user id if the claim specified by userNameClaim is not present. This is useful when client_credentials authentication only results in the client id being provided in another claim. It only takes effect if userNameClaim is set.

string

fallbackUserNamePrefix

The prefix to use with the value of fallbackUserNameClaim to construct the user id. This only takes effect if fallbackUserNameClaim is true, and the value is present for the claim. Mapping usernames and client ids into the same user id space is useful in preventing name collisions.

string

groupsClaim

JsonPath query used to extract groups for the user during authentication. Extracted groups can be used by a custom authorizer. By default no groups are extracted.

string

groupsClaimDelimiter

A delimiter used to parse groups when they are extracted as a single String value rather than a JSON array. Default value is ',' (comma).

string

introspectionEndpointUri

URI of the token introspection endpoint which can be used to validate opaque non-JWT tokens.

string

jwksEndpointUri

URI of the JWKS certificate endpoint, which can be used for local JWT validation.

string

jwksExpirySeconds

Configures how often are the JWKS certificates considered valid. The expiry interval has to be at least 60 seconds longer then the refresh interval specified in jwksRefreshSeconds. Defaults to 360 seconds.

integer

jwksIgnoreKeyUse

Flag to ignore the 'use' attribute of key declarations in a JWKS endpoint response. Default value is false.

boolean

jwksMinRefreshPauseSeconds

The minimum pause between two consecutive refreshes. When an unknown signing key is encountered the refresh is scheduled immediately, but will always wait for this minimum pause. Defaults to 1 second.

integer

jwksRefreshSeconds

Configures how often are the JWKS certificates refreshed. The refresh interval has to be at least 60 seconds shorter then the expiry interval specified in jwksExpirySeconds. Defaults to 300 seconds.

integer

maxSecondsWithoutReauthentication

Maximum number of seconds the authenticated session remains valid without re-authentication. This enables Apache Kafka re-authentication feature, and causes sessions to expire when the access token expires. If the access token expires before max time or if max time is reached, the client has to re-authenticate, otherwise the server will drop the connection. Not set by default - the authenticated session does not expire when the access token expires. This option only applies to SASL_OAUTHBEARER authentication mechanism (when enableOauthBearer is true).

integer

readTimeoutSeconds

The read timeout in seconds when connecting to authorization server. If not set, the effective read timeout is 60 seconds.

integer

tlsTrustedCertificates

Trusted certificates for TLS connection to the OAuth server.

CertSecretSource array

tokenEndpointUri

URI of the Token Endpoint to use with SASL_PLAIN mechanism when the client authenticates with clientId and a secret. If set, the client can authenticate over SASL_PLAIN by either setting username to clientId, and setting password to client secret, or by setting username to account username, and password to access token prefixed with $accessToken:. If this option is not set, the password is always interpreted as an access token (without a prefix), and username as the account username (a so called 'no-client-credentials' mode).

string

type

Must be oauth.

string

userInfoEndpointUri

URI of the User Info Endpoint to use as a fallback to obtaining the user id when the Introspection Endpoint does not return information that can be used for the user id.

string

userNameClaim

Name of the claim from the JWT authentication token, Introspection Endpoint response or User Info Endpoint response which will be used to extract the user id. Defaults to sub.

string

validIssuerUri

URI of the token issuer used for authentication.

string

validTokenType

Valid value for the token_type attribute returned by the Introspection Endpoint. No default value, and not checked by default.

string

9.2.8. GenericSecretSource schema reference

Property Description

key

The key under which the secret value is stored in the Kubernetes Secret.

string

secretName

The name of the Kubernetes Secret containing the secret value.

string

9.2.9. CertSecretSource schema reference

Property Description

certificate

The name of the file certificate in the Secret.

string

secretName

The name of the Secret containing the certificate.

string

9.2.10. KafkaListenerAuthenticationCustom schema reference

To configure custom authentication, set the type property to custom.

Custom authentication allows for any type of kafka-supported authentication to be used.

Example custom OAuth authentication configuration
spec:
  kafka:
    config:
      principal.builder.class: SimplePrincipal.class
    listeners:
      - name: oauth-bespoke
        port: 9093
        type: internal
        tls: true
        authentication:
          type: custom
          sasl: true
          listenerConfig:
            oauthbearer.sasl.client.callback.handler.class: client.class
            oauthbearer.sasl.server.callback.handler.class: server.class
            oauthbearer.sasl.login.callback.handler.class: login.class
            oauthbearer.connections.max.reauth.ms: 999999999
            sasl.enabled.mechanisms: oauthbearer
            oauthbearer.sasl.jaas.config: |
              org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required ;
          secrets:
            - name: example

A protocol map is generated that uses the sasl and tls values to determine which protocol to map to the listener.

  • SASL = True, TLS = True → SASL_SSL

  • SASL = False, TLS = True → SSL

  • SASL = True, TLS = False → SASL_PLAINTEXT

  • SASL = False, TLS = False → PLAINTEXT

listenerConfig

Listener configuration specified using listenerConfig is prefixed with listener.name.<listener_name>-<port>. For example, sasl.enabled.mechanisms becomes listener.name.<listener_name>-<port>.sasl.enabled.mechanisms.

secrets

Secrets are mounted to /opt/kafka/custom-authn-secrets/custom-listener-<listener_name>-<port>/<secret_name> in the Kafka broker nodes' containers.

For example, the mounted secret (example) in the example configuration would be located at /opt/kafka/custom-authn-secrets/custom-listener-oauth-bespoke-9093/example.

Principal builder

You can set a custom principal builder in the Kafka cluster configuration. However, the principal builder is subject to the following requirements:

  • The specified principal builder class must exist on the image. Before building your own, check if one already exists. You’ll need to rebuild the Strimzi images with the required classes.

  • No other listener is using oauth type authentication. This is because an OAuth listener appends its own principle builder to the Kafka configuration.

  • The specified principal builder is compatible with Strimzi.

Custom principal builders must support peer certificates for authentication, as Strimzi uses these to manage the Kafka cluster.

A custom OAuth principal builder might be identical or very similar to the Strimzi OAuth principal builder.

Note
Kafka’s default principal builder class supports the building of principals based on the names of peer certificates. The custom principal builder should provide a principal of type user using the name of the SSL peer certificate.

The following example shows a custom principal builder that satisfies the OAuth requirements of Strimzi.

Example principal builder for custom OAuth configuration
public final class CustomKafkaPrincipalBuilder implements KafkaPrincipalBuilder {

    public KafkaPrincipalBuilder() {}

    @Override
    public KafkaPrincipal build(AuthenticationContext context) {
        if (context instanceof SslAuthenticationContext) {
            SSLSession sslSession = ((SslAuthenticationContext) context).session();
            try {
                return new KafkaPrincipal(
                    KafkaPrincipal.USER_TYPE, sslSession.getPeerPrincipal().getName());
            } catch (SSLPeerUnverifiedException e) {
                throw new IllegalArgumentException("Cannot use an unverified peer for authentication", e);
            }
        }

        // Create your own KafkaPrincipal here
        ...
    }
}
KafkaListenerAuthenticationCustom schema properties

The type property is a discriminator that distinguishes use of the KafkaListenerAuthenticationCustom type from KafkaListenerAuthenticationTls, KafkaListenerAuthenticationScramSha512, KafkaListenerAuthenticationOAuth. It must have the value custom for the type KafkaListenerAuthenticationCustom.

Property Description

listenerConfig

Configuration to be used for a specific listener. All values are prefixed with listener.name.<listener_name>.

map

sasl

Enable or disable SASL on this listener.

boolean

secrets

Secrets to be mounted to /opt/kafka/custom-authn-secrets/custom-listener-<listener_name>-<port>/<secret_name>.

GenericSecretSource array

type

Must be custom.

string

9.2.11. GenericKafkaListenerConfiguration schema reference

Configuration for Kafka listeners.

brokerCertChainAndKey

The brokerCertChainAndKey property is only used with listeners that have TLS encryption enabled. You can use the property to provide your own Kafka listener certificates.

Example configuration for a loadbalancer external listener with TLS encryption enabled
listeners:
  #...
  - name: external
    port: 9094
    type: loadbalancer
    tls: true
    authentication:
      type: tls
    configuration:
      brokerCertChainAndKey:
        secretName: my-secret
        certificate: my-listener-certificate.crt
        key: my-listener-key.key
# ...
externalTrafficPolicy

The externalTrafficPolicy property is used with loadbalancer and nodeport listeners. When exposing Kafka outside of Kubernetes you can choose Local or Cluster. Local avoids hops to other nodes and preserves the client IP, whereas Cluster does neither. The default is Cluster.

loadBalancerSourceRanges

The loadBalancerSourceRanges property is only used with loadbalancer listeners. When exposing Kafka outside of Kubernetes use source ranges, in addition to labels and annotations, to customize how a service is created.

Example source ranges configured for a loadbalancer listener
listeners:
  #...
  - name: external
    port: 9094
    type: loadbalancer
    tls: false
    configuration:
      externalTrafficPolicy: Local
      loadBalancerSourceRanges:
        - 10.0.0.0/8
        - 88.208.76.87/32
      # ...
# ...
class

The class property is only used with ingress listeners. You can configure the Ingress class using the class property.

Example of an external listener of type ingress using Ingress class nginx-internal
listeners:
  #...
  - name: external
    port: 9094
    type: ingress
    tls: true
    configuration:
      class: nginx-internal
    # ...
# ...
preferredNodePortAddressType

The preferredNodePortAddressType property is only used with nodeport listeners.

Use the preferredNodePortAddressType property in your listener configuration to specify the first address type checked as the node address. This property is useful, for example, if your deployment does not have DNS support, or you only want to expose a broker internally through an internal DNS or IP address. If an address of this type is found, it is used. If the preferred address type is not found, Strimzi proceeds through the types in the standard order of priority:

  1. ExternalDNS

  2. ExternalIP

  3. Hostname

  4. InternalDNS

  5. InternalIP

Example of an external listener configured with a preferred node port address type
listeners:
  #...
  - name: external
    port: 9094
    type: nodeport
    tls: false
    configuration:
      preferredNodePortAddressType: InternalDNS
      # ...
# ...
useServiceDnsDomain

The useServiceDnsDomain property is only used with internal and cluster-ip listeners. It defines whether the fully-qualified DNS names that include the cluster service suffix (usually .cluster.local) are used. With useServiceDnsDomain set as false, the advertised addresses are generated without the service suffix; for example, my-cluster-kafka-0.my-cluster-kafka-brokers.myproject.svc. With useServiceDnsDomain set as true, the advertised addresses are generated with the service suffix; for example, my-cluster-kafka-0.my-cluster-kafka-brokers.myproject.svc.cluster.local. Default is false.

Example of an internal listener configured to use the Service DNS domain
listeners:
  #...
  - name: plain
    port: 9092
    type: internal
    tls: false
    configuration:
      useServiceDnsDomain: true
      # ...
# ...

If your Kubernetes cluster uses a different service suffix than .cluster.local, you can configure the suffix using the KUBERNETES_SERVICE_DNS_DOMAIN environment variable in the Cluster Operator configuration. See Configuring the Cluster Operator with environment variables for more details.

GenericKafkaListenerConfiguration schema properties
Property Description

brokerCertChainAndKey

Reference to the Secret which holds the certificate and private key pair which will be used for this listener. The certificate can optionally contain the whole chain. This field can be used only with listeners with enabled TLS encryption.

CertAndKeySecretSource

externalTrafficPolicy

Specifies whether the service routes external traffic to node-local or cluster-wide endpoints. Cluster may cause a second hop to another node and obscures the client source IP. Local avoids a second hop for LoadBalancer and Nodeport type services and preserves the client source IP (when supported by the infrastructure). If unspecified, Kubernetes will use Cluster as the default.This field can be used only with loadbalancer or nodeport type listener.

string (one of [Local, Cluster])

loadBalancerSourceRanges

A list of CIDR ranges (for example 10.0.0.0/8 or 130.211.204.1/32) from which clients can connect to load balancer type listeners. If supported by the platform, traffic through the loadbalancer is restricted to the specified CIDR ranges. This field is applicable only for loadbalancer type services and is ignored if the cloud provider does not support the feature. This field can be used only with loadbalancer type listener.

string array

bootstrap

Bootstrap configuration.

GenericKafkaListenerConfigurationBootstrap

brokers

Per-broker configurations.

GenericKafkaListenerConfigurationBroker array

ipFamilyPolicy

Specifies the IP Family Policy used by the service. Available options are SingleStack, PreferDualStack and RequireDualStack. SingleStack is for a single IP family. PreferDualStack is for two IP families on dual-stack configured clusters or a single IP family on single-stack clusters. RequireDualStack fails unless there are two IP families on dual-stack configured clusters. If unspecified, Kubernetes will choose the default value based on the service type. Available on Kubernetes 1.20 and newer.

string (one of [RequireDualStack, SingleStack, PreferDualStack])

ipFamilies

Specifies the IP Families used by the service. Available options are IPv4 and IPv6. If unspecified, Kubernetes will choose the default value based on the `ipFamilyPolicy setting. Available on Kubernetes 1.20 and newer.

string (one or more of [IPv6, IPv4]) array

createBootstrapService

Whether to create the bootstrap service or not. The bootstrap service is created by default (if not specified differently). This field can be used with the loadBalancer type listener.

boolean

class

Configures a specific class for Ingress and LoadBalancer that defines which controller will be used. This field can only be used with ingress and loadbalancer type listeners. If not specified, the default controller is used. For an ingress listener, set the ingressClassName property in the Ingress resources. For a loadbalancer listener, set the loadBalancerClass property in the Service resources.

string

finalizers

A list of finalizers which will be configured for the LoadBalancer type Services created for this listener. If supported by the platform, the finalizer service.kubernetes.io/load-balancer-cleanup to make sure that the external load balancer is deleted together with the service.For more information, see https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#garbage-collecting-load-balancers. This field can be used only with loadbalancer type listeners.

string array

maxConnectionCreationRate

The maximum connection creation rate we allow in this listener at any time. New connections will be throttled if the limit is reached.

integer

maxConnections

The maximum number of connections we allow for this listener in the broker at any time. New connections are blocked if the limit is reached.

integer

preferredNodePortAddressType

Defines which address type should be used as the node address. Available types are: ExternalDNS, ExternalIP, InternalDNS, InternalIP and Hostname. By default, the addresses will be used in the following order (the first one found will be used):

  • ExternalDNS

  • ExternalIP

  • InternalDNS

  • InternalIP

  • Hostname

This field is used to select the preferred address type, which is checked first. If no address is found for this address type, the other types are checked in the default order. This field can only be used with nodeport type listener.

string (one of [ExternalDNS, ExternalIP, Hostname, InternalIP, InternalDNS])

useServiceDnsDomain

Configures whether the Kubernetes service DNS domain should be used or not. If set to true, the generated addresses will contain the service DNS domain suffix (by default .cluster.local, can be configured using environment variable KUBERNETES_SERVICE_DNS_DOMAIN). Defaults to false.This field can be used only with internal and cluster-ip type listeners.

boolean

9.2.12. CertAndKeySecretSource schema reference

Property Description

certificate

The name of the file certificate in the Secret.

string

key

The name of the private key in the Secret.

string

secretName

The name of the Secret containing the certificate.

string

9.2.13. GenericKafkaListenerConfigurationBootstrap schema reference

Broker service equivalents of nodePort, host, loadBalancerIP and annotations properties are configured in the GenericKafkaListenerConfigurationBroker schema.

alternativeNames

You can specify alternative names for the bootstrap service. The names are added to the broker certificates and can be used for TLS hostname verification. The alternativeNames property is applicable to all types of listeners.

Example of an external route listener configured with an additional bootstrap address
listeners:
  #...
  - name: external
    port: 9094
    type: route
    tls: true
    authentication:
      type: tls
    configuration:
      bootstrap:
        alternativeNames:
          - example.hostname1
          - example.hostname2
# ...
host

The host property is used with route and ingress listeners to specify the hostnames used by the bootstrap and per-broker services.

A host property value is mandatory for ingress listener configuration, as the Ingress controller does not assign any hostnames automatically. Make sure that the hostnames resolve to the Ingress endpoints. Strimzi will not perform any validation that the requested hosts are available and properly routed to the Ingress endpoints.

Example of host configuration for an ingress listener
listeners:
  #...
  - name: external
    port: 9094
    type: ingress
    tls: true
    authentication:
      type: tls
    configuration:
      bootstrap:
        host: bootstrap.myingress.com
      brokers:
      - broker: 0
        host: broker-0.myingress.com
      - broker: 1
        host: broker-1.myingress.com
      - broker: 2
        host: broker-2.myingress.com
# ...

By default, route listener hosts are automatically assigned by OpenShift. However, you can override the assigned route hosts by specifying hosts.

Strimzi does not perform any validation that the requested hosts are available. You must ensure that they are free and can be used.

Example of host configuration for a route listener
# ...
listeners:
  #...
  - name: external
    port: 9094
    type: route
    tls: true
    authentication:
      type: tls
    configuration:
      bootstrap:
        host: bootstrap.myrouter.com
      brokers:
      - broker: 0
        host: broker-0.myrouter.com
      - broker: 1
        host: broker-1.myrouter.com
      - broker: 2
        host: broker-2.myrouter.com
# ...
nodePort

By default, the port numbers used for the bootstrap and broker services are automatically assigned by Kubernetes. You can override the assigned node ports for nodeport listeners by specifying the requested port numbers.

Strimzi does not perform any validation on the requested ports. You must ensure that they are free and available for use.

Example of an external listener configured with overrides for node ports
# ...
listeners:
  #...
  - name: external
    port: 9094
    type: nodeport
    tls: true
    authentication:
      type: tls
    configuration:
      bootstrap:
        nodePort: 32100
      brokers:
      - broker: 0
        nodePort: 32000
      - broker: 1
        nodePort: 32001
      - broker: 2
        nodePort: 32002
# ...
loadBalancerIP

Use the loadBalancerIP property to request a specific IP address when creating a loadbalancer. Use this property when you need to use a loadbalancer with a specific IP address. The loadBalancerIP field is ignored if the cloud provider does not support the feature.

Example of an external listener of type loadbalancer with specific loadbalancer IP address requests
# ...
listeners:
  #...
  - name: external
    port: 9094
    type: loadbalancer
    tls: true
    authentication:
      type: tls
    configuration:
      bootstrap:
        loadBalancerIP: 172.29.3.10
      brokers:
      - broker: 0
        loadBalancerIP: 172.29.3.1
      - broker: 1
        loadBalancerIP: 172.29.3.2
      - broker: 2
        loadBalancerIP: 172.29.3.3
# ...
annotations

Use the annotations property to add annotations to Kubernetes resources related to the listeners. You can use these annotations, for example, to instrument DNS tooling such as External DNS, which automatically assigns DNS names to the loadbalancer services.

Example of an external listener of type loadbalancer using annotations
# ...
listeners:
  #...
  - name: external
    port: 9094
    type: loadbalancer
    tls: true
    authentication:
      type: tls
    configuration:
      bootstrap:
        annotations:
          external-dns.alpha.kubernetes.io/hostname: kafka-bootstrap.mydomain.com.
          external-dns.alpha.kubernetes.io/ttl: "60"
      brokers:
      - broker: 0
        annotations:
          external-dns.alpha.kubernetes.io/hostname: kafka-broker-0.mydomain.com.
          external-dns.alpha.kubernetes.io/ttl: "60"
      - broker: 1
        annotations:
          external-dns.alpha.kubernetes.io/hostname: kafka-broker-1.mydomain.com.
          external-dns.alpha.kubernetes.io/ttl: "60"
      - broker: 2
        annotations:
          external-dns.alpha.kubernetes.io/hostname: kafka-broker-2.mydomain.com.
          external-dns.alpha.kubernetes.io/ttl: "60"
# ...
GenericKafkaListenerConfigurationBootstrap schema properties
Property Description

alternativeNames

Additional alternative names for the bootstrap service. The alternative names will be added to the list of subject alternative names of the TLS certificates.

string array

host

The bootstrap host. This field will be used in the Ingress resource or in the Route resource to specify the desired hostname. This field can be used only with route (optional) or ingress (required) type listeners.

string

nodePort

Node port for the bootstrap service. This field can be used only with nodeport type listener.

integer

loadBalancerIP

The loadbalancer is requested with the IP address specified in this field. This feature depends on whether the underlying cloud provider supports specifying the loadBalancerIP when a load balancer is created. This field is ignored if the cloud provider does not support the feature.This field can be used only with loadbalancer type listener.

string

annotations

Annotations that will be added to the Ingress, Route, or Service resource. You can use this field to configure DNS providers such as External DNS. This field can be used only with loadbalancer, nodeport, route, or ingress type listeners.

map

labels

Labels that will be added to the Ingress, Route, or Service resource. This field can be used only with loadbalancer, nodeport, route, or ingress type listeners.

map

9.2.14. GenericKafkaListenerConfigurationBroker schema reference

You can see example configuration for the nodePort, host, loadBalancerIP and annotations properties in the GenericKafkaListenerConfigurationBootstrap schema, which configures bootstrap service overrides.

Advertised addresses for brokers

By default, Strimzi tries to automatically determine the hostnames and ports that your Kafka cluster advertises to its clients. This is not sufficient in all situations, because the infrastructure on which Strimzi is running might not provide the right hostname or port through which Kafka can be accessed.

You can specify a broker ID and customize the advertised hostname and port in the configuration property of the listener. Strimzi will then automatically configure the advertised address in the Kafka brokers and add it to the broker certificates so it can be used for TLS hostname verification. Overriding the advertised host and ports is available for all types of listeners.

Example of an external route listener configured with overrides for advertised addresses
listeners:
  #...
  - name: external
    port: 9094
    type: route
    tls: true
    authentication:
      type: tls
    configuration:
      brokers:
      - broker: 0
        advertisedHost: example.hostname.0
        advertisedPort: 12340
      - broker: 1
        advertisedHost: example.hostname.1
        advertisedPort: 12341
      - broker: 2
        advertisedHost: example.hostname.2
        advertisedPort: 12342
# ...
GenericKafkaListenerConfigurationBroker schema properties
Property Description

broker

ID of the kafka broker (broker identifier). Broker IDs start from 0 and correspond to the number of broker replicas.

integer

advertisedHost

The host name which will be used in the brokers' advertised.brokers.

string

advertisedPort

The port number which will be used in the brokers' advertised.brokers.

integer

host

The broker host. This field will be used in the Ingress resource or in the Route resource to specify the desired hostname. This field can be used only with route (optional) or ingress (required) type listeners.

string

nodePort

Node port for the per-broker service. This field can be used only with nodeport type listener.

integer

loadBalancerIP

The loadbalancer is requested with the IP address specified in this field. This feature depends on whether the underlying cloud provider supports specifying the loadBalancerIP when a load balancer is created. This field is ignored if the cloud provider does not support the feature.This field can be used only with loadbalancer type listener.

string

annotations

Annotations that will be added to the Ingress or Service resource. You can use this field to configure DNS providers such as External DNS. This field can be used only with loadbalancer, nodeport, or ingress type listeners.

map

labels

Labels that will be added to the Ingress, Route, or Service resource. This field can be used only with loadbalancer, nodeport, route, or ingress type listeners.

map

9.2.15. EphemeralStorage schema reference

The type property is a discriminator that distinguishes use of the EphemeralStorage type from PersistentClaimStorage. It must have the value ephemeral for the type EphemeralStorage.

Property Description

id

Storage identification number. It is mandatory only for storage volumes defined in a storage of type 'jbod'.

integer

sizeLimit

When type=ephemeral, defines the total amount of local storage required for this EmptyDir volume (for example 1Gi).

string

type

Must be ephemeral.

string

9.2.16. PersistentClaimStorage schema reference

The type property is a discriminator that distinguishes use of the PersistentClaimStorage type from EphemeralStorage. It must have the value persistent-claim for the type PersistentClaimStorage.

Property Description

type

Must be persistent-claim.

string

size

When type=persistent-claim, defines the size of the persistent volume claim (i.e 1Gi). Mandatory when type=persistent-claim.

string

selector

Specifies a specific persistent volume to use. It contains key:value pairs representing labels for selecting such a volume.

map

deleteClaim

Specifies if the persistent volume claim has to be deleted when the cluster is un-deployed.

boolean

class

The storage class to use for dynamic volume allocation.

string

id

Storage identification number. It is mandatory only for storage volumes defined in a storage of type 'jbod'.

integer

overrides

Overrides for individual brokers. The overrides field allows to specify a different configuration for different brokers.

PersistentClaimStorageOverride array

9.2.17. PersistentClaimStorageOverride schema reference

Property Description

class

The storage class to use for dynamic volume allocation for this broker.

string

broker

Id of the kafka broker (broker identifier).

integer

9.2.18. JbodStorage schema reference

Used in: KafkaClusterSpec

The type property is a discriminator that distinguishes use of the JbodStorage type from EphemeralStorage, PersistentClaimStorage. It must have the value jbod for the type JbodStorage.

Property Description

type

Must be jbod.

string

volumes

List of volumes as Storage objects representing the JBOD disks array.

EphemeralStorage, PersistentClaimStorage array

9.2.19. KafkaAuthorizationSimple schema reference

Used in: KafkaClusterSpec

Simple authorization in Strimzi uses the AclAuthorizer plugin, the default Access Control Lists (ACLs) authorization plugin provided with Apache Kafka. ACLs allow you to define which users have access to which resources at a granular level.

Configure the Kafka custom resource to use simple authorization. Set the type property in the authorization section to the value simple, and configure a list of super users.

Access rules are configured for the KafkaUser, as described in the ACLRule schema reference.

superUsers

A list of user principals treated as super users, so that they are always allowed without querying ACL rules.

An example of simple authorization configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
  namespace: myproject
spec:
  kafka:
    # ...
    authorization:
      type: simple
      superUsers:
        - CN=client_1
        - user_2
        - CN=client_3
    # ...
Note
The super.user configuration option in the config property in Kafka.spec.kafka is ignored. Designate super users in the authorization property instead. For more information, see Kafka broker configuration.
KafkaAuthorizationSimple schema properties

The type property is a discriminator that distinguishes use of the KafkaAuthorizationSimple type from KafkaAuthorizationOpa, KafkaAuthorizationKeycloak, KafkaAuthorizationCustom. It must have the value simple for the type KafkaAuthorizationSimple.

Property Description

type

Must be simple.

string

superUsers

List of super users. Should contain list of user principals which should get unlimited access rights.

string array

9.2.20. KafkaAuthorizationOpa schema reference

Used in: KafkaClusterSpec

To use Open Policy Agent authorization, set the type property in the authorization section to the value opa, and configure OPA properties as required. Strimzi uses Open Policy Agent plugin for Kafka authorization as the authorizer. For more information about the format of the input data and policy examples, see Open Policy Agent plugin for Kafka authorization.

url

The URL used to connect to the Open Policy Agent server. The URL has to include the policy which will be queried by the authorizer. Required.

allowOnError

Defines whether a Kafka client should be allowed or denied by default when the authorizer fails to query the Open Policy Agent, for example, when it is temporarily unavailable. Defaults to false - all actions will be denied.

initialCacheCapacity

Initial capacity of the local cache used by the authorizer to avoid querying the Open Policy Agent for every request. Defaults to 5000.

maximumCacheSize

Maximum capacity of the local cache used by the authorizer to avoid querying the Open Policy Agent for every request. Defaults to 50000.

expireAfterMs

The expiration of the records kept in the local cache to avoid querying the Open Policy Agent for every request. Defines how often the cached authorization decisions are reloaded from the Open Policy Agent server. In milliseconds. Defaults to 3600000 milliseconds (1 hour).

tlsTrustedCertificates

Trusted certificates for TLS connection to the OPA server.

superUsers

A list of user principals treated as super users, so that they are always allowed without querying the open Policy Agent policy.

An example of Open Policy Agent authorizer configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
  namespace: myproject
spec:
  kafka:
    # ...
    authorization:
      type: opa
      url: http://opa:8181/v1/data/kafka/allow
      allowOnError: false
      initialCacheCapacity: 1000
      maximumCacheSize: 10000
      expireAfterMs: 60000
      superUsers:
        - CN=fred
        - sam
        - CN=edward
    # ...
KafkaAuthorizationOpa schema properties

The type property is a discriminator that distinguishes use of the KafkaAuthorizationOpa type from KafkaAuthorizationSimple, KafkaAuthorizationKeycloak, KafkaAuthorizationCustom. It must have the value opa for the type KafkaAuthorizationOpa.

Property Description

type

Must be opa.

string

url

The URL used to connect to the Open Policy Agent server. The URL has to include the policy which will be queried by the authorizer. This option is required.

string

allowOnError

Defines whether a Kafka client should be allowed or denied by default when the authorizer fails to query the Open Policy Agent, for example, when it is temporarily unavailable). Defaults to false - all actions will be denied.

boolean

initialCacheCapacity

Initial capacity of the local cache used by the authorizer to avoid querying the Open Policy Agent for every request Defaults to 5000.

integer

maximumCacheSize

Maximum capacity of the local cache used by the authorizer to avoid querying the Open Policy Agent for every request. Defaults to 50000.

integer

expireAfterMs

The expiration of the records kept in the local cache to avoid querying the Open Policy Agent for every request. Defines how often the cached authorization decisions are reloaded from the Open Policy Agent server. In milliseconds. Defaults to 3600000.

integer

tlsTrustedCertificates

Trusted certificates for TLS connection to the OPA server.

CertSecretSource array

superUsers

List of super users, which is specifically a list of user principals that have unlimited access rights.

string array

enableMetrics

Defines whether the Open Policy Agent authorizer plugin should provide metrics. Defaults to false.

boolean

9.2.21. KafkaAuthorizationKeycloak schema reference

Used in: KafkaClusterSpec

The type property is a discriminator that distinguishes use of the KafkaAuthorizationKeycloak type from KafkaAuthorizationSimple, KafkaAuthorizationOpa, KafkaAuthorizationCustom. It must have the value keycloak for the type KafkaAuthorizationKeycloak.

Property Description

type

Must be keycloak.

string

clientId

OAuth Client ID which the Kafka client can use to authenticate against the OAuth server and use the token endpoint URI.

string

tokenEndpointUri

Authorization server token endpoint URI.

string

tlsTrustedCertificates

Trusted certificates for TLS connection to the OAuth server.

CertSecretSource array

disableTlsHostnameVerification

Enable or disable TLS hostname verification. Default value is false.

boolean

delegateToKafkaAcls

Whether authorization decision should be delegated to the 'Simple' authorizer if DENIED by Keycloak Authorization Services policies. Default value is false.

boolean

grantsRefreshPeriodSeconds

The time between two consecutive grants refresh runs in seconds. The default value is 60.

integer

grantsRefreshPoolSize

The number of threads to use to refresh grants for active sessions. The more threads, the more parallelism, so the sooner the job completes. However, using more threads places a heavier load on the authorization server. The default value is 5.

integer

superUsers

List of super users. Should contain list of user principals which should get unlimited access rights.

string array

connectTimeoutSeconds

The connect timeout in seconds when connecting to authorization server. If not set, the effective connect timeout is 60 seconds.

integer

readTimeoutSeconds

The read timeout in seconds when connecting to authorization server. If not set, the effective read timeout is 60 seconds.

integer

enableMetrics

Enable or disable OAuth metrics. Default value is false.

boolean

9.2.22. KafkaAuthorizationCustom schema reference

Used in: KafkaClusterSpec

To use custom authorization in Strimzi, you can configure your own Authorizer plugin to define Access Control Lists (ACLs).

ACLs allow you to define which users have access to which resources at a granular level.

Configure the Kafka custom resource to use custom authorization. Set the type property in the authorization section to the value custom, and the set following properties.

Important
The custom authorizer must implement the org.apache.kafka.server.authorizer.Authorizer interface, and support configuration of super.users using the super.users configuration property.
authorizerClass

(Required) Java class that implements the org.apache.kafka.server.authorizer.Authorizer interface to support custom ACLs.

superUsers

A list of user principals treated as super users, so that they are always allowed without querying ACL rules.

You can add configuration for initializing the custom authorizer using Kafka.spec.kafka.config.

An example of custom authorization configuration under Kafka.spec
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
  namespace: myproject
spec:
  kafka:
    # ...
    authorization:
      type: custom
      authorizerClass: io.mycompany.CustomAuthorizer
      superUsers:
        - CN=client_1
        - user_2
        - CN=client_3
    # ...
    config:
      authorization.custom.property1=value1
      authorization.custom.property2=value2
    # ...

In addition to the Kafka custom resource configuration, the JAR file containing the custom authorizer class along with its dependencies must be available on the classpath of the Kafka broker.

The Strimzi Maven build process provides a mechanism to add custom third-party libraries to the generated Kafka broker container image by adding them as dependencies in the pom.xml file under the docker-images/kafka/kafka-thirdparty-libs directory. The directory contains different folders for different Kafka versions. Choose the appropriate folder. Before modifying the pom.xml file, the third-party library must be available in a Maven repository, and that Maven repository must be accessible to the Strimzi build process.

Note
The super.user configuration option in the config property in Kafka.spec.kafka is ignored. Designate super users in the authorization property instead. For more information, see Kafka broker configuration.

Custom authorization can make use of group membership information extracted from the JWT token during authentication when using oauth authentication and configuring groupsClaim configuration attribute. Groups are available on the OAuthKafkaPrincipal object during authorize() call as follows:

    public List<AuthorizationResult> authorize(AuthorizableRequestContext requestContext, List<Action> actions) {

        KafkaPrincipal principal = requestContext.principal();
        if (principal instanceof OAuthKafkaPrincipal) {
            OAuthKafkaPrincipal p = (OAuthKafkaPrincipal) principal;

            for (String group: p.getGroups()) {
                System.out.println("Group: " + group);
            }
        }
    }
KafkaAuthorizationCustom schema properties

The type property is a discriminator that distinguishes use of the KafkaAuthorizationCustom type from KafkaAuthorizationSimple, KafkaAuthorizationOpa, KafkaAuthorizationKeycloak. It must have the value custom for the type KafkaAuthorizationCustom.

Property Description

type

Must be custom.

string

authorizerClass

Authorization implementation class, which must be available in classpath.

string

superUsers

List of super users, which are user principals with unlimited access rights.

string array

supportsAdminApi

Indicates whether the custom authorizer supports the APIs for managing ACLs using the Kafka Admin API. Defaults to false.

boolean

9.2.23. Rack schema reference

The rack option configures rack awareness. A rack can represent an availability zone, data center, or an actual rack in your data center. The rack is configured through a topologyKey. topologyKey identifies a label on Kubernetes nodes that contains the name of the topology in its value. An example of such a label is topology.kubernetes.io/zone (or failure-domain.beta.kubernetes.io/zone on older Kubernetes versions), which contains the name of the availability zone in which the Kubernetes node runs. You can configure your Kafka cluster to be aware of the rack in which it runs, and enable additional features such as spreading partition replicas across different racks or consuming messages from the closest replicas.

For more information about Kubernetes node labels, see Well-Known Labels, Annotations and Taints. Consult your Kubernetes administrator regarding the node label that represents the zone or rack into which the node is deployed.

Spreading partition replicas across racks

When rack awareness is configured, Strimzi will set broker.rack configuration for each Kafka broker. The broker.rack configuration assigns a rack ID to each broker. When broker.rack is configured, Kafka brokers will spread partition replicas across as many different racks as possible. When replicas are spread across multiple racks, the probability that multiple replicas will fail at the same time is lower than if they would be in the same rack. Spreading replicas improves resiliency, and is important for availability and reliability. To enable rack awareness in Kafka, add the rack option to the .spec.kafka section of the Kafka custom resource as shown in the example below.

Example rack configuration for Kafka
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    rack:
      topologyKey: topology.kubernetes.io/zone
    # ...
Note
The rack in which brokers are running can change in some cases when the pods are deleted or restarted. As a result, the replicas running in different racks might then share the same rack. Use Cruise Control and the KafkaRebalance resource with the RackAwareGoal to make sure that replicas remain distributed across different racks.

When rack awareness is enabled in the Kafka custom resource, Strimzi will automatically add the Kubernetes preferredDuringSchedulingIgnoredDuringExecution affinity rule to distribute the Kafka brokers across the different racks. However, the preferred rule does not guarantee that the brokers will be spread. Depending on your exact Kubernetes and Kafka configurations, you should add additional affinity rules or configure topologySpreadConstraints for both ZooKeeper and Kafka to make sure the nodes are properly distributed accross as many racks as possible. For more information see Configuring pod scheduling.

Consuming messages from the closest replicas

Rack awareness can also be used in consumers to fetch data from the closest replica. This is useful for reducing the load on your network when a Kafka cluster spans multiple datacenters and can also reduce costs when running Kafka in public clouds. However, it can lead to increased latency.

In order to be able to consume from the closest replica, rack awareness has to be configured in the Kafka cluster, and the RackAwareReplicaSelector has to be enabled. The replica selector plugin provides the logic that enables clients to consume from the nearest replica. The default implementation uses LeaderSelector to always select the leader replica for the client. Specify RackAwareReplicaSelector for the replica.selector.class to switch from the default implementation.

Example rack configuration with enabled replica-aware selector
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    rack:
      topologyKey: topology.kubernetes.io/zone
    config:
      # ...
      replica.selector.class: org.apache.kafka.common.replica.RackAwareReplicaSelector
    # ...

In addition to the Kafka broker configuration, you also need to specify the client.rack option in your consumers. The client.rack option should specify the rack ID in which the consumer is running. RackAwareReplicaSelector associates matching broker.rack and client.rack IDs, to find the nearest replica and consume from it. If there are multiple replicas in the same rack, RackAwareReplicaSelector always selects the most up-to-date replica. If the rack ID is not specified, or if it cannot find a replica with the same rack ID, it will fall back to the leader replica.

consuming from replicas in the same availability zone
Figure 4. Example showing client consuming from replicas in the same availability zone

You can also configure Kafka Connect, MirrorMaker 2.0 and Kafka Bridge so that connectors consume messages from the closest replicas. You enable rack awareness in the KafkaConnect, KafkaMirrorMaker2, and KafkaBridge custom resources. The configuration does does not set affinity rules, but you can also configure affinity or topologySpreadConstraints. For more information see Configuring pod scheduling.

When deploying Kafka Connect using Strimzi, you can use the rack section in the KafkaConnect custom resource to automatically configure the client.rack option.

Example rack configuration for Kafka Connect
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
# ...
spec:
  # ...
  rack:
    topologyKey: topology.kubernetes.io/zone
  # ...

When deploying MirrorMaker 2 using Strimzi, you can use the rack section in the KafkaMirrorMaker2 custom resource to automatically configure the client.rack option.

Example rack configuration for MirrorMaker 2.0
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
# ...
spec:
  # ...
  rack:
    topologyKey: topology.kubernetes.io/zone
  # ...

When deploying Kafka Bridge using Strimzi, you can use the rack section in the KafkaBridge custom resource to automatically configure the client.rack option.

Example rack configuration for Kafka Bridge
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
# ...
spec:
  # ...
  rack:
    topologyKey: topology.kubernetes.io/zone
  # ...
Rack schema properties
Property Description

topologyKey

A key that matches labels assigned to the Kubernetes cluster nodes. The value of the label is used to set a broker’s broker.rack config, and the client.rack config for Kafka Connect or MirrorMaker 2.0.

string

9.2.24. Probe schema reference

Property Description

failureThreshold

Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.

integer

initialDelaySeconds

The initial delay before first the health is first checked. Default to 15 seconds. Minimum value is 0.

integer

periodSeconds

How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.

integer

successThreshold

Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness. Minimum value is 1.

integer

timeoutSeconds

The timeout for each attempted health check. Default to 5 seconds. Minimum value is 1.

integer

9.2.25. JvmOptions schema reference

Property Description

-XX

A map of -XX options to the JVM.

map

-Xms

-Xms option to to the JVM.

string

-Xmx

-Xmx option to to the JVM.

string

gcLoggingEnabled

Specifies whether the Garbage Collection logging is enabled. The default is false.

boolean

javaSystemProperties

A map of additional system properties which will be passed using the -D option to the JVM.

SystemProperty array

9.2.26. SystemProperty schema reference

Used in: JvmOptions

Property Description

name

The system property name.

string

value

The system property value.

string

9.2.27. KafkaJmxOptions schema reference

Configures JMX connection options.

Get JMX metrics from Kafka brokers, ZooKeeper nodes, Kafka Connect, and MirrorMaker 2.0. by connecting to port 9999. Use the jmxOptions property to configure a password-protected or an unprotected JMX port. Using password protection prevents unauthorized pods from accessing the port.

You can then obtain metrics about the component.

For example, for each Kafka broker you can obtain bytes-per-second usage data from clients, or the request rate of the network of the broker.

To enable security for the JMX port, set the type parameter in the authentication field to password.

Example password-protected JMX configuration for Kafka brokers and ZooKeeper nodes
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    jmxOptions:
      authentication:
        type: "password"
    # ...
  zookeeper:
    # ...
    jmxOptions:
      authentication:
        type: "password"
    #...

You can then deploy a pod into a cluster and obtain JMX metrics using the headless service by specifying which broker you want to address.

For example, to get JMX metrics from broker 0 you specify:

"CLUSTER-NAME-kafka-0.CLUSTER-NAME-kafka-brokers"

CLUSTER-NAME-kafka-0 is name of the broker pod, and CLUSTER-NAME-kafka-brokers is the name of the headless service to return the IPs of the broker pods.

If the JMX port is secured, you can get the username and password by referencing them from the JMX Secret in the deployment of your pod.

For an unprotected JMX port, use an empty object {} to open the JMX port on the headless service. You deploy a pod and obtain metrics in the same way as for the protected port, but in this case any pod can read from the JMX port.

Example open port JMX configuration for Kafka brokers and ZooKeeper nodes
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    jmxOptions: {}
    # ...
  zookeeper:
    # ...
    jmxOptions: {}
    # ...
Additional resources
KafkaJmxOptions schema properties
Property Description

authentication

Authentication configuration for connecting to the JMX port. The type depends on the value of the authentication.type property within the given object, which must be one of [password].

KafkaJmxAuthenticationPassword

9.2.28. KafkaJmxAuthenticationPassword schema reference

Used in: KafkaJmxOptions

The type property is a discriminator that distinguishes use of the KafkaJmxAuthenticationPassword type from other subtypes which may be added in the future. It must have the value password for the type KafkaJmxAuthenticationPassword.

Property Description

type

Must be password.

string

9.2.29. JmxPrometheusExporterMetrics schema reference

The type property is a discriminator that distinguishes use of the JmxPrometheusExporterMetrics type from other subtypes which may be added in the future. It must have the value jmxPrometheusExporter for the type JmxPrometheusExporterMetrics.

Property Description

type

Must be jmxPrometheusExporter.

string

valueFrom

ConfigMap entry where the Prometheus JMX Exporter configuration is stored. For details of the structure of this configuration, see the Prometheus JMX Exporter.

ExternalConfigurationReference

9.2.30. ExternalConfigurationReference schema reference

Property Description

configMapKeyRef

Reference to the key in the ConfigMap containing the configuration. For more information, see the external documentation for core/v1 configmapkeyselector.

ConfigMapKeySelector

9.2.31. InlineLogging schema reference

The type property is a discriminator that distinguishes use of the InlineLogging type from ExternalLogging. It must have the value inline for the type InlineLogging.

Property Description

type

Must be inline.

string

loggers

A Map from logger name to logger level.

map

9.2.32. ExternalLogging schema reference

The type property is a discriminator that distinguishes use of the ExternalLogging type from InlineLogging. It must have the value external for the type ExternalLogging.

Property Description

type

Must be external.

string

valueFrom

ConfigMap entry where the logging configuration is stored.

ExternalConfigurationReference

9.2.33. KafkaClusterTemplate schema reference

Used in: KafkaClusterSpec

Property Description

statefulset

Template for Kafka StatefulSet.

StatefulSetTemplate

pod

Template for Kafka Pods.

PodTemplate

bootstrapService

Template for Kafka bootstrap Service.

InternalServiceTemplate

brokersService

Template for Kafka broker Service.

InternalServiceTemplate

externalBootstrapService

Template for Kafka external bootstrap Service.

ResourceTemplate

perPodService

Template for Kafka per-pod Services used for access from outside of Kubernetes.

ResourceTemplate

externalBootstrapRoute

Template for Kafka external bootstrap Route.

ResourceTemplate

perPodRoute

Template for Kafka per-pod Routes used for access from outside of OpenShift.

ResourceTemplate

externalBootstrapIngress

Template for Kafka external bootstrap Ingress.

ResourceTemplate

perPodIngress

Template for Kafka per-pod Ingress used for access from outside of Kubernetes.

ResourceTemplate

persistentVolumeClaim

Template for all Kafka PersistentVolumeClaims.

ResourceTemplate

podDisruptionBudget

Template for Kafka PodDisruptionBudget.

PodDisruptionBudgetTemplate

kafkaContainer

Template for the Kafka broker container.

ContainerTemplate

initContainer

Template for the Kafka init container.

ContainerTemplate

clusterCaCert

Template for Secret with Kafka Cluster certificate public key.

ResourceTemplate

serviceAccount

Template for the Kafka service account.

ResourceTemplate

jmxSecret

Template for Secret of the Kafka Cluster JMX authentication.

ResourceTemplate

clusterRoleBinding

Template for the Kafka ClusterRoleBinding.

ResourceTemplate

podSet

Template for Kafka StrimziPodSet resource.

ResourceTemplate

9.2.34. StatefulSetTemplate schema reference

Property Description

metadata

Metadata applied to the resource.

MetadataTemplate

podManagementPolicy

PodManagementPolicy which will be used for this StatefulSet. Valid values are Parallel and OrderedReady. Defaults to Parallel.

string (one of [OrderedReady, Parallel])

9.2.35. MetadataTemplate schema reference

Labels and Annotations are used to identify and organize resources, and are configured in the metadata property.

For example:

# ...
template:
  pod:
    metadata:
      labels:
        label1: value1
        label2: value2
      annotations:
        annotation1: value1
        annotation2: value2
# ...

The labels and annotations fields can contain any labels or annotations that do not contain the reserved string strimzi.io. Labels and annotations containing strimzi.io are used internally by Strimzi and cannot be configured.

MetadataTemplate schema properties
Property Description

labels

Labels added to the resource template. Can be applied to different resources such as StatefulSets, Deployments, Pods, and Services.

map

annotations

Annotations added to the resource template. Can be applied to different resources such as StatefulSets, Deployments, Pods, and Services.

map

9.2.36. PodTemplate schema reference

Configures the template for Kafka pods.

Example PodTemplate configuration
# ...
template:
  pod:
    metadata:
      labels:
        label1: value1
      annotations:
        anno1: value1
    imagePullSecrets:
      - name: my-docker-credentials
    securityContext:
      runAsUser: 1000001
      fsGroup: 0
    terminationGracePeriodSeconds: 120
# ...
hostAliases

Use the hostAliases property to a specify a list of hosts and IP addresses, which are injected into the /etc/hosts file of the pod.

This configuration is especially useful for Kafka Connect or MirrorMaker when a connection outside of the cluster is also requested by users.

Example hostAliases configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
#...
spec:
  # ...
  template:
    pod:
      hostAliases:
      - ip: "192.168.1.86"
        hostnames:
        - "my-host-1"
        - "my-host-2"
      #...
PodTemplate schema properties
Property Description

metadata

Metadata applied to the resource.

MetadataTemplate

imagePullSecrets

List of references to secrets in the same namespace to use for pulling any of the images used by this Pod. When the STRIMZI_IMAGE_PULL_SECRETS environment variable in Cluster Operator and the imagePullSecrets option are specified, only the imagePullSecrets variable is used and the STRIMZI_IMAGE_PULL_SECRETS variable is ignored. For more information, see the external documentation for core/v1 localobjectreference.

LocalObjectReference array

securityContext

Configures pod-level security attributes and common container settings. For more information, see the external documentation for core/v1 podsecuritycontext.

PodSecurityContext

terminationGracePeriodSeconds

The grace period is the duration in seconds after the processes running in the pod are sent a termination signal, and the time when the processes are forcibly halted with a kill signal. Set this value to longer than the expected cleanup time for your process. Value must be a non-negative integer. A zero value indicates delete immediately. You might need to increase the grace period for very large Kafka clusters, so that the Kafka brokers have enough time to transfer their work to another broker before they are terminated. Defaults to 30 seconds.

integer

affinity

The pod’s affinity rules. For more information, see the external documentation for core/v1 affinity.

Affinity

tolerations

The pod’s tolerations. For more information, see the external documentation for core/v1 toleration.

Toleration array

priorityClassName

The name of the priority class used to assign priority to the pods. For more information about priority classes, see Pod Priority and Preemption.

string

schedulerName

The name of the scheduler used to dispatch this Pod. If not specified, the default scheduler will be used.

string

hostAliases

The pod’s HostAliases. HostAliases is an optional list of hosts and IPs that will be injected into the Pod’s hosts file if specified. For more information, see the external documentation for core/v1 hostalias.

HostAlias array

tmpDirSizeLimit

Defines the total amount (for example 1Gi) of local storage required for temporary EmptyDir volume (/tmp). Default value is 5Mi.

string

enableServiceLinks

Indicates whether information about services should be injected into Pod’s environment variables.

boolean

topologySpreadConstraints

The pod’s topology spread constraints. For more information, see the external documentation for core/v1 topologyspreadconstraint.

TopologySpreadConstraint array

9.2.37. InternalServiceTemplate schema reference

Property Description

metadata

Metadata applied to the resource.

MetadataTemplate

ipFamilyPolicy

Specifies the IP Family Policy used by the service. Available options are SingleStack, PreferDualStack and RequireDualStack. SingleStack is for a single IP family. PreferDualStack is for two IP families on dual-stack configured clusters or a single IP family on single-stack clusters. RequireDualStack fails unless there are two IP families on dual-stack configured clusters. If unspecified, Kubernetes will choose the default value based on the service type. Available on Kubernetes 1.20 and newer.

string (one of [RequireDualStack, SingleStack, PreferDualStack])

ipFamilies

Specifies the IP Families used by the service. Available options are IPv4 and IPv6. If unspecified, Kubernetes will choose the default value based on the `ipFamilyPolicy setting. Available on Kubernetes 1.20 and newer.

string (one or more of [IPv6, IPv4]) array

9.2.39. PodDisruptionBudgetTemplate schema reference

Strimzi creates a PodDisruptionBudget for every new StatefulSet or Deployment. By default, pod disruption budgets only allow a single pod to be unavailable at a given time. You can increase the amount of unavailable pods allowed by changing the default value of the maxUnavailable property.

An example of PodDisruptionBudget template
# ...
template:
  podDisruptionBudget:
    metadata:
      labels:
        key1: label1
        key2: label2
      annotations:
        key1: label1
        key2: label2
    maxUnavailable: 1
# ...
PodDisruptionBudgetTemplate schema properties
Property Description

metadata

Metadata to apply to the PodDisruptionBudgetTemplate resource.

MetadataTemplate

maxUnavailable

Maximum number of unavailable pods to allow automatic Pod eviction. A Pod eviction is allowed when the maxUnavailable number of pods or fewer are unavailable after the eviction. Setting this value to 0 prevents all voluntary evictions, so the pods must be evicted manually. Defaults to 1.

integer

9.2.40. ContainerTemplate schema reference

You can set custom security context and environment variables for a container.

The environment variables are defined under the env property as a list of objects with name and value fields. The following example shows two custom environment variables and a custom security context set for the Kafka broker containers:

# ...
template:
  kafkaContainer:
    env:
    - name: EXAMPLE_ENV_1
      value: example.env.one
    - name: EXAMPLE_ENV_2
      value: example.env.two
    securityContext:
      runAsUser: 2000
# ...

Environment variables prefixed with KAFKA_ are internal to Strimzi and should be avoided. If you set a custom environment variable that is already in use by Strimzi, it is ignored and a warning is recorded in the log.

ContainerTemplate schema properties
Property Description

env

Environment variables which should be applied to the container.

ContainerEnvVar array

securityContext

Security context for the container. For more information, see the external documentation for core/v1 securitycontext.

SecurityContext

9.2.41. ContainerEnvVar schema reference

Property Description

name

The environment variable key.

string

value

The environment variable value.

string

9.2.42. ZookeeperClusterSpec schema reference

Used in: KafkaSpec

Configures a ZooKeeper cluster.

config

Use the config properties to configure ZooKeeper options as keys.

Standard Apache ZooKeeper configuration may be provided, restricted to those properties not managed directly by Strimzi.

Configuration options that cannot be configured relate to:

  • Security (Encryption, Authentication, and Authorization)

  • Listener configuration

  • Configuration of data directories

  • ZooKeeper cluster composition

The values can be one of the following JSON types:

  • String

  • Number

  • Boolean

You can specify and configure the options listed in the ZooKeeper documentation with the exception of those managed directly by Strimzi. Specifically, all configuration options with keys equal to or starting with one of the following strings are forbidden:

  • server.

  • dataDir

  • dataLogDir

  • clientPort

  • authProvider

  • quorum.auth

  • requireClientAuthScheme

When a forbidden option is present in the config property, it is ignored and a warning message is printed to the Cluster Operator log file. All other supported options are passed to ZooKeeper.

There are exceptions to the forbidden options. For client connection using a specific cipher suite for a TLS version, you can configure allowed ssl properties.

Example ZooKeeper configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
  kafka:
    # ...
  zookeeper:
    # ...
    config:
      autopurge.snapRetainCount: 3
      autopurge.purgeInterval: 1
      ssl.cipher.suites: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
      ssl.enabled.protocols: "TLSv1.2"
      ssl.protocol: "TLSv1.2"
    # ...
logging

ZooKeeper has a configurable logger:

  • zookeeper.root.logger

ZooKeeper uses the Apache log4j logge