Optional, default regex pattern is (app.kubernetes.io/(?!part-of).|</sup>kustomize.toolkit.fluxcd.io.)</code>.
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
.</p>
env:
- name: STRIMZI_LABELS_EXCLUSION_PATTERN
value: "^key1.*"
</dd>
STRIMZI_CUSTOM_<COMPONENT_NAME>_LABELS
Optional.
One or more custom labels to apply to all the pods created by the custom resource of the component.
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
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 image containing a Kafka broker for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.44.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0
.
STRIMZI_KAFKA_CONNECT_IMAGES
Required.
The mapping from the Kafka version to the corresponding image of Kafka Connect for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.44.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0
.
STRIMZI_KAFKA_MIRROR_MAKER2_IMAGES
Required.
The mapping from the Kafka version to the corresponding image of MirrorMaker 2 for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.44.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0
.
(Deprecated) STRIMZI_KAFKA_MIRROR_MAKER_IMAGES
Required.
The mapping from the Kafka version to the corresponding image of MirrorMaker for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.44.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0
.
STRIMZI_DEFAULT_TOPIC_OPERATOR_IMAGE
Optional.
The default is quay.io/strimzi/operator:0.44.0
.
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.
The default is quay.io/strimzi/operator:0.44.0
.
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_KAFKA_EXPORTER_IMAGE
Optional.
The default is quay.io/strimzi/kafka:0.44.0-kafka-3.8.0
.
The image name to use as the default when deploying the Kafka Exporter if no image is specified as the Kafka.spec.kafkaExporter.image
in the Kafka
resource.
STRIMZI_DEFAULT_CRUISE_CONTROL_IMAGE
Optional.
The default is quay.io/strimzi/kafka:0.44.0-kafka-3.8.0
.
The image name to use as the default when deploying Cruise Control if no image is specified as the Kafka.spec.cruiseControl.image
in the Kafka
resource.
STRIMZI_DEFAULT_KAFKA_BRIDGE_IMAGE
Optional.
The default is quay.io/strimzi/kafka-bridge:0.30.0
.
The image name to use as the default when deploying the Kafka Bridge if no image is specified as the Kafka.spec.kafkaBridge.image
in the Kafka
resource.
STRIMZI_DEFAULT_KAFKA_INIT_IMAGE
Optional.
The default is quay.io/strimzi/operator:0.44.0
.
The image name to use as the default for the Kafka initializer container if no image is specified in the brokerRackInitImage
of the Kafka
resource or the clientRackInitImage
of the Kafka Connect resource.
The init container is started before the Kafka cluster for initial configuration work, such as rack 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.
</dl>
</div>
11.7.1. Restricting access to the Cluster Operator using 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
#...
11.7.2. Setting periodic reconciliation of custom resources
Use the STRIMZI_FULL_RECONCILIATION_INTERVAL_MS
variable to set the time interval for periodic reconciliations by the Cluster Operator.
Replace its value with the required interval in milliseconds.
Reconciliation period configured for the Cluster Operator deployment
#...
env:
# ...
- name: STRIMZI_FULL_RECONCILIATION_INTERVAL_MS
value: "120000"
#...
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.
11.7.3. Pausing reconciliation of custom resources using annotations
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.
Procedure
-
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"
-
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
11.7.4. Running multiple Cluster Operator replicas with leader election
The default Cluster Operator configuration enables 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 caused by major failure.
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.
Enabling leader election for Cluster Operator replicas
Configure leader election environment variables when running additional Cluster Operator replicas.
The following environment variables are supported:
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.
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.
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.
-
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
-
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
If you specified a different name or namespace for the Lease
resource used in leader election, update the RBAC resources.
-
(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
# ...
-
(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
# ...
-
Deploy the Cluster Operator:
kubectl create -f install/cluster-operator -n myproject
-
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.
11.7.5. Configuring Cluster Operator HTTP 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>.
Procedure
-
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)
# ...
-
Address of the proxy server.
-
Secure address of the proxy server.
-
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
-
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
11.7.6. Disabling FIPS mode using Cluster Operator configuration
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
-
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)
# ...
Alternatively, edit the Deployment
directly:
kubectl edit deployment strimzi-cluster-operator
-
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
</div>
11.8. Configuring Kafka Connect
Update the spec
properties of the KafkaConnect
custom resource to configure your Kafka Connect deployment.
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.
You can also use the KafkaConnect
resource to specify the following:
-
Connector plugin configuration to build a container image that includes the plugins to make connections
-
Configuration for the Kafka Connect worker pods that run connectors
-
An annotation to enable use of the KafkaConnector
resource to manage connectors
The Cluster Operator manages Kafka Connect clusters deployed using the KafkaConnect
resource and connectors created using the KafkaConnector
resource.
Example KafkaConnect
custom resource configuration
# Basic configuration (required)
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect # (1)
metadata:
name: my-connect-cluster
annotations:
strimzi.io/use-connector-resources: "true" # (2)
# Deployment specifications
spec:
# Replicas (required)
replicas: 3 # (3)
# Bootstrap servers (required)
bootstrapServers: my-cluster-kafka-bootstrap:9092 # (4)
# Kafka Connect configuration (recommended)
config: # (5)
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
# Resources requests and limits (recommended)
resources: # (6)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# Authentication (optional)
authentication: # (7)
type: tls
certificateAndKey:
certificate: source.crt
key: source.key
secretName: my-user-source
# TLS configuration (optional)
tls: # (8)
trustedCertificates:
- secretName: my-cluster-cluster-cert
pattern: "*.crt"
- secretName: my-cluster-cluster-cert
pattern: "*.crt"
# Build configuration (optional)
build: # (9)
output: # (10)
type: docker
image: my-registry.io/my-org/my-connect-cluster:latest
pushSecret: my-registry-credentials
plugins: # (11)
- name: connector-1
artifacts:
- type: tgz
url: <url_to_download_connector_1_artifact>
sha512sum: <SHA-512_checksum_of_connector_1_artifact>
- name: connector-2
artifacts:
- type: jar
url: <url_to_download_connector_2_artifact>
sha512sum: <SHA-512_checksum_of_connector_2_artifact>
# Logging configuration (optional)
logging: # (12)
type: inline
loggers:
log4j.rootLogger: INFO
# Readiness probe (optional)
readinessProbe: # (13)
initialDelaySeconds: 15
timeoutSeconds: 5
# Liveness probe (optional)
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
# Metrics configuration (optional)
metricsConfig: # (14)
type: jmxPrometheusExporter
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-key
# JVM options (optional)
jvmOptions: # (15)
"-Xmx": "1g"
"-Xms": "1g"
# Custom image (optional)
image: my-org/my-image:latest # (16)
# Rack awareness (optional)
rack:
topologyKey: topology.kubernetes.io/zone # (17)
# Pod and container template (optional)
template: # (18)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
connectContainer: # (19)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: aws-creds
key: awsAccessKey
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws-creds
key: awsSecretAccessKey
# Tracing configuration (optional)
tracing:
type: opentelemetry # (20)
-
Use KafkaConnect
.
-
Enables the use of KafkaConnector
resources to start, stop, and manage connector instances.
-
The number of replica nodes for the workers that run tasks.
-
Bootstrap address for connection to the Kafka cluster. The address takes the format <cluster_name>-kafka-bootstrap:<port_number>
. The Kafka cluster doesn’t need to be managed by Strimzi or deployed to a Kubernetes cluster.
-
Kafka Connect configuration of workers (not connectors) that run connectors and their tasks.
Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.
In this example, JSON convertors are specified.
A replication factor of 3 is set for the internal topics used by Kafka Connect (minimum requirement for production environment).
Changing the replication factor after the topics have been created has no effect.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
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.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Build configuration properties for building a container image with connector plugins automatically.
-
(Required) Configuration of the container registry where new images are pushed.
-
(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
.
-
Specified Kafka Connect loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. For the Kafka Connect log4j.rootLogger
logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
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
.
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka Connect.
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
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.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing and to pass credentials to connectors.
-
Distributed tracing is enabled by using OpenTelemetry.
11.8.1. Configuring Kafka Connect for multiple instances
By default, Strimzi configures the group ID and names of the internal topics used by Kafka Connect.
When running multiple instances of Kafka Connect, you must change these default settings using the following config
properties:
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)
# ...
# ...
-
The Kafka Connect cluster group ID within Kafka.
-
Kafka topic that stores connector offsets.
-
Kafka topic that stores connector and task status configurations.
-
Kafka topic that stores connector and task status updates.
Note
|
Values for the three topics must be the same for all instances with the same group.id .
|
Unless you modify these default settings, each instance connecting to the same Kafka cluster is deployed with the same values.
In practice, this means all instances form a cluster and use the same internal topics.
Multiple instances attempting to use the same internal topics will cause unexpected errors, so you must change the values of these properties for each instance.
11.8.2. Configuring Kafka Connect user authorization
When using authorization in Kafka, a Kafka Connect user requires read/write access to the cluster group and internal topics of Kafka Connect.
This procedure outlines how access is granted using simple
authorization and ACLs.
Properties for the Kafka Connect cluster group ID and internal topics are configured by Strimzi by default.
Alternatively, you can define them explicitly in the spec
of the KafkaConnect
resource.
This is useful when configuring Kafka Connect for multiple instances, as the values for the group ID and topics must differ when running multiple Kafka Connect instances.
Simple authorization uses ACL rules managed by the Kafka AclAuthorizer
and StandardAuthorizer
plugins to ensure appropriate access levels.
For more information on configuring a KafkaUser
resource to use simple authorization, see the AclRule
schema reference.
Procedure
-
Edit the authorization
property in the KafkaUser
resource to provide access rights to the user.
Access rights are configured for the Kafka Connect topics and cluster group using literal
name values.
The following table shows the default names configured for the topics and cluster group ID.
Table 12. Names for the access rights configuration
Property |
Name |
offset.storage.topic
|
connect-cluster-offsets
|
status.storage.topic
|
connect-cluster-status
|
config.storage.topic
|
connect-cluster-configs
|
group
|
connect-cluster
|
In this example configuration, the default names are used to specify access rights.
If you are using different names for a Kafka Connect instance, use those names in the ACLs configuration.
Example configuration for simple authorization
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: "*"
# cluster group
- resource:
type: group
name: connect-cluster
patternType: literal
operations:
- Read
host: "*"
-
Create or update the resource.
kubectl apply -f KAFKA-USER-CONFIG-FILE
11.9. Configuring Kafka Connect connectors
The KafkaConnector
resource provides a Kubernetes-native approach to management of connectors by the Cluster Operator.
To create, delete, or reconfigure connectors with KafkaConnector
resources, you must set the use-connector-resources
annotation to true
in your KafkaConnect
custom resource.
Annotation to enable KafkaConnectors
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect-cluster
annotations:
strimzi.io/use-connector-resources: "true"
# ...
When the use-connector-resources
annotation is enabled in your KafkaConnect
configuration, you must define and manage connectors using KafkaConnector
resources.
Note
|
Alternatively, you can manage connectors using the Kafka Connect REST API instead of KafkaConnector resources.
To use the API, you must remove the strimzi.io/use-connector-resources annotation to use KafkaConnector resources in the KafkaConnect the resource.
|
KafkaConnector
resources provide the configuration needed to create connectors within a Kafka Connect cluster, which interacts with a Kafka cluster as specified in the KafkaConnect
configuration.
The Kafka cluster does not need to be managed by Strimzi or deployed to a Kubernetes cluster.
Kafka components contained in the same Kubernetes cluster
The configuration also specifies how the connector instances interact with external data systems, including any required authentication methods. Additionally, you must define the data to watch.
For example, in a source connector that reads data from a database, the configuration might include the database name.
You can also define where this data should be placed in Kafka by specifying the target topic name.
Use the tasksMax
property to specify the maximum number of tasks.
For instance, a source connector with tasksMax: 2
might split the import of source data into two tasks.
Example source connector configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector # (1)
labels:
strimzi.io/cluster: my-connect-cluster # (2)
spec:
class: org.apache.kafka.connect.file.FileStreamSourceConnector # (3)
tasksMax: 2 # (4)
autoRestart: # (5)
enabled: true
config: # (6)
file: "/opt/kafka/LICENSE" # (7)
topic: my-topic # (8)
# ...
-
Name of the KafkaConnector
resource, which is used as the name of the connector. Use any name that is valid for a Kubernetes resource.
-
Name of the Kafka Connect cluster to create the connector instance in. Connectors must be deployed to the same namespace as the Kafka Connect cluster they link to.
-
Full name of the connector class. This should be present in the image being used by the Kafka Connect cluster.
-
Maximum number of Kafka Connect tasks that the connector can create.
-
Enables automatic restarts of failed connectors and tasks. By default, the number of restarts is indefinite, but you can set a maximum on the number of automatic restarts using the maxRestarts
property.
-
Connector configuration as key-value pairs.
-
Location of the external data file. In this example, we’re configuring the FileStreamSourceConnector
to read from the /opt/kafka/LICENSE
file.
-
Kafka topic to publish the source data to.
To include external connector configurations, such as user access credentials stored in a secret, use the template
property of the KafkaConnect
resource.
You can also load values using configuration providers.
11.9.1. Manually stopping or pausing Kafka Connect connectors
If you are using KafkaConnector
resources to configure connectors, use the state
configuration to either stop or pause a connector.
In contrast to the paused state, where the connector and tasks remain instantiated, stopping a connector retains only the configuration, with no active processes.
Stopping a connector from running may be more suitable for longer durations than just pausing.
While a paused connector is quicker to resume, a stopped connector has the advantages of freeing up memory and resources.
Note
|
The state configuration replaces the (deprecated) pause configuration in the KafkaConnectorSpec schema, which allows pauses on connectors.
If you were previously using the pause configuration to pause connectors, we encourage you to transition to using the state configuration only to avoid conflicts.
|
Procedure
-
Find the name of the KafkaConnector
custom resource that controls the connector you want to pause or stop:
kubectl get KafkaConnector
-
Edit the KafkaConnector
resource to stop or pause the connector.
Example configuration for stopping a Kafka Connect connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: org.apache.kafka.connect.file.FileStreamSourceConnector
tasksMax: 2
config:
file: "/opt/kafka/LICENSE"
topic: my-topic
state: stopped
# ...
Change the state
configuration to stopped
or paused
.
The default state for the connector when this property is not set is running
.
-
Apply the changes to the KafkaConnector
configuration.
You can resume the connector by changing state
to running
or removing the configuration.
Note
|
Alternatively, you can expose the Kafka Connect API and use the stop and pause endpoints to stop a connector from running.
For example, PUT /connectors/<connector_name>/stop .
You can then use the resume endpoint to restart it.
|
11.9.2. Manually restarting Kafka Connect connectors
If you are using KafkaConnector
resources to manage connectors, use the strimzi.io/restart
annotation to manually trigger a restart of a connector.
Procedure
-
Find the name of the KafkaConnector
custom resource that controls the Kafka connector you want to restart:
kubectl get KafkaConnector
-
Restart the connector by annotating the KafkaConnector
resource in Kubernetes:
kubectl annotate KafkaConnector <kafka_connector_name> strimzi.io/restart="true"
The restart
annotation is set to true
.
-
Wait for the next reconciliation to occur (every two minutes by default).
The Kafka connector is restarted, as long as the annotation was detected by the reconciliation process.
When Kafka Connect accepts the restart request, the annotation is removed from the KafkaConnector
custom resource.
11.9.3. Manually restarting Kafka Connect connector tasks
If you are using KafkaConnector
resources to manage connectors, use the strimzi.io/restart-task
annotation to manually trigger a restart of a connector task.
Procedure
-
Find the name of the KafkaConnector
custom resource that controls the Kafka connector task you want to restart:
kubectl get KafkaConnector
-
Find the ID of the task to be restarted from the KafkaConnector
custom resource:
kubectl describe KafkaConnector <kafka_connector_name>
Task IDs are non-negative integers, starting from 0.
-
Use the ID to restart the connector task by annotating the KafkaConnector
resource in Kubernetes:
kubectl annotate KafkaConnector <kafka_connector_name> strimzi.io/restart-task="0"
In this example, task 0
is restarted.
-
Wait for the next reconciliation to occur (every two minutes by default).
The Kafka connector task is restarted, as long as the annotation was detected by the reconciliation process.
When Kafka Connect accepts the restart request, the annotation is removed from the KafkaConnector
custom resource.
11.9.4. Listing connector offsets
To track connector offsets using KafkaConnector
resources, add the listOffsets
configuration.
The offsets, which keep track of the flow of data, are written to a config map specified in the configuration.
If the config map does not exist, Strimzi creates it.
After the configuration is in place, annotate the KafkaConnector
resource to write the list to the config map.
Sink connectors use Kafka’s standard consumer offset mechanism, while source connectors store offsets in a custom format within a Kafka topic.
-
For sink connectors, the list shows Kafka topic partitions and the last committed offset for each partition.
-
For source connectors, the list shows the source system’s partition and the last offset processed.
Procedure
-
Edit the KafkaConnector
resource for the connector to include the listOffsets
configuration.
Example configuration to list offsets
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
listOffsets:
toConfigMap: # (1)
name: my-connector-offsets # (2)
# ...
-
The reference to the config map where the list of offsets will be written to.
-
The name of the config map, which is named my-connector-offsets
in this example.
-
Run the command to write the list to the config map by annotating the KafkaConnector
resource:
kubectl annotate kafkaconnector my-source-connector strimzi.io/connector-offsets=list -n <namespace>
The annotation remains until either the list operation succeeds or it is manually removed from the resource.
-
After the KafkaConnector
resource is updated, use the following command to check if the config map with the offsets was created:
kubectl get configmap my-connector-offsets -n <namespace>
-
Inspect the contents of the config map to verify the offsets are being listed:
kubectl describe configmap my-connector-offsets -n <namespace>
Strimzi puts the offset information into the offsets.json
property.
This does not overwrite any other properties when updating an existing config map.
Example source connector offset list
apiVersion: v1
kind: ConfigMap
metadata:
# ...
ownerReferences: # (1)
- apiVersion: kafka.strimzi.io/v1beta2
blockOwnerDeletion: false
controller: false
kind: KafkaConnector
name: my-source-connector
uid: 637e3be7-bd96-43ab-abde-c55b4c4550e0
resourceVersion: "66951"
uid: 641d60a9-36eb-4f29-9895-8f2c1eb9638e
data:
offsets.json: |-
{
"offsets" : [ {
"partition" : {
"filename" : "/data/myfile.txt" # (2)
},
"offset" : {
"position" : 15295 # (3)
}
} ]
}
-
The owner reference pointing to the KafkaConnector
resource for the source connector.
To provide a custom owner reference, create the config map in advance and set the owner reference.
-
The source partition, represented by the filename /data/myfile.txt
in this example for a file-based connector.
-
The last processed offset position in the source partition.
Example sink connector offset list
apiVersion: v1
kind: ConfigMap
metadata:
# ...
ownerReferences: # (1)
- apiVersion: kafka.strimzi.io/v1beta2
blockOwnerDeletion: false
controller: false
kind: KafkaConnector
name: my-sink-connector
uid: 84a29d7f-77e6-43ac-bfbb-719f9b9a4b3b
resourceVersion: "79241"
uid: 721e30bc-23df-41a2-9b48-fb2b7d9b042c
data:
offsets.json: |-
{
"offsets": [
{
"partition": {
"kafka_topic": "my-topic", # (2)
"kafka_partition": 2 # (3)
},
"offset": {
"kafka_offset": 4 # (4)
}
}
]
}
-
The owner reference pointing to the KafkaConnector
resource for the sink connector.
-
The Kafka topic that the sink connector is consuming from.
-
The partition of the Kafka topic.
-
The last committed Kafka offset for this topic and partition.
11.9.5. Altering connector offsets
To alter connector offsets using KafkaConnector
resources, configure the resource to stop the connector and add alterOffsets
configuration to specify the offset changes in a config map.
You can reuse the same config map used to list offsets.
After the connector is stopped and the configuration is in place, annotate the KafkaConnector
resource to apply the offset alteration, then restart the connector.
Altering connector offsets can be useful, for example, to skip a poison record or replay a record.
In this procedure, we alter the offset position for a source connector named my-source-connector
.
Procedure
-
Edit the KafkaConnector
resource to stop the connector and include the alterOffsets
configuration.
Example configuration to stop a connector and alter offsets
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
state: stopped # (1)
alterOffsets:
fromConfigMap: # (2)
name: my-connector-offsets # (3)
# ...
-
Changes the state of the connector to stopped
. The default state for the connector when this property is not set is running
.
-
The reference to the config map that provides the update.
-
The name of the config map, which is named my-connector-offsets
in this example.
-
Edit the config map to make the alteration.
In this example, we’re resetting the offset position for a source connector to 15000.
Example source connector offset list configuration
apiVersion: v1
kind: ConfigMap
metadata:
# ...
data:
offsets.json: |- # (1)
{
"offsets" : [ {
"partition" : {
"filename" : "/data/myfile.txt"
},
"offset" : {
"position" : 15000 # (2)
}
} ]
}
-
Edits must be made within the offsets.json
property.
-
The updated offset position in the source partition.
-
Run the command to update the offset position by annotating the KafkaConnector
resource:
kubectl annotate kafkaconnector my-source-connector strimzi.io/connector-offsets=alter -n <namespace>
The annotation remains until either the update operation succeeds or it is manually removed from the resource.
-
Check the changes by using the procedure to list connector offsets.
-
Restart the connector by changing the state to running
.
Example configuration to start a connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
state: running
# ...
11.9.6. Resetting connector offsets
To reset connector offsets using KafkaConnector
resources, configure the resource to stop the connector.
After the connector is stopped, annotate the KafkaConnector
resource to clear the offsets, then restart the connector.
In this procedure, we reset the offset position for a source connector named my-source-connector
.
Procedure
-
Edit the KafkaConnector
resource to stop the connector.
Example configuration to stop a connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
# ...
state: stopped # (1)
# ...
-
Changes the state of the connector to stopped
. The default state for the connector when this property is not set is running
.
-
Run the command to reset the offset position by annotating the KafkaConnector
resource:
kubectl annotate kafkaconnector my-source-connector strimzi.io/connector-offsets=reset -n <namespace>
The annotation remains until either the reset operation succeeds or it is manually removed from the resource.
-
Check the changes by using the procedure to list connector offsets.
After resetting, the offsets.json
property is empty.
Example source connector offset list
apiVersion: v1
kind: ConfigMap
metadata:
# ...
data:
offsets.json: |-
{
"offsets" : []
}
-
Restart the connector by changing the state to running
.
Example configuration to start a connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
state: running
# ...
11.10. Configuring Kafka MirrorMaker 2
Update the spec
properties of the KafkaMirrorMaker2
custom resource to configure your MirrorMaker 2 deployment.
MirrorMaker 2 uses source cluster configuration for data consumption and target cluster configuration for data output.
MirrorMaker 2 is based on the Kafka Connect framework, connectors managing the transfer of data between clusters.
You configure MirrorMaker 2 to define the Kafka Connect deployment, including the connection details of the source and target clusters, and then run a set of MirrorMaker 2 connectors to make the connection.
MirrorMaker 2 supports topic configuration synchronization between the source and target clusters.
You specify source topics in the MirrorMaker 2 configuration.
MirrorMaker 2 monitors the source topics.
MirrorMaker 2 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.
|
The configuration must specify:
Note
|
MirrorMaker 2 resource configuration differs from the previous version of MirrorMaker, which is now deprecated.
There is currently no legacy support, so any resources must be manually converted into the new format.
|
Default configuration
MirrorMaker 2 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
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
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.
Example KafkaMirrorMaker2
custom resource configuration
# Basic configuration (required)
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
# Deployment specifications
spec:
# Replicas (required)
replicas: 3 # (1)
# Connect cluster name (required)
connectCluster: "my-cluster-target" # (2)
# Cluster configurations (required)
clusters: # (3)
- alias: "my-cluster-source" # (4)
# Authentication (optional)
authentication: # (5)
certificateAndKey:
certificate: source.crt
key: source.key
secretName: my-user-source
type: tls
bootstrapServers: my-cluster-source-kafka-bootstrap:9092 # (6)
# TLS configuration (optional)
tls: # (7)
trustedCertificates:
- pattern: "*.crt"
secretName: my-cluster-source-cluster-ca-cert
- alias: "my-cluster-target" # (8)
# Authentication (optional)
authentication: # (9)
certificateAndKey:
certificate: target.crt
key: target.key
secretName: my-user-target
type: tls
bootstrapServers: my-cluster-target-kafka-bootstrap:9092 # (10)
# Kafka Connect configuration (optional)
config: # (11)
config.storage.replication.factor: 1
offset.storage.replication.factor: 1
status.storage.replication.factor: 1
# TLS configuration (optional)
tls: # (12)
trustedCertificates:
- pattern: "*.crt"
secretName: my-cluster-target-cluster-ca-cert
# Mirroring configurations (required)
mirrors: # (13)
- sourceCluster: "my-cluster-source" # (14)
targetCluster: "my-cluster-target" # (15)
# Topic and group patterns (required)
topicsPattern: "topic1|topic2|topic3" # (16)
groupsPattern: "group1|group2|group3" # (17)
# Source connector configuration (required)
sourceConnector: # (18)
tasksMax: 10 # (19)
autoRestart: # (20)
enabled: true
config:
replication.factor: 1 # (21)
offset-syncs.topic.replication.factor: 1 # (22)
sync.topic.acls.enabled: "false" # (23)
refresh.topics.interval.seconds: 60 # (24)
replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy" # (25)
# Heartbeat connector configuration (optional)
heartbeatConnector: # (26)
autoRestart:
enabled: true
config:
heartbeats.topic.replication.factor: 1 # (27)
replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"
# Checkpoint connector configuration (optional)
checkpointConnector: # (28)
autoRestart:
enabled: true
config:
checkpoints.topic.replication.factor: 1 # (29)
refresh.groups.interval.seconds: 600 # (30)
sync.group.offsets.enabled: true # (31)
sync.group.offsets.interval.seconds: 60 # (32)
emit.checkpoints.interval.seconds: 60 # (33)
replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"
# Kafka version (recommended)
version: 3.8.0 # (34)
# Resources requests and limits (recommended)
resources: # (35)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# Logging configuration (optional)
logging: # (36)
type: inline
loggers:
connect.root.logger.level: INFO
# Readiness probe (optional)
readinessProbe: # (37)
initialDelaySeconds: 15
timeoutSeconds: 5
# Liveness probe (optional)
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
# JVM options (optional)
jvmOptions: # (38)
"-Xmx": "1g"
"-Xms": "1g"
# Custom image (optional)
image: my-org/my-image:latest # (39)
# Rack awareness (optional)
rack:
topologyKey: topology.kubernetes.io/zone # (40)
# Pod template (optional)
template: # (41)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
connectContainer: # (42)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
# Tracing configuration (optional)
tracing:
type: opentelemetry # (43)
-
The number of replica nodes for the workers that run tasks.
-
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.
-
Specification for the Kafka clusters being synchronized.
-
Cluster alias for the source Kafka cluster.
-
Authentication for the source cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.
-
Bootstrap address for connection to the source Kafka cluster. The address takes the format <cluster_name>-kafka-bootstrap:<port_number>
. The Kafka cluster doesn’t need to be managed by Strimzi or deployed to a Kubernetes cluster.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Cluster alias for the target Kafka cluster.
-
Authentication for the target Kafka cluster is configured in the same way as for the source Kafka cluster.
-
Bootstrap address for connection to the target Kafka cluster. The address takes the format <cluster_name>-kafka-bootstrap:<port_number>
. The Kafka cluster doesn’t need to be managed by Strimzi or deployed to a Kubernetes cluster.
-
Kafka Connect configuration.
Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.
-
TLS encryption for the target Kafka cluster is configured in the same way as for the source Kafka cluster.
-
MirrorMaker 2 connectors.
-
Cluster alias for the source cluster used by the MirrorMaker 2 connectors.
-
Cluster alias for the target cluster used by the MirrorMaker 2 connectors.
-
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.
-
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.
-
Configuration for the MirrorSourceConnector
that creates remote topics. The config
overrides the default configuration options.
-
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.
-
Enables automatic restarts of failed connectors and tasks. By default, the number of restarts is indefinite, but you can set a maximum on the number of automatic restarts using the maxRestarts
property.
-
Replication factor for mirrored topics created at the target cluster.
-
Replication factor for the MirrorSourceConnector
offset-syncs
internal topic that maps the offsets of the source and target clusters.
-
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
.
-
Optional setting to change the frequency of checks for new topics. The default is for a check every 10 minutes.
-
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. The property must be specified for all connectors. For bidirectional (active/active) replication, use the DefaultReplicationPolicy
class to automatically rename remote topics and specify the replication.policy.separator
property for all connectors to add a custom separator.
-
Configuration for the MirrorHeartbeatConnector
that performs connectivity checks. The config
overrides the default configuration options.
-
Replication factor for the heartbeat topic created at the target cluster.
-
Configuration for the MirrorCheckpointConnector
that tracks offsets. The config
overrides the default configuration options.
-
Replication factor for the checkpoints topic created at the target cluster.
-
Optional setting to change the frequency of checks for new consumer groups. The default is for a check every 10 minutes.
-
Optional setting to synchronize consumer group offsets, which is useful for recovery in an active/passive configuration. Synchronization is not enabled by default.
-
If the synchronization of consumer group offsets is enabled, you can adjust the frequency of the synchronization.
-
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.
-
The Kafka Connect and MirrorMaker 2 version, which will always be the same.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Specified Kafka Connect loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. For the Kafka Connect log4j.rootLogger
logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka MirrorMaker.
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
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.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
11.10.1. Configuring active/active or active/passive modes
You can use MirrorMaker 2 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 cluster is required at each target destination.
Bidirectional replication (active/active)
The MirrorMaker 2 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 to represent the source cluster.
The name of the originating cluster is prepended to the name of the topic.
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 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.
11.10.2. Configuring MirrorMaker 2 for multiple instances
By default, Strimzi configures the group ID and names of the internal topics used by the Kafka Connect framework that MirrorMaker 2 runs on.
When running multiple instances of MirrorMaker 2, and they share the same connectCluster
value, you must change these default settings using the following config
properties:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
connectCluster: "my-cluster-target"
clusters:
- alias: "my-cluster-target"
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)
# ...
# ...
-
The Kafka Connect cluster group ID within Kafka.
-
Kafka topic that stores connector offsets.
-
Kafka topic that stores connector and task status configurations.
-
Kafka topic that stores connector and task status updates.
Note
|
Values for the three topics must be the same for all instances with the same group.id .
|
The connectCluster
setting specifies the alias of the target Kafka cluster used by Kafka Connect for its internal topics.
As a result, modifications to the connectCluster
, group ID, and internal topic naming configuration are specific to the target Kafka cluster.
You don’t need to make changes if two MirrorMaker 2 instances are using the same source Kafka cluster or in an active-active mode where each MirrorMaker 2 instance has a different connectCluster
setting and target cluster.
However, if multiple MirrorMaker 2 instances share the same connectCluster
, each instance connecting to the same target Kafka cluster is deployed with the same values.
In practice, this means all instances form a cluster and use the same internal topics.
Multiple instances attempting to use the same internal topics will cause unexpected errors, so you must change the values of these properties for each instance.
11.10.3. Configuring MirrorMaker 2 connectors
Use MirrorMaker 2 connector configuration for the internal connectors that orchestrate the synchronization of data between Kafka clusters.
MirrorMaker 2 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.
The following table describes connector properties and the connectors you configure to use them.
Table 13. MirrorMaker 2 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. By default, the separator is set to a dot (.).
Separator configuration is only applicable to the DefaultReplicationPolicy replication policy class, which defines remote topic names.
The IdentityReplicationPolicy class does not use the property as topics retain their original names.
|
✓ |
✓ |
✓ |
- 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). 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.
|
✓ |
|
|
- replication.factor
-
The replication factor for new topics. Default is 2 .
|
✓ |
|
|
|
✓ |
|
|
- 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 .
|
|
|
✓ |
Changing the location of the consumer group offsets topic
MirrorMaker 2 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 are used internally by MirrorMaker 2, 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 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.
|
Deciding when to use the heartbeat connector
The heartbeat connector emits heartbeats to check connectivity between source and target Kafka clusters.
An internal heartbeat
topic is replicated from the source cluster, which means that the heartbeat connector must be connected to the source cluster.
The heartbeat
topic is located on the target cluster, which allows it to do the following:
This helps to make sure that the process is not stuck or has stopped for any reason.
While the heartbeat connector can be a valuable tool for monitoring the mirroring processes between Kafka clusters, it’s not always necessary to use it.
For example, if your deployment has low network latency or a small number of topics, you might prefer to monitor the mirroring process using log messages or other monitoring tools.
If you decide not to use the heartbeat connector, simply omit it from your MirrorMaker 2 configuration.
Aligning the configuration of MirrorMaker 2 connectors
To ensure that MirrorMaker 2 connectors work properly, make sure to align certain configuration settings across connectors.
Specifically, ensure that the following properties have the same value across all applicable connectors:
For example, the value for replication.policy.class
must be the same for the source, checkpoint, and heartbeat connectors.
Mismatched or missing settings cause issues with data replication or offset syncing, so it’s essential to keep all relevant connectors configured with the same settings.
Listing the offsets of MirrorMaker 2 connectors
To list the offset positions of the internal MirrorMaker 2 connectors, use the same configuration that’s used to manage Kafka Connect connectors.
For more information on setting up the configuration and listing offsets, see Listing connector offsets.
In this example, the sourceConnector
configuration is updated to return the connector offset position.
The offset information is written to a specified config map.
Example configuration for MirrorMaker 2 connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
# ...
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:
listOffsets:
toConfigMap:
name: my-connector-offsets
# ...
You must apply the following annotations to the KafkaMirrorMaker2
resource be able to manage connector offsets:
The strimzi.io/mirrormaker-connector
annotation must be set to the name of the connector.
These annotations remain until the operation succeeds or they are manually removed from the resource.
MirrorMaker 2 connectors are named using the aliases of the source and target clusters, followed by the connector type: <source_alias>-><target_alias>.<connector_type>
.
In the following example, the annotations are applied for a connector named my-cluster-source->my-cluster-target.MirrorSourceConnector
.
Example application of annotations for connector
kubectl annotate kafkamirrormaker2 my-mirror-maker-2 strimzi.io/connector-offsets=list strimzi.io/mirrormaker-connector="my-cluster-source->my-cluster-target.MirrorSourceConnector" -n kafka
The offsets are listed in the specified config map.
Strimzi puts the offset information into a .json
property named after the connector.
This does not overwrite any other properties when updating an existing config map.
Example source connector offset list
apiVersion: v1
kind: ConfigMap
metadata:
# ...
ownerReferences: # (1)
- apiVersion: kafka.strimzi.io/v1beta2
blockOwnerDeletion: false
controller: false
kind: KafkaMirrorMaker2
name: my-mirror-maker2
uid: 637e3be7-bd96-43ab-abde-c55b4c4550e0
data:
my-cluster-source--my-cluster-target.MirrorSourceConnector.json: |- # (2)
{
"offsets": [
{
"partition": {
"cluster": "east-kafka",
"partition": 0,
"topic": "mirrormaker2-cluster-configs"
},
"offset": {
"offset": 0
}
}
]
}
-
The owner reference pointing to the KafkaMirrorMaker2
resource.
To provide a custom owner reference, create the config map in advance and set the owner reference.
-
The .json
property uses the connector name. Since ->
characters are not allowed in config map keys, ->
is changed to --
in the connector name.
Note
|
It is possible to use configuration to alter or reset connector offsets, though this is rarely necessary.
|
11.10.4. Configuring MirrorMaker 2 connector producers and consumers
MirrorMaker 2 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 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 14. 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 15. 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 16. Heartbeat connector producer
Type |
Description |
Configuration |
Producer |
|
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.8.0
# ...
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
# ...
11.10.5. Specifying a maximum number of data replication 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 source 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 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 performance.
The example MirrorMaker 2 Grafana dashboard provided with Strimzi shows the following metrics related to tasks and latency.
11.10.6. Synchronizing ACL rules for remote topics
When using MirrorMaker 2 with Strimzi, it is possible to synchronize ACL rules for remote topics.
However, this feature is only available if you are not using the User Operator.
If you are using type: simple
authorization without the User Operator, the ACL rules that manage access to brokers also apply to remote topics.
This means that users who have read access to a source topic can also read its remote equivalent.
Note
|
OAuth 2.0 authorization does not support access to remote topics in this way.
|
11.10.7. Securing a Kafka MirrorMaker 2 deployment
This procedure describes in outline the configuration required to secure a MirrorMaker 2 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.
After you have created the cluster and user authentication credentials, you specify them in your MirrorMaker configuration for secure connections.
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 using mTLS or SCRAM-SHA-512 authentication.
The examples specify internal listeners for connecting within a Kubernetes cluster.
The examples also provide the configuration for full authorization, including the ACLs that allow user operations on the source and target Kafka clusters.
When configuring user access to source and target Kafka clusters, ACLs must grant access rights to internal MirrorMaker 2 connectors and read/write access to the cluster group and internal topics used by the underlying Kafka Connect framework in the target cluster.
If you’ve renamed the cluster group or internal topics, such as when configuring MirrorMaker 2 for multiple instances, use those names in the ACLs configuration.
Simple authorization uses ACL rules managed by the Kafka AclAuthorizer
and StandardAuthorizer
plugins to ensure appropriate access levels.
For more information on configuring a KafkaUser
resource to use simple authorization, see the AclRule
schema reference.
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
-
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.8.0
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.8"
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.8.0
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.8"
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: {}
-
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
.
-
Configure two KafkaUser
resources, one for a user of the source Kafka cluster and one for a user of the target Kafka cluster.
-
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.
-
Configure the ACLs needed by MirrorMaker 2 to allow operations on the source and target Kafka clusters.
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:
# cluster group
- resource:
type: group
name: mirrormaker2-cluster
operations:
- Read
# access to config.storage.topic
- resource:
type: topic
name: mirrormaker2-cluster-configs
operations:
- Create
- Describe
- DescribeConfigs
- Read
- Write
# access to status.storage.topic
- resource:
type: topic
name: mirrormaker2-cluster-status
operations:
- Create
- Describe
- DescribeConfigs
- Read
- Write
# access to offset.storage.topic
- 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 the KafkaUserSpec schema reference.
|
-
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.
-
Configure a KafkaMirrorMaker2
resource with the authentication details to connect to the source and target Kafka clusters.
Example MirrorMaker 2 configuration with TLS encryption and mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker-2
spec:
version: 3.8.0
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
pattern: "*.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
pattern: "*.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"
-
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.
-
The user authentication for accessing the source Kafka cluster using the TLS mechanism.
-
The TLS certificates for the target Kafka cluster.
-
The user authentication for accessing the target Kafka cluster.
-
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>
11.10.8. Manually stopping or pausing MirrorMaker 2 connectors
If you are using KafkaMirrorMaker2
resources to configure internal MirrorMaker connectors, use the state
configuration to either stop or pause a connector.
In contrast to the paused state, where the connector and tasks remain instantiated, stopping a connector retains only the configuration, with no active processes.
Stopping a connector from running may be more suitable for longer durations than just pausing.
While a paused connector is quicker to resume, a stopped connector has the advantages of freeing up memory and resources.
Note
|
The state configuration replaces the (deprecated) pause configuration in the KafkaMirrorMaker2ConnectorSpec schema, which allows pauses on connectors.
If you were previously using the pause configuration to pause connectors, we encourage you to transition to using the state configuration only to avoid conflicts.
|
Procedure
-
Find the name of the KafkaMirrorMaker2
custom resource that controls the MirrorMaker 2 connector you want to pause or stop:
kubectl get KafkaMirrorMaker2
-
Edit the KafkaMirrorMaker2
resource to stop or pause the connector.
Example configuration for stopping a MirrorMaker 2 connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
replicas: 3
connectCluster: "my-cluster-target"
clusters:
# ...
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector:
tasksMax: 10
autoRestart:
enabled: true
state: stopped
# ...
Change the state
configuration to stopped
or paused
.
The default state for the connector when this property is not set is running
.
-
Apply the changes to the KafkaMirrorMaker2
configuration.
You can resume the connector by changing state
to running
or removing the configuration.
Note
|
Alternatively, you can expose the Kafka Connect API and use the stop and pause endpoints to stop a connector from running.
For example, PUT /connectors/<connector_name>/stop .
You can then use the resume endpoint to restart it.
|
11.10.9. Manually restarting MirrorMaker 2 connectors
Use the strimzi.io/restart-connector
annotation to manually trigger a restart of a MirrorMaker 2 connector.
Procedure
-
Find the name of the KafkaMirrorMaker2
custom resource that controls the Kafka MirrorMaker 2 connector you want to restart:
kubectl get KafkaMirrorMaker2
-
Find the name of the Kafka MirrorMaker 2 connector to be restarted from the KafkaMirrorMaker2
custom resource:
kubectl describe KafkaMirrorMaker2 <mirrormaker_cluster_name>
-
Use the name of the connector to restart the connector by annotating the KafkaMirrorMaker2
resource in Kubernetes:
kubectl annotate KafkaMirrorMaker2 <mirrormaker_cluster_name> "strimzi.io/restart-connector=<mirrormaker_connector_name>"
In this example, connector my-connector
in the my-mirror-maker-2
cluster is restarted:
kubectl annotate KafkaMirrorMaker2 my-mirror-maker-2 "strimzi.io/restart-connector=my-connector"
-
Wait for the next reconciliation to occur (every two minutes by default).
The MirrorMaker 2 connector is restarted, as long as the annotation was detected by the reconciliation process.
When MirrorMaker 2 accepts the request, the annotation is removed from the KafkaMirrorMaker2
custom resource.
11.10.10. Manually restarting MirrorMaker 2 connector tasks
Use the strimzi.io/restart-connector-task
annotation to manually trigger a restart of a MirrorMaker 2 connector.
Procedure
-
Find the name of the KafkaMirrorMaker2
custom resource that controls the MirrorMaker 2 connector task you want to restart:
kubectl get KafkaMirrorMaker2
-
Find the name of the connector and the ID of the task to be restarted from the KafkaMirrorMaker2
custom resource:
kubectl describe KafkaMirrorMaker2 <mirrormaker_cluster_name>
Task IDs are non-negative integers, starting from 0.
-
Use the name and ID to restart the connector task by annotating the KafkaMirrorMaker2
resource in Kubernetes:
kubectl annotate KafkaMirrorMaker2 <mirrormaker_cluster_name> "strimzi.io/restart-connector-task=<mirrormaker_connector_name>:<task_id>"
In this example, task 0
for connector my-connector
in the my-mirror-maker-2
cluster is restarted:
kubectl annotate KafkaMirrorMaker2 my-mirror-maker-2 "strimzi.io/restart-connector-task=my-connector:0"
-
Wait for the next reconciliation to occur (every two minutes by default).
The MirrorMaker 2 connector task is restarted, as long as the annotation was detected by the reconciliation process.
When MirrorMaker 2 accepts the request, the annotation is removed from the KafkaMirrorMaker2
custom resource.
11.11. Configuring Kafka MirrorMaker (deprecated)
Update the spec
properties of the KafkaMirrorMaker
custom 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.
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 .
|
Example KafkaMirrorMaker
custom resource 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
pattern: "*.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
producer:
bootstrapServers: my-target-cluster-kafka-bootstrap:9092
abortOnSendFailure: false # (9)
tls:
trustedCertificates:
- secretName: my-target-cluster-ca-cert
pattern: "*.crt"
authentication:
type: tls
certificateAndKey:
secretName: my-target-secret
certificate: public.crt
key: private.key
config:
compression.type: gzip
batch.size: 8192
include: "my-topic|other-topic" # (10)
resources: # (11)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
logging: # (12)
type: inline
loggers:
mirrormaker.root.logger: INFO
readinessProbe: # (13)
initialDelaySeconds: 15
timeoutSeconds: 5
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
metricsConfig: # (14)
type: jmxPrometheusExporter
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-key
jvmOptions: # (15)
"-Xmx": "1g"
"-Xms": "1g"
image: my-org/my-image:latest # (16)
template: # (17)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
mirrorMakerContainer: # (18)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
tracing: # (19)
type: opentelemetry
-
The number of replica nodes.
-
Bootstrap servers for consumer and producer.
-
Group ID for the consumer.
-
The number of consumer streams.
-
The offset auto-commit interval in milliseconds.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Authentication for consumer or producer, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.
-
Kafka configuration options for consumer and producer.
-
If the abortOnSendFailure
property is set to true
, Kafka MirrorMaker will exit and the container will restart following a send failure for a message.
-
A list of included topics mirrored from source to target Kafka cluster.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Specified loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. MirrorMaker has a single logger called mirrormaker.root.logger
. You can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
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
.
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka MirrorMaker.
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
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.
|
11.12. Configuring the Kafka Bridge
Update the spec
properties of the KafkaBridge
custom 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.
Example KafkaBridge
custom resource configuration
# Basic configuration (required)
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# Replicas (required)
replicas: 3 # (1)
# Kafka bootstrap servers (required)
bootstrapServers: <cluster_name>-cluster-kafka-bootstrap:9092 # (2)
# HTTP configuration (required)
http: # (3)
port: 8080
# CORS configuration (optional)
cors: # (4)
allowedOrigins: "https://strimzi.io"
allowedMethods: "GET,POST,PUT,DELETE,OPTIONS,PATCH"
# Resources requests and limits (recommended)
resources: # (5)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# TLS configuration (optional)
tls: # (6)
trustedCertificates:
- secretName: my-cluster-cluster-cert
pattern: "*.crt"
- secretName: my-cluster-cluster-cert
certificate: ca2.crt
# Authentication (optional)
authentication: # (7)
type: tls
certificateAndKey:
secretName: my-secret
certificate: public.crt
key: private.key
# Consumer configuration (optional)
consumer: # (8)
config:
auto.offset.reset: earliest
# Producer configuration (optional)
producer: # (9)
config:
delivery.timeout.ms: 300000
# Logging configuration (optional)
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
# JVM options (optional)
jvmOptions: # (11)
"-Xmx": "1g"
"-Xms": "1g"
# Readiness probe (optional)
readinessProbe: # (12)
initialDelaySeconds: 15
timeoutSeconds: 5
# Liveness probe (optional)
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
# Custom image (optional)
image: my-org/my-image:latest # (13)
# Pod template (optional)
template: # (14)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
bridgeContainer: # (15)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
# Tracing configuration (optional)
tracing:
type: opentelemetry # (16)
-
The number of replica nodes.
-
Bootstrap address for connection to the target Kafka cluster. The address takes the format <cluster_name>-kafka-bootstrap:<port_number>
. The Kafka cluster doesn’t need to be managed by Strimzi or deployed to a Kubernetes cluster.
-
HTTP access to Kafka brokers.
-
CORS access specifying selected resources and access methods. Additional HTTP headers in requests describe the origins that are permitted access to the Kafka cluster.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
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.
-
Consumer configuration options.
-
Producer configuration options.
-
Specified Kafka Bridge loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. For the Kafka Bridge loggers, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running the Kafka Bridge.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
Optional: Container image configuration, which is recommended only in special situations.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
11.13. Configuring CPU and memory resource limits and requests
By default, the Strimzi Cluster Operator does not specify CPU and memory resource requests and limits for its deployed operands.
Ensuring an adequate allocation of resources is crucial for maintaining stability and achieving optimal performance in Kafka.
The ideal resource allocation depends on your specific requirements and use cases.
11.14. Restrictions on Kubernetes labels
Kubernetes labels make it easier to organize, manage, and discover Kubernetes resources within your applications.
The Cluster Operator is responsible for applying the following Kubernetes labels to the operands it deploys.
These labels cannot be overridden through template
configuration of Strimzi resources:
-
app.kubernetes.io/name
: Identifies the component type within Strimzi, such as kafka
, zookeeper
, and`cruise-control`.
-
app.kubernetes.io/instance
: Represents the name of the custom resource to which the operand belongs to. For instance, if a Kafka custom resource is named my-cluster
, this label will bear that name on the associated pods.
-
app.kubernetes.io/part-of
: Similar to app.kubernetes.io/instance
, but prefixed with strimzi-
.
-
app.kubernetes.io/managed-by
: Defines the application responsible for managing the operand, such as strimzi-cluster-operator
or strimzi-user-operator
.
Example Kubernetes labels on a Kafka pod when deploying a Kafka
custom resource named my-cluster
apiVersion: kafka.strimzi.io/v1beta2
kind: Pod
metadata:
name: my-cluster-kafka-0
labels:
app.kubernetes.io/instance: my-cluster
app.kubernetes.io/managed-by: strimzi-cluster-operator
app.kubernetes.io/name: kafka
app.kubernetes.io/part-of: strimzi-my-cluster
spec:
# ...
11.15. Configuring pod scheduling
To avoid performance degradation caused by resource conflicts between applications scheduled on the same Kubernetes node, you can schedule Kafka pods separately from critical workloads.
This can be achieved by either selecting specific nodes or dedicating a set of nodes exclusively for Kafka.
11.15.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:
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.
11.15.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.
Procedure
-
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.
-
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.
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
11.15.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.
Procedure
-
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:
# ...
-
Create or update the resource.
This can be done using kubectl apply
:
kubectl apply -f <kafka_configuration_file>
11.15.4. Configuring node affinity in Kafka components
Procedure
-
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.
-
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:
# ...
-
Create or update the resource.
This can be done using kubectl apply
:
kubectl apply -f <kafka_configuration_file>
11.15.5. Setting up dedicated nodes and scheduling pods on them
Procedure
-
Select the nodes which should be used as dedicated.
-
Make sure there are no workloads scheduled on these nodes.
-
Set the taints on the selected nodes:
This can be done using kubectl taint
:
kubectl taint node NAME-OF-NODE dedicated=Kafka:NoSchedule
-
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
-
Edit the affinity
and tolerations
properties in the resource specifying the cluster deployment.
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:
# ...
-
Create or update the resource.
This can be done using kubectl apply
:
kubectl apply -f <kafka_configuration_file>
11.16. Disabling pod disruption budget generation
Strimzi generates pod disruption budget resources for Kafka, Kafka Connect worker, MirrorMaker2 worker, and Kafka Bridge worker nodes.
If you want to use custom pod disruption budget resources, you can set the STRIMZI_POD_DISRUPTION_BUDGET_GENERATION
environment variable to false
in the Cluster Operator configuration.
For more information, see Configuring the Cluster Operator.
11.17. Configuring logging levels
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:
Example inline
logging configuration
# ...
logging:
type: inline
loggers:
kafka.root.logger.level: INFO
# ...
Example external
logging configuration
# ...
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.
11.17.1. Logging options for Kafka components and operators
For more information on configuring logging for specific Kafka components or operators, see the following sections.
11.17.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
-
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"
# ...
-
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.
# ...
logging:
type: external
valueFrom:
configMapKeyRef:
name: logging-configmap
key: log4j.properties
# ...
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
11.17.3. Configuring 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.log4j2.properties
values 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
With this ConfigMap, you can control various aspects of logging, including the root logger level, log output format, and log levels for different components.
The monitorInterval
setting, determines how often the logging configuration is reloaded.
You can also control the logging levels for the Kafka AdminClient
, ZooKeeper ZKTrustManager
, Netty, and the OkHttp client.
Netty is a framework used in Strimzi for network communication, and OkHttp is a library used for making HTTP requests.
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 .
|
11.17.4. Adding logging filters to Strimzi 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)
-
The MarkerFilter
type compares a specified marker for filtering.
-
The onMatch
property accepts the log if the marker matches.
-
The onMismatch
property rejects the log if the marker does not match.
-
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
-
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
-
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
-
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)
# ...
-
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
-
Apply the changes by deploying the Cluster Operator:
create -f install/cluster-operator -n my-cluster-operator-namespace
11.17.5. Lock acquisition warnings for cluster operations
The Cluster Operator ensures that only one operation runs at a time for each cluster by using locks.
If another operation attempts to start while a lock is held, it waits until the current operation completes.
Operations such as cluster creation, rolling updates, scaling down, and scaling up are managed by the Cluster Operator.
If acquiring a lock takes longer than the configured timeout (STRIMZI_OPERATION_TIMEOUT_MS
), a DEBUG message is logged:
Example DEBUG message for lock acquisition
DEBUG AbstractOperator:406 - Reconciliation #55(timer) Kafka(myproject/my-cluster): Failed to acquire lock lock::myproject::Kafka::my-cluster within 10000ms.
Timed-out operations are retried during the next periodic reconciliation in intervals defined by STRIMZI_FULL_RECONCILIATION_INTERVAL_MS
(by default 120 seconds).
If an INFO message continues to appear with the same same reconciliation number, it might indicate a lock release error:
Example INFO message for reconciliation
INFO AbstractOperator:399 - Reconciliation #1(watch) Kafka(myproject/my-cluster): Reconciliation is in progress
Restarting the Cluster Operator can resolve such issues.
11.18. Using ConfigMaps to add configuration
Add specific configuration to your Strimzi deployment using ConfigMap
resources.
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 the following types of configuration data:
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
# ...
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.
template
properties allow data from a ConfigMap
or Secret
to be mounted in a pod 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:
# ...
template:
connectContainer:
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.
11.18.1. Naming custom ConfigMaps
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.
11.19. Loading configuration values from external sources
Use configuration providers 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.
You reference the external source in the configuration of the component and provide access rights.
The provider loads data without needing to restart the Kafka component or extracting files, even when referencing a new external source.
For example, use providers to supply the credentials for the Kafka Connect connector configuration.
The configuration must include any access rights to the external source.
11.19.1. Enabling configuration providers
You can enable one or more configuration providers using the config.providers
properties in the spec
configuration of a component.
Example configuration to enable a 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
config.providers.env.class: org.apache.kafka.common.config.provider.EnvVarConfigProvider
# ...
- KubernetesSecretConfigProvider
-
Loads configuration data from Kubernetes secrets.
You specify the name of the secret and the key within the secret where the configuration data is stored.
This provider is useful for storing sensitive configuration data like passwords or other user credentials.
- KubernetesConfigMapConfigProvider
-
Loads configuration data from Kubernetes config maps.
You specify the name of the config map and the key within the config map where the configuration data is stored.
This provider is useful for storing non-sensitive configuration data.
- EnvVarConfigProvider
-
Loads configuration data from environment variables.
You specify the name of the environment variable where the configuration data is stored.
This provider is useful for configuring applications running in containers, for example, to load certificates or JAAS configuration from environment variables mapped from secrets.
- FileConfigProvider
-
Loads configuration data from a file.
You specify the path to the file where the configuration data is stored.
This provider is useful for loading configuration data from files that are mounted into containers.
- DirectoryConfigProvider
-
Loads configuration data from files within a directory.
You specify the path to the directory where the configuration files are stored.
This provider is useful for loading multiple configuration files and for organizing configuration data into separate files.
To use KubernetesSecretConfigProvider
and KubernetesConfigMapConfigProvider
, which are part of the Kubernetes Configuration Provider plugin, you must set up access rights to the namespace that contains the configuration file.
You can use the other providers without setting up access rights.
You can supply connector configuration for Kafka Connect or MirrorMaker 2 in this way by doing the following:
-
Mount config maps or secrets into the Kafka Connect pod as environment variables or volumes
-
Enable EnvVarConfigProvider
, FileConfigProvider
, or DirectoryConfigProvider
in the Kafka Connect or MirrorMaker 2 configuration
-
Pass connector configuration using the template
property in the spec
of the KafkaConnect
or KafkaMirrorMaker2
resource
Using providers help prevent the passing of restricted information through the Kafka Connect REST interface.
You can use this approach in the following scenarios:
-
Mounting environment variables with the values a connector uses to connect and communicate with a data source
-
Mounting a properties file with values that are used to configure Kafka Connect connectors
-
Mounting files in a directory that contains values for the TLS truststore and keystore used by a connector
Note
|
A restart is required when using a new Secret or ConfigMap for a connector, which can disrupt other connectors.
|
11.19.2. Loading configuration values from secrets or config maps
Use the KubernetesSecretConfigProvider
to provide configuration properties from a secret or the KubernetesConfigMapConfigProvider
to provide configuration properties from a config map.
In this procedure, a config map provides configuration properties for a connector.
The properties are specified as key values of the config map.
The config map is mounted into the Kafka Connect pod as a volume.
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a config map containing the connector configuration.
Example config map with connector properties
apiVersion: v1
kind: ConfigMap
metadata:
name: my-connector-configuration
data:
option1: value1
option2: value2
Procedure
-
Configure the KafkaConnect
resource.
The specification shown here can support loading values from config maps and secrets.
Example Kafka Connect configuration to use config maps and secrets
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.configmaps.class: io.strimzi.kafka.KubernetesConfigMapConfigProvider # (2)
config.providers.secrets.class: io.strimzi.kafka.KubernetesSecretConfigProvider # (3)
# ...
-
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
.
-
KubernetesConfigMapConfigProvider
provides values from config maps.
-
KubernetesSecretConfigProvider
provides values from secrets.
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
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.
-
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.
-
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}
# ...
# ...
The placeholder structure is configmaps:<path_and_file_name>:<property>
.
KubernetesConfigMapConfigProvider
reads and extracts the option1
property value from the external config map.
11.19.3. Loading configuration values from environment variables
Use the EnvVarConfigProvider
to provide configuration properties as environment variables.
Environment variables can contain values from config maps or secrets.
In this procedure, environment variables provide configuration properties for a connector to communicate with Amazon AWS.
The connector must be able to read the AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
.
The values of the environment variables are derived from a secret mounted into the Kafka Connect pod.
Note
|
The names of user-defined environment variables cannot start with KAFKA_ or STRIMZI_ .
|
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a secret containing the connector configuration.
Example secret with values for environment variables
apiVersion: v1
kind: Secret
metadata:
name: aws-creds
type: Opaque
data:
awsAccessKey: QUtJQVhYWFhYWFhYWFhYWFg=
awsSecretAccessKey: Ylhsd1lYTnpkMjl5WkE=
Procedure
-
Configure the KafkaConnect
resource.
Example Kafka Connect configuration to use external environment variables
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: org.apache.kafka.common.config.provider.EnvVarConfigProvider # (2)
# ...
template:
connectContainer:
env:
- name: AWS_ACCESS_KEY_ID # (3)
valueFrom:
secretKeyRef:
name: aws-creds # (4)
key: awsAccessKey # (5)
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws-creds
key: awsSecretAccessKey
# ...
-
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
.
-
EnvVarConfigProvider
provides values from environment variables.
-
The environment variable takes a value from the secret.
-
The name of the secret containing the environment variable.
-
The name of the key stored in the secret.
Note
|
The secretKeyRef property references keys in a secret.
If you are using a config map instead of a secret, use the configMapKeyRef property.
|
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
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:AWS_ACCESS_KEY_ID}
option: ${env:AWS_SECRET_ACCESS_KEY}
# ...
# ...
The placeholder structure is env:<environment_variable_name>
.
EnvVarConfigProvider
reads and extracts the environment variable values from the mounted secret.
11.19.4. Loading configuration values from a file within a directory
Use the FileConfigProvider
to provide configuration properties from a file within a directory.
Files can be stored in config maps or secrets.
In this procedure, a file provides configuration properties for a connector.
A database name and password are specified as properties of a secret.
The secret is mounted to the Kafka Connect pod as a volume.
Volumes are mounted on the path /mnt/<volume-name>
.
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a secret containing the connector configuration.
Example secret with database properties
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
stringData:
connector.properties: |- # (1)
dbUsername: my-username # (2)
dbPassword: my-password
-
The connector configuration in properties file format.
-
Database username and password properties used in the configuration.
Procedure
-
Configure the KafkaConnect
resource.
Example Kafka Connect configuration to use an external property file
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
spec:
# ...
config:
config.providers: file # (1)
config.providers.file.class: org.apache.kafka.common.config.provider.FileConfigProvider # (2)
#...
template:
pod:
volumes:
- name: connector-config-volume # (3)
secret:
secretName: mysecret # (4)
connectContainer:
volumeMounts:
- name: connector-config-volume # (5)
mountPath: /mnt/mysecret # (6)
-
The alias for the configuration provider is used to define other configuration parameters.
-
FileConfigProvider
provides values from properties files.
The parameter uses the alias from config.providers
, taking the form config.providers.${alias}.class
.
-
The name of the volume containing the secret.
-
The name of the secret.
-
The name of the mounted volume, which must match the volume name in the volumes
list.
-
The path where the secret is mounted, which must start with /mnt/
.
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
Reference the file properties in the connector configuration as placeholders.
Example connector configuration referencing the file
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: io.debezium.connector.mysql.MySqlConnector
tasksMax: 2
config:
database.hostname: 192.168.99.1
database.port: "3306"
database.user: "${file:/mnt/mysecret/connector.properties:dbUsername}"
database.password: "${file:/mnt/mysecret/connector.properties:dbPassword}"
database.server.id: "184054"
#...
The placeholder structure is file:<path_and_file_name>:<property>
.
FileConfigProvider
reads and extracts the database username and password property values from the mounted secret.
11.19.5. Loading configuration values from multiple files within a directory
Use the DirectoryConfigProvider
to provide configuration properties from multiple files within a directory.
Files can be config maps or secrets.
In this procedure, a secret provides the TLS keystore and truststore user credentials for a connector.
The credentials are in separate files.
The secrets are mounted into the Kafka Connect pod as volumes.
Volumes are mounted on the path /mnt/<volume-name>
.
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a secret containing the user credentials.
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
ca.crt: <public_key> # Public key of the clients CA used to sign this user certificate
user.crt: <user_certificate> # Public key of the user
user.key: <user_private_key> # Private key of the user
user.p12: <store> # PKCS #12 store for user certificates and keys
user.password: <password_for_store> # Protects the PKCS #12 store
The my-user
secret provides the keystore credentials (user.crt
and user.key
) for the connector.
The <cluster_name>-cluster-ca-cert
secret generated when deploying the Kafka cluster provides the cluster CA certificate as truststore credentials (ca.crt
).
Procedure
-
Configure the KafkaConnect
resource.
Example Kafka Connect configuration to use external property files
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
spec:
# ...
config:
config.providers: directory # (1)
config.providers.directory.class: org.apache.kafka.common.config.provider.DirectoryConfigProvider # (2)
#...
template:
pod:
volumes:
- name: my-user-volume # (3)
secret:
secretName: my-user # (4)
- name: cluster-ca-volume
secret:
secretName: my-cluster-cluster-ca-cert
connectContainer:
volumeMounts:
- name: my-user-volume # (5)
mountPath: /mnt/my-user # (6)
- name: cluster-ca-volume
mountPath: /mnt/cluster-ca
-
The alias for the configuration provider is used to define other configuration parameters.
-
DirectoryConfigProvider
provides values from files in a directory. The parameter uses the alias from config.providers
, taking the form config.providers.${alias}.class
.
-
The name of the volume containing the secret.
-
The name of the secret.
-
The name of the mounted volume, which must match the volume name in the volumes
list.
-
The path where the secret is mounted, which must start with /mnt/
.
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
Reference the file properties in the connector configuration as placeholders.
Example connector configuration referencing the files
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: io.debezium.connector.mysql.MySqlConnector
tasksMax: 2
config:
# ...
database.history.producer.security.protocol: SSL
database.history.producer.ssl.truststore.type: PEM
database.history.producer.ssl.truststore.certificates: "${directory:/mtn/cluster-ca:ca.crt}"
database.history.producer.ssl.keystore.type: PEM
database.history.producer.ssl.keystore.certificate.chain: "${directory:/mnt/my-user:user.crt}"
database.history.producer.ssl.keystore.key: "${directory:/mnt/my-user:user.key}"
#...
The placeholder structure is directory:<path>:<file_name>
.
DirectoryConfigProvider
reads and extracts the credentials from the mounted secrets.
11.20. Customizing Kubernetes resources
A Strimzi deployment creates Kubernetes resources, such as Deployment
, Pod
, and Service
resources.
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 the following:
To make the changes to a Kubernetes resource, you can use the template
property within the spec
section of various Strimzi custom resources.
Here is a list of the custom resources where you can apply the changes:
The Strimzi Custom Resource API Reference provides more details about the customizable fields.
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
# ...
11.20.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.
Currently, the image pull policy can only be customized 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.
11.20.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
# ...
# ...
</div>
</div>
12. Using the Topic Operator to manage Kafka topics
The KafkaTopic
resource configures topics, including partition and replication factor settings.
When you create, modify, or delete a topic using KafkaTopic
, the Topic Operator ensures that these changes are reflected in the Kafka cluster.
12.1. Topic management
The KafkaTopic
resource is responsible for managing a single topic within a Kafka cluster.
The Topic Operator operates as follows:
-
When a KafkaTopic
is created, deleted, or changed, the Topic Operator performs the corresponding operation on the Kafka topic.
If a topic is created, deleted, or modified directly within the Kafka cluster, without the presence of a corresponding KafkaTopic
resource, the Topic Operator does not manage that topic.
The Topic Operator will only manage Kafka topics associated with KafkaTopic
resources and does not interfere with topics managed independently within the Kafka cluster.
If a KafkaTopic
does exist for a Kafka topic, any configuration changes made outside the resource are reverted.
The Topic Operator can detect cases where where multiple KafkaTopic
resources are attempting to manage a Kafka topic using the same .spec.topicName
.
Only the oldest resource is reconciled, while the other resources fail with a resource conflict error.
12.2. Topic naming conventions
A KafkaTopic
resource includes a name for the topic and a label that identifies the name of the Kafka cluster it belongs to.
Label identifying a Kafka cluster for topic handling
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: topic-name-1
labels:
strimzi.io/cluster: my-cluster
spec:
topicName: topic-name-1
The label provides the cluster name of the Kafka
resource.
The Topic Operator uses the label as a mechanism for determining which KafkaTopic
resources to manage.
If the label does not match the Kafka cluster, the Topic Operator cannot see the KafkaTopic
, and the topic is not created.
Kafka and Kubernetes have their own naming validation rules, and a Kafka topic name might not be a valid resource name in Kubernetes.
If possible, try and stick to a naming convention that works for both.
Consider the following guidelines:
-
Use topic names that reflect the nature of the topic
-
Be concise and keep the name under 63 characters
-
Use all lower case and hyphens
-
Avoid special characters, spaces or symbols
The KafkaTopic
resource allows you to specify the Kafka topic name using the metadata.name
field.
However, if the desired Kafka topic name is not a valid Kubernetes resource name, you can use the spec.topicName
property to specify the actual name.
The spec.topicName
field is optional, and when it’s absent, the Kafka topic name defaults to the metadata.name
of the topic.
When a topic is created, the topic name cannot be changed later.
Example of supplying a valid Kafka topic name
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic-1 # (1)
spec:
topicName: My.Topic.1 # (2)
# ...
-
A valid topic name that works in Kubernetes.
-
A Kafka topic name that uses upper case and periods, which are invalid in Kubernetes.
If more than one KafkaTopic
resource refers to the same Kafka topic, the resource that was created first is considered to be the one managing the topic.
The status of the newer resources is updated to indicate a conflict, and their Ready
status is changed to False
.
A Kafka client application, such as Kafka Streams, can automatically create topics with invalid Kubernetes resource names.
If you want to manage these topics, you must create KafkaTopic
resources with a different .metadata.name
, as shown in the previous example.
Note
|
For more information on the requirements for identifiers and names in a cluster, refer to the Kubernetes documentation Object Names and IDs.
|
12.3. Handling changes to topics
Configuration changes only go in one direction: from the KafkaTopic
resource to the Kafka topic.
Any changes to a Kafka topic managed outside the KafkaTopic
resource are reverted.
If you are reverting back to a version of Strimzi earlier than 0.41, which uses internal topics 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.
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-topics
command, specifying the bootstrap address of the Kafka cluster.
For example:
kubectl run kafka-admin -ti --image=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0 --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.
12.3.3. Automatic creation of topics
Applications can trigger the automatic creation of topics in the Kafka cluster.
By default, the Kafka broker configuration auto.create.topics.enable
is set to true
, allowing the broker to create topics automatically when an application attempts to produce or consume from a non-existing topic.
Applications might also use the Kafka AdminClient
to automatically create topics.
When an application is deployed along with its KafkaTopic
resources, it is possible that automatic topic creation in the cluster happens before the Topic Operator can react to the KafkaTopic
.
The topics created for an application deployment are initially created with default topic configuration.
If the Topic Operator attempts to reconfigure the topics based on KafkaTopic
resource specifications included with the application deployment, the operation might fail because the required change to the configuration is not allowed.
For example, if the change means lowering the number of topic partitions.
For this reason, it is recommended to disable auto.create.topics.enable
in the Kafka cluster configuration.
12.4. Configuring Kafka topics
Use the properties of the KafkaTopic
resource to configure Kafka topics.
Changes made to topic configuration in the KafkaTopic
are propagated to Kafka.
You can use kubectl apply
to create or modify topics, and kubectl delete
to delete existing topics.
To be able to delete topics, delete.topic.enable
must be set to true
(default) in the spec.kafka.config
of the Kafka resource.
This procedure shows how to create a topic with 10 partitions and 2 replicas.
Before you begin
The KafkaTopic resource does not allow the following changes:
-
Renaming the topic defined in spec.topicName
. A mismatch between spec.topicName
and status.topicName
will be detected.
-
Decreasing the number of partitions using spec.partitions
(not supported by Kafka).
-
Modifying the number of replicas specified in spec.replicas
.
Warning
|
Increasing spec.partitions for topics with keys will alter the partitioning of records, which can cause issues, especially when the topic uses semantic partitioning.
|
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
-
Configure the KafkaTopic
resource.
Example Kafka topic configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic-1
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 my-topic-1 -o yaml .
|
-
Create the KafkaTopic
resource in Kubernetes.
kubectl apply -f <topic_config_file>
-
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
.
-
If the READY
column stays blank, get more details on the status from the resource YAML or from the Topic Operator logs.
Status 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
12.5. Configuring topics for replication and number of partitions
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)
#...
-
The number of partitions for the topic.
-
The number of replica topic partitions. Changing the number of replicas in the topic configuration requires a deployment of Cruise Control.
For more information, see Using Cruise Control to modify topic replication factor.
-
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.
Replicas need to be reassigned when adding or removing brokers (see Scaling clusters by adding or removing brokers).
|
12.6. Managing KafkaTopic resources without impacting Kafka topics
This procedure describes how to convert Kafka topics that are currently managed through the KafkaTopic
resource into unmanaged topics.
This capability can be useful in various scenarios.
For instance, you might want to update the metadata.name
of a KafkaTopic
resource.
You can only do that by deleting the original KafkaTopic
resource and recreating a new one.
By annotating a KafkaTopic
resource with strimzi.io/managed=false
, you indicate that the Topic Operator should no longer manage that particular topic.
This allows you to retain the Kafka topic while making changes to the resource’s configuration or other administrative tasks.
Procedure
-
Annotate the KafkaTopic
resource in Kubernetes, setting strimzi.io/managed
to false
:
kubectl annotate kafkatopic my-topic-1 strimzi.io/managed="false" --overwrite
Specify the metadata.name
of the topic in your KafkaTopic
resource, which is my-topic-1
in this example.
-
Check the status of the KafkaTopic
resource to make sure the request was successful:
kubectl get kafkatopic my-topic-1 -o yaml
Example topic with an Unmanaged
status
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 124
name: my-topic-1
finalizer:
- strimzi.io/topic-operator
labels:
strimzi.io/cluster: my-cluster
annotations:
strimzi.io/managed: "false"
spec:
partitions: 10
replicas: 2
config:
retention.ms: 432000000
status:
observedGeneration: 124 # (1)
conditions:
- lastTransitionTime: "2024-08-22T06:07:57.671085635Z"
status: "True"
type: Unmanaged # (2)
-
The value of metadata.generation
must match status.observedGeneration
.
-
The Unmanaged
condition means that the KafkaTopic
is no longer reconciled.
-
You can now make changes to the KafkaTopic
resource without it affecting the Kafka topic it was managing.
For example, to change the metadata.name
, do as follows:
-
Delete the original KafkTopic
resource:
kubectl delete kafkatopic <kafka_topic_name>
-
Recreate the KafkTopic
resource with a different metadata.name
, but use spec.topicName
to refer to the same topic that was managed by the original
-
If you haven’t deleted the original KafkaTopic
resource, and you wish to resume management of the Kafka topic again, set the strimzi.io/managed
annotation to true
or remove the annotation.
12.7. Enabling topic management for existing Kafka topics
This procedure describes how to enable topic management for topics that are not currently managed through the KafkaTopic
resource.
You do this by creating a matching KafkaTopic
resource.
Procedure
-
Create a KafkaTopic
resource with a metadata.name
that is the same as the Kafka topic.
Or use spec.topicName
if the name of the topic in Kafka would not be a legal Kubernetes resource name.
Example Kafka topic configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic-1
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 2
In this example, the Kafka topic is named my-topic-1
.
The Topic Operator checks whether the topic is managed by another KafkaTopic
resource.
If it is, the older resource takes precedence and a resource conflict error is returned in the status of the new resource.
-
Apply the KafkaTopic
resource:
kubectl apply -f <topic_configuration_file>
-
Wait for the operator to update the topic in Kafka.
The operator updates the Kafka topic with the spec
of the KafkaTopic
that has the same name.
-
Check the status of the KafkaTopic
resource to make sure the request was successful:
oc get kafkatopics my-topic-1 -o yaml
Example topic with a Ready
status
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 1
name: my-topic-1
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 2
# ...
status:
observedGeneration: 1 # (1)
topicName: my-topic-1
conditions:
- type: Ready
status: True
lastTransitionTime: 20230301T103000Z
-
Successful reconciliation of the resource means the topic is now managed.
The value of metadata.generation
(the current version of the deployment) must match status.observedGeneration
(the latest reconciliation of the resource).
12.8. Deleting managed topics
The Topic Operator supports the deletion of topics managed through the KafkaTopic
resource with or without Kubernetes finalizers.
This is determined by the STRIMZI_USE_FINALIZERS
Topic Operator environment variable.
By default, this is set to true
, though it can be set to false
in the Topic Operator env
configuration if you do not want the Topic Operator to add finalizers.
Finalizers ensure orderly and controlled deletion of KafkaTopic
resources.
A finalizer for the Topic Operator is added to the metadata of the KafkaTopic
resource:
Finalizer to control topic deletion
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 1
name: my-topic-1
finalizers:
- strimzi.io/topic-operator
labels:
strimzi.io/cluster: my-cluster
In this example, the finalizer is added for topic my-topic-1
.
The finalizer prevents the topic from being fully deleted until the finalization process is complete.
If you then delete the topic using kubectl delete kafkatopic my-topic-1
, a timestamp is added to the metadata:
Finalizer timestamp on deletion
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 1
name: my-topic-1
finalizers:
- strimzi.io/topic-operator
labels:
strimzi.io/cluster: my-cluster
deletionTimestamp: 20230301T000000.000
The resource is still present.
If the deletion fails, it is shown in the status of the resource.
When the finalization tasks are successfully executed, the finalizer is removed from the metadata, and the resource is fully deleted.
Finalizers also serve to prevent related resources from being deleted.
If the Topic Operator is not running, it won’t be able to remove its finalizer from the metadata.finalizers
.
And any attempt to directly delete the KafkaTopic
resources or the namespace will fail or timeout, leaving the namespace in a stuck terminating state.
If this happens, you can bypass the finalization process by removing the finalizers on topics.
12.9. Removing finalizers on topics
If the Topic Operator is not running, and you want to bypass the finalization process when deleting managed topics, you must remove the finalizers.
You can do this manually by editing the resources directly or by using a command.
To remove finalizers on all topics, use the following command:
Removing finalizers on topics
kubectl get kt -o=json | jq '.items[].metadata.finalizers = null' | kubectl apply -f -
The command uses the jq
command line JSON parser tool to modify the KafkaTopic
(kt
) resources by setting the finalizers to null
.
You can also use the command for a specific topic:
Removing a finalizer on a specific topic
kubectl get kt <topic_name> -o=json | jq '.metadata.finalizers = null' | kubectl apply -f -
After running the command, you can go ahead and delete the topics.
Alternatively, if the topics were already being deleted but were blocked due to outstanding finalizers then their deletion should complete.
Warning
|
Be careful when removing finalizers, as any cleanup operations associated with the finalization process are not performed if the Topic Operator is not running.
For example, if you remove the finalizer from a KafkaTopic resource and subsequently delete the resource, the related Kafka topic won’t be deleted.
|
12.10. Considerations when disabling topic deletion
When the delete.topic.enable
configuration in Kafka is set to false
, topics cannot be deleted.
This might be required in certain scenarios, but it introduces a consideration when using the Topic Operator.
As topics cannot be deleted, finalizers added to the metadata of a KafkaTopic
resource to control topic deletion are never removed by the Topic Operator (though they can be removed manually).
Similarly, any Custom Resource Definitions (CRDs) or namespaces associated with topics cannot be deleted.
Before configuring delete.topic.enable=false
, assess these implications to ensure it aligns with your specific requirements.
Note
|
To avoid using finalizers, you can set the STRIMZI_USE_FINALIZERS Topic Operator environment variable to false .
|
12.11. Tuning request batches for topic operations
The Topic Operator uses the request batching capabilities of the Kafka Admin API for operations on topic resources.
You can fine-tune the batching mechanism using the following operator configuration properties:
-
STRIMZI_MAX_QUEUE_SIZE
to set the maximum size of the topic event queue.
The default value is 1024.
-
STRIMZI_MAX_BATCH_SIZE
to set the maximum number of topic events allowed in a single batch.
The default value is 100.
-
MAX_BATCH_LINGER_MS
to specify the maximum time to wait for a batch to accumulate items before processing.
The default is 100 milliseconds.
If the maximum size of the request batching queue is exceeded, the Topic Operator shuts down and is restarted.
To prevent frequent restarts, consider adjusting the STRIMZI_MAX_QUEUE_SIZE
property to accommodate the typical load.
13. Using the User Operator to manage Kafka users
When you create, modify or delete a user using the KafkaUser
resource,
the User Operator ensures that these changes are reflected in the Kafka cluster.
13.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.
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 a Kafka cluster.
Procedure
-
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-1
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: "*"
-
Create the KafkaUser
resource in Kubernetes.
kubectl apply -f <user_config_file>
-
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
.
-
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
14. Setting up client access to a Kafka cluster
After you have deployed Strimzi, you can set up client access to your Kafka cluster.
To verify the deployment, you can deploy example producer and consumer clients.
Otherwise, create listeners that provide client access within or outside the Kubernetes cluster.
14.1. Deploying example clients
Send and receive messages from a Kafka cluster installed on Kubernetes.
This procedure describes how to deploy Kafka clients to the Kubernetes cluster, then produce and consume messages to test your installation.
The clients are deployed using the Kafka container image.
Procedure
-
Deploy a Kafka producer.
This example deploys a Kafka producer that connects to the Kafka cluster my-cluster
.
A topic named my-topic
is created.
Deploying a Kafka producer to Kubernetes
kubectl run kafka-producer -ti --image=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0 --rm=true --restart=Never -- bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9092 --topic my-topic
-
Type a message into the console where the producer is running.
-
Press Enter to send the message.
-
Deploy a Kafka consumer.
The consumer should consume messages produced to my-topic
in the Kafka cluster my-cluster
.
Deploying a Kafka consumer to Kubernetes
kubectl run kafka-consumer -ti --image=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0 --rm=true --restart=Never -- bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9092 --topic my-topic --from-beginning
-
Confirm that you see the incoming messages in the consumer console.
14.2. Configuring listeners to connect to Kafka
Use listeners to enable client connections to Kafka.
Strimzi provides a generic GenericKafkaListener
schema with properties to configure listeners through the Kafka
resource.
When configuring a Kafka cluster, you specify a listener type
based on your requirements, environment, and infrastructure.
Services, routes, load balancers, and ingresses for clients to connect to a cluster are created according to the listener type.
Internal and external listener types are supported.
- Internal listeners
-
Use internal listener types to connect clients within a kubernetes cluster.
- External listeners
-
Use external listener types to connect clients outside a Kubernetes cluster.
-
nodeport
to use ports on Kubernetes nodes
-
loadbalancer
to use loadbalancer services
-
ingress
to use Kubernetes Ingress
and the Ingress NGINX Controller for Kubernetes (Kubernetes only)
-
route
to use OpenShift Route
and the default HAProxy router (OpenShift only)
External listeners handle access to a Kafka cluster from networks that require different authentication mechanisms.
For example, loadbalancers might not be suitable for certain infrastructure, such as bare metal, where node ports provide a better option.
Important
|
Do not use the built-in ingress controller on OpenShift, use the route type instead. The Ingress NGINX Controller is only intended for use on Kubernetes. The route type is only supported on OpenShift.
|
Each listener is defined as an array in the Kafka
resource.
Example listener configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: false
configuration:
useServiceDnsDomain: true
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
- name: external1
port: 9094
type: route
tls: true
configuration:
brokerCertChainAndKey:
secretName: my-secret
certificate: my-certificate.crt
key: my-key.key
# ...
You can configure as many listeners as required, as long as their names and ports are unique.
You can also configure listeners for secure connection using authentication.
Note
|
If you scale your Kafka cluster while using external listeners, it might trigger a rolling update of all Kafka brokers. This depends on the configuration.
|
14.3. Listener naming conventions
From the listener configuration, the resulting listener bootstrap and per-broker service names are structured according to the following naming conventions:
Table 17. Listener naming conventions
Listener type |
Bootstrap service name |
Per-Broker service name |
|
<cluster_name>-kafka-bootstrap |
Not applicable |
loadbalancer
nodeport
ingress
route
cluster-ip
|
<cluster_name>-kafka-<listener-name>-bootstrap |
<cluster_name>-kafka-<listener-name>-<idx> |
For example, my-cluster-kafka-bootstrap
, my-cluster-kafka-external1-bootstrap
, and my-cluster-kafka-external1-0
.
The names are assigned to the services, routes, load balancers, and ingresses created through the listener configuration.
You can use certain backwards compatible names and port numbers to transition listeners initially configured under the retired KafkaListeners
schema.
The resulting external listener naming convention varies slightly.
The specific combinations of listener name and port configuration values in the following table are backwards compatible.
Table 18. Backwards compatible listener name and port combinations
Listener name |
Port |
Bootstrap service name |
Per-Broker service name |
|
|
<cluster_name>-kafka-bootstrap |
Not applicable |
|
|
<cluster-name>-kafka-bootstrap |
Not applicable |
|
|
<cluster_name>-kafka-bootstrap |
<cluster_name>-kafka-bootstrap-<idx> |
14.4. Accessing Kafka using node ports
Use node ports to access a Kafka cluster from an external client outside the Kubernetes cluster.
To connect to a broker, you specify a hostname and port number for the Kafka bootstrap address, as well as the certificate used for TLS encryption.
The procedure shows basic nodeport
listener configuration.
You can use listener properties to enable TLS encryption (tls
) and specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the following configuration properties with nodeport
listeners:
preferredNodePortAddressType
-
Specifies the first address type that’s checked as the node address.
externalTrafficPolicy
-
Specifies whether the service routes external traffic to node-local or cluster-wide endpoints.
nodePort
-
Overrides the assigned node port numbers for the bootstrap and broker services.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external4
.
Procedure
-
Configure a Kafka
resource with an external listener set to the nodeport
type.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external4
port: 9094
type: nodeport
tls: true
authentication:
type: tls
# ...
# ...
zookeeper:
# ...
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is created in the secret my-cluster-cluster-ca-cert
.
NodePort
type services are created for each Kafka broker, as well as an external bootstrap service.
Node port services created for the bootstrap and brokers
NAME TYPE CLUSTER-IP PORT(S)
my-cluster-kafka-external4-0 NodePort 172.30.55.13 9094:31789/TCP
my-cluster-kafka-external4-1 NodePort 172.30.250.248 9094:30028/TCP
my-cluster-kafka-external4-2 NodePort 172.30.115.81 9094:32650/TCP
my-cluster-kafka-external4-bootstrap NodePort 172.30.30.23 9094:32650/TCP
The bootstrap address used for client connection is propagated to the status
of the Kafka
resource.
Example status for the bootstrap address
status:
clusterId: Y_RJQDGKRXmNF7fEcWldJQ
conditions:
- lastTransitionTime: '2023-01-31T14:59:37.113630Z'
status: 'True'
type: Ready
kafkaVersion: 3.8.0
listeners:
# ...
- addresses:
- host: ip-10-0-224-199.us-west-2.compute.internal
port: 32650
bootstrapServers: 'ip-10-0-224-199.us-west-2.compute.internal:32650'
certificates:
- |
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
name: external4
observedGeneration: 2
operatorLastSuccessfulVersion: 0.44.0
# ...
-
Retrieve the bootstrap address you can use to access the Kafka cluster from the status of the Kafka
resource.
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external4")].bootstrapServers}{"\n"}'
ip-10-0-224-199.us-west-2.compute.internal:32650
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the bootstrap host and port in your Kafka client as the bootstrap address to connect to the Kafka cluster. For example, ip-10-0-224-199.us-west-2.compute.internal:32650
.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
14.5. Accessing Kafka using loadbalancers
Use loadbalancers to access a Kafka cluster from an external client outside the Kubernetes cluster.
To connect to a broker, you specify a hostname and port number for the Kafka bootstrap address, as well as the certificate used for TLS encryption.
The procedure shows basic loadbalancer
listener configuration.
You can use listener properties to enable TLS encryption (tls
) and specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the following configuration properties with loadbalancer
listeners:
loadBalancerSourceRanges
-
Restricts traffic to a specified list of CIDR (Classless Inter-Domain Routing) ranges.
externalTrafficPolicy
-
Specifies whether the service routes external traffic to node-local or cluster-wide endpoints.
loadBalancerIP
-
Requests a specific IP address when creating a loadbalancer.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external3
.
Procedure
-
Configure a Kafka
resource with an external listener set to the loadbalancer
type.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: tls
# ...
# ...
zookeeper:
# ...
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is also created in the secret my-cluster-cluster-ca-cert
.
loadbalancer
type services and loadbalancers are created for each Kafka broker, as well as an external bootstrap service.
Loadbalancer services and loadbalancers created for the bootstraps and brokers
NAME TYPE CLUSTER-IP PORT(S)
my-cluster-kafka-external3-0 LoadBalancer 172.30.204.234 9094:30011/TCP
my-cluster-kafka-external3-1 LoadBalancer 172.30.164.89 9094:32544/TCP
my-cluster-kafka-external3-2 LoadBalancer 172.30.73.151 9094:32504/TCP
my-cluster-kafka-external3-bootstrap LoadBalancer 172.30.30.228 9094:30371/TCP
NAME EXTERNAL-IP (loadbalancer)
my-cluster-kafka-external3-0 a8a519e464b924000b6c0f0a05e19f0d-1132975133.us-west-2.elb.amazonaws.com
my-cluster-kafka-external3-1 ab6adc22b556343afb0db5ea05d07347-611832211.us-west-2.elb.amazonaws.com
my-cluster-kafka-external3-2 a9173e8ccb1914778aeb17eca98713c0-777597560.us-west-2.elb.amazonaws.com
my-cluster-kafka-external3-bootstrap a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com
The bootstrap address used for client connection is propagated to the status
of the Kafka
resource.
Example status for the bootstrap address
status:
clusterId: Y_RJQDGKRXmNF7fEcWldJQ
conditions:
- lastTransitionTime: '2023-01-31T14:59:37.113630Z'
status: 'True'
type: Ready
kafkaVersion: 3.8.0
listeners:
# ...
- addresses:
- host: >-
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com
port: 9094
bootstrapServers: >-
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com:9094
certificates:
- |
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
name: external3
observedGeneration: 2
operatorLastSuccessfulVersion: 0.44.0
# ...
The DNS addresses used for client connection are propagated to the status
of each loadbalancer service.
Example status for the bootstrap loadbalancer
status:
loadBalancer:
ingress:
- hostname: >-
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com
# ...
-
Retrieve the bootstrap address you can use to access the Kafka cluster from the status of the Kafka
resource.
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external3")].bootstrapServers}{"\n"}'
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com:9094
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the bootstrap host and port in your Kafka client as the bootstrap address to connect to the Kafka cluster. For example, a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com:9094
.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
14.6. Accessing Kafka using an Ingress NGINX Controller for Kubernetes
To be able to use an Ingress NGINX Controller for Kubernetes, add configuration for an ingress
type listener in the Kafka
custom resource.
When applied, the configuration creates a dedicated ingress and service for an external bootstrap and each broker in the cluster.
Clients connect to the bootstrap ingress, which routes them through the bootstrap service to connect to a broker.
Per-broker connections are then established using DNS names, which route traffic from the client to the broker through the broker-specific ingresses and services.
To connect to a broker, you specify a hostname for the ingress bootstrap address, as well as the certificate used for TLS encryption.
For access using an ingress, the port used in the Kafka client is typically 443.
The procedure shows basic ingress
listener configuration.
TLS encryption (tls
) must be enabled.
You can also specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the class
configuration property with ingress
listeners to specify the ingress controller used.
TLS passthrough
Make sure that you enable TLS passthrough in your Ingress NGINX Controller for Kubernetes deployment.
Kafka uses a binary protocol over TCP, but the Ingress NGINX Controller for Kubernetes is designed to work with a HTTP protocol.
To be able to route TCP traffic through ingresses, Strimzi uses TLS passthrough with Server Name Indication (SNI).
SNI helps with identifying and passing connection to Kafka brokers.
In passthrough mode, TLS encryption is always used.
Because the connection passes to the brokers, the listeners use the TLS certificates signed by the internal cluster CA and not the ingress certificates.
To configure listeners to use your own listener certificates, use the brokerCertChainAndKey
property.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external2
.
Procedure
-
Configure a Kafka
resource with an external listener set to the ingress
type.
Specify an ingress hostname for the bootstrap service and for the Kafka brokers in the Kafka cluster.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external2
port: 9094
type: ingress
tls: true # (1)
authentication:
type: tls
configuration:
class: nginx # (2)
hostTemplate: broker-{nodeId}.myingress.com # (3)
bootstrap:
host: bootstrap.myingress.com # (4)
# ...
zookeeper:
# ...
-
For ingress
type listeners, TLS encryption must be enabled (true
).
-
(Optional) Class that specifies the ingress controller to use. You might need to add a class if you have not set up a default and a class name is missing in the ingresses created.
-
The host template used to generate the hostnames for the per-broker Ingress resources.
-
The host used as the hostnames for the bootstrap Ingress resource.
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is created in the secret my-cluster-cluster-ca-cert
.
ClusterIP
type services are created for each Kafka broker, as well as an external bootstrap service.
An ingress
is also created for each service, with a DNS address to expose them using the Ingress NGINX Controller for Kubernetes.
Ingresses created for the bootstrap and brokers
NAME CLASS HOSTS ADDRESS PORTS
my-cluster-kafka-external2-0 nginx broker-0.myingress.com 192.168.49.2 80,443
my-cluster-kafka-external2-1 nginx broker-1.myingress.com 192.168.49.2 80,443
my-cluster-kafka-external2-2 nginx broker-2.myingress.com 192.168.49.2 80,443
my-cluster-kafka-external2-bootstrap nginx bootstrap.myingress.com 192.168.49.2 80,443
The DNS addresses used for client connection are propagated to the status
of each ingress.
Status for the bootstrap ingress
status:
loadBalancer:
ingress:
- ip: 192.168.49.2
# ...
-
Use a target broker to check the client-server TLS connection on port 443 using the OpenSSL s_client
.
openssl s_client -connect broker-0.myingress.com:443 -servername broker-0.myingress.com -showcerts
The server name is the SNI for passing the connection to the broker.
If the connection is successful, the certificates for the broker are returned.
Certificates for the broker
Certificate chain
0 s:O = io.strimzi, CN = my-cluster-kafka
i:O = io.strimzi, CN = cluster-ca v0
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the bootstrap host (from the listener configuration
) and port 443 in your Kafka client as the bootstrap address to connect to the Kafka cluster. For example, bootstrap.myingress.com:443
.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
14.7. Accessing Kafka using OpenShift routes
Use OpenShift routes to access a Kafka cluster from clients outside the OpenShift cluster.
To be able to use routes, add configuration for a route
type listener in the Kafka
custom resource.
When applied, the configuration creates a dedicated route and service for an external bootstrap and each broker in the cluster.
Clients connect to the bootstrap route, which routes them through the bootstrap service to connect to a broker.
Per-broker connections are then established using DNS names, which route traffic from the client to the broker through the broker-specific routes and services.
To connect to a broker, you specify a hostname for the route bootstrap address, as well as the certificate used for TLS encryption.
For access using routes, the port is always 443.
Warning
|
An OpenShift route address comprises the Kafka cluster name, the listener name, the project name, and the domain of the router.
For example, my-cluster-kafka-external1-bootstrap-my-project.domain.com (<cluster_name>-kafka-<listener_name>-bootstrap-<namespace>.<domain>).
Each DNS label (between periods “.”) must not exceed 63 characters, and the total length of the address must not exceed 255 characters.
|
The procedure shows basic listener configuration.
TLS encryption (tls
) must be enabled.
You can also specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the host
configuration property with route
listeners to specify the hostnames used by the bootstrap and per-broker services.
TLS passthrough
TLS passthrough is enabled for routes created by Strimzi.
Kafka uses a binary protocol over TCP, but routes are designed to work with a HTTP protocol.
To be able to route TCP traffic through routes, Strimzi uses TLS passthrough with Server Name Indication (SNI).
SNI helps with identifying and passing connection to Kafka brokers.
In passthrough mode, TLS encryption is always used.
Because the connection passes to the brokers, the listeners use TLS certificates signed by the internal cluster CA and not the ingress certificates.
To configure listeners to use your own listener certificates, use the brokerCertChainAndKey
property.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external1
.
Procedure
-
Configure a Kafka
resource with an external listener set to the route
type.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external1
port: 9094
type: route
tls: true # (1)
authentication:
type: tls
# ...
# ...
zookeeper:
# ...
-
For route
type listeners, TLS encryption must be enabled (true
).
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is created in the secret my-cluster-cluster-ca-cert
.
ClusterIP
type services are created for each Kafka broker, as well as an external bootstrap service.
A route
is also created for each service, with a DNS address (host/port) to expose them using the default OpenShift HAProxy router.
The routes are preconfigured with TLS passthrough.
Routes created for the bootstraps and brokers
NAME HOST/PORT SERVICES PORT TERMINATION
my-cluster-kafka-external1-0 my-cluster-kafka-external1-0-my-project.router.com my-cluster-kafka-external1-0 9094 passthrough
my-cluster-kafka-external1-1 my-cluster-kafka-external1-1-my-project.router.com my-cluster-kafka-external1-1 9094 passthrough
my-cluster-kafka-external1-2 my-cluster-kafka-external1-2-my-project.router.com my-cluster-kafka-external1-2 9094 passthrough
my-cluster-kafka-external1-bootstrap my-cluster-kafka-external1-bootstrap-my-project.router.com my-cluster-kafka-external1-bootstrap 9094 passthrough
The DNS addresses used for client connection are propagated to the status
of each route.
Example status for the bootstrap route
status:
ingress:
- host: >-
my-cluster-kafka-external1-bootstrap-my-project.router.com
# ...
-
Use a target broker to check the client-server TLS connection on port 443 using the OpenSSL s_client
.
openssl s_client -connect my-cluster-kafka-external1-0-my-project.router.com:443 -servername my-cluster-kafka-external1-0-my-project.router.com -showcerts
The server name is the Server Name Indication (SNI) for passing the connection to the broker.
If the connection is successful, the certificates for the broker are returned.
Certificates for the broker
Certificate chain
0 s:O = io.strimzi, CN = my-cluster-kafka
i:O = io.strimzi, CN = cluster-ca v0
-
Retrieve the address of the bootstrap service from the status of the Kafka
resource.
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external1")].bootstrapServers}{"\n"}'
my-cluster-kafka-external1-bootstrap-my-project.router.com:443
The address comprises the Kafka cluster name, the listener name, the project name and the domain of the router (router.com
in this example).
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the address for the bootstrap service and port 443 in your Kafka client as the bootstrap address to connect to the Kafka cluster.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
14.8. Discovering connection details for clients
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 are created for the following services:
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 Kafka 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
Find services by specifying the discovery label when fetching services from the command line or a corresponding API call.
Returning services using the discovery label
kubectl get service -l strimzi.io/discovery=true
Connection details are returned when retrieving the service discovery label.
15. Securing access to a Kafka cluster
Secure connections by configuring Kafka and Kafka users.
Through configuration, you can implement encryption, authentication, and authorization mechanisms.
Kafka configuration
To establish secure access to Kafka, configure the Kafka
resource to set up the following configurations based on your specific requirements:
-
Listeners with specified authentication types to define how clients authenticate
-
Authorization for the entire Kafka cluster
-
Network policies for restricting access
-
Super users for unconstrained access to brokers
Authentication is configured independently for each listener, while authorization is set up for the whole Kafka cluster.
User (client-side) configuration
To enable secure client access to Kafka, configure KafkaUser
resources.
These resources represent clients and determine how they authenticate and authorize with the Kafka cluster.
Configure the KafkaUser
resource to set up the following configurations based on your specific requirements:
-
Authentication that must match the enabled listener authentication
-
Simple authorization to apply Access Control List (ACL) rules
-
Quotas to limit client access based on byte rates or CPU utilization
The User Operator creates the user representing the client and the security credentials used for client authentication, based on the chosen authentication type.
15.1. Configuring client authentication on listeners
Configure client authentication for Kafka brokers when creating listeners.
Specify the listener authentication type using the Kafka.spec.kafka.listeners.authentication
property in the Kafka
resource.
For clients inside the Kubernetes cluster, you can create plain
(without encryption) or tls
internal listeners.
The internal
listener type use a headless service and the DNS names given to the broker pods.
As an alternative to the headless service, you can also create a cluster-ip
type of internal listener to expose Kafka using per-broker ClusterIP
services.
For clients outside the Kubernetes cluster, you create external listeners and specify a connection mechanism,
which can be nodeport
, loadbalancer
, ingress
(Kubernetes only), or route
(OpenShift only).
Supported authentication options:
If you’re using OAuth 2.0 for client access management, user authentication and authorization credentials are handled through the authorization server.
The authentication option you choose depends on how you wish to authenticate client access to Kafka brokers.
Note
|
Try exploring the standard authentication options before using custom authentication. Custom authentication allows for any type of Kafka-supported authentication. It can provide more flexibility, but also adds complexity.
|
Figure 4. Kafka listener authentication options
The listener authentication
property is used to specify an authentication mechanism specific to that listener.
If no authentication
property is specified then the listener does not authenticate clients which connect through that listener.
The listener will accept all connections without authentication.
Authentication must be configured when using the User Operator to manage KafkaUsers
.
The following example shows:
-
A plain
listener configured for SCRAM-SHA-512 authentication
-
A tls
listener with mTLS authentication
-
An external
listener with mTLS authentication
Each listener is configured with a unique name and port within a Kafka cluster.
Important
|
When configuring listeners for client access to brokers, you can use port 9092 or higher (9093, 9094, and so on), but with a few exceptions.
The listeners cannot be configured to use the ports reserved for interbroker communication (9090 and 9091), Prometheus metrics (9404), and JMX (Java Management Extensions) monitoring (9999).
|
Example listener authentication configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: true
authentication:
type: scram-sha-512
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: tls
# ...
15.1.1. mTLS authentication
mTLS authentication is always used for the communication between Kafka brokers and ZooKeeper pods.
Strimzi can configure Kafka to use TLS (Transport Layer Security) to provide encrypted communication between Kafka brokers and clients either with or without mutual authentication.
For mutual, or two-way, authentication, both the server and the client present certificates.
When you configure mTLS authentication, the broker authenticates the client (client authentication) and the client authenticates the broker (server authentication).
mTLS listener configuration in the Kafka
resource requires the following:
When a Kafka cluster is created by the Cluster Operator, it creates a new secret with the name <cluster_name>-cluster-ca-cert
.
The secret contains a CA certificate.
The CA certificate is in PEM and PKCS #12 format.
To verify a Kafka cluster, add the CA certificate to the truststore in your client configuration.
To verify a client, add a user certificate and key to the keystore in your client configuration.
For more information on configuring a client for mTLS, see Configuring user authentication.
Note
|
TLS authentication is more commonly one-way, with one party authenticating the identity of another.
For example, when HTTPS is used between a web browser and a web server, the browser obtains proof of the identity of the web server.
|
15.1.2. SCRAM-SHA-512 authentication
SCRAM (Salted Challenge Response Authentication Mechanism) is an authentication protocol that can establish mutual authentication using passwords.
Strimzi can configure Kafka to use SASL (Simple Authentication and Security Layer) SCRAM-SHA-512 to provide authentication on both unencrypted and encrypted client connections.
When SCRAM-SHA-512 authentication is used with a TLS connection, the TLS protocol provides the encryption, but is not used for authentication.
The following properties of SCRAM make it safe to use SCRAM-SHA-512 even on unencrypted connections:
-
The passwords are not sent in the clear over the communication channel.
Instead the client and the server are each challenged by the other to offer proof that they know the password of the authenticating user.
-
The server and client each generate a new challenge for each authentication exchange.
This means that the exchange is resilient against replay attacks.
When KafkaUser.spec.authentication.type
is configured with scram-sha-512
the User Operator will generate a random 32-character password consisting of upper and lowercase ASCII letters and numbers.
15.1.3. Restricting access to listeners with network policies
Control listener access by configuring the networkPolicyPeers
property in the Kafka
resource.
By default, Strimzi automatically creates a NetworkPolicy
resource for every enabled Kafka listener, allowing connections from all namespaces.
If you want to use custom network policies, you can set the STRIMZI_NETWORK_POLICY_GENERATION
environment variable to false
in the Cluster Operator configuration.
For more information, see Configuring the Cluster Operator.
Note
|
Your configuration of Kubernetes must support ingress NetworkPolicies in order to use network policies.
|
Procedure
-
Configure the networkPolicyPeers
property to define the application pods or namespaces allowed to access the Kafka cluster.
This example shows configuration for a tls
listener to allow connections only from application pods with the label app
set to kafka-client
:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
networkPolicyPeers:
- podSelector:
matchLabels:
app: kafka-client
# ...
zookeeper:
# ...
-
Apply the changes to the Kafka
resource configuration.
15.1.4. Using custom listener certificates for TLS encryption
This procedure shows how to configure custom server certificates for TLS listeners or external listeners which have TLS encryption enabled.
By default, Kafka listeners use certificates signed by Strimzi’s internal CA (certificate authority).
The Cluster Operator automatically generates a CA certificate when creating a Kafka cluster.
To configure a client for TLS, the CA certificate is included in its truststore configuration to authenticate the Kafka cluster.
Alternatively, you have the option to install and use your own CA certificates.
However, if you prefer more granular control by using your own custom certificates at the listener-level, you can configure listeners using brokerCertChainAndKey
properties.
You create a secret with your own private key and server certificate, then specify them in the brokerCertChainAndKey
configuration.
User-provided certificates allow you to leverage existing security infrastructure.
You can use a certificate signed by a public (external) CA or a private CA.
Kafka clients need to trust the CA which was used to sign the listener certificate.
If signed by a public CA, you usually won’t need to add it to a client’s truststore configuration.
Custom certificates are not managed by Strimzi, so you need to renew them manually.
Note
|
Listener certificates are used for TLS encryption and server authentication only.
They are not used for TLS client authentication.
If you want to use your own certificate for TLS client authentication as well, you must install and use your own clients CA.
|
If you are not using a self-signed certificate, you can provide a certificate that includes the whole CA chain in the certificate.
You can only use the brokerCertChainAndKey
properties if TLS encryption (tls: true
) is configured for the listener.
Note
|
Strimzi does not support the use of encrypted private keys for TLS. The private key stored in the secret must be unencrypted for this to work.
|
Procedure
-
Create a Secret
containing your private key and server certificate:
kubectl create secret generic <my_secret> --from-file=<my_listener_key.key> --from-file=<my_listener_certificate.crt>
-
Edit the Kafka
resource for your cluster.
Configure the listener to use your Secret
, certificate file, and private key file in the configuration.brokerCertChainAndKey
property.
Example configuration for a loadbalancer
external listener with TLS encryption enabled
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: false
- name: external3
port: 9094
type: loadbalancer
tls: true
configuration:
brokerCertChainAndKey:
secretName: my-secret
certificate: my-listener-certificate.crt
key: my-listener-key.key
# ...
Example configuration for a TLS listener
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: false
- name: tls
port: 9093
type: internal
tls: true
configuration:
brokerCertChainAndKey:
secretName: my-secret
certificate: my-listener-certificate.crt
key: my-listener-key.key
# ...
-
Apply the changes to the Kafka
resource configuration.
The Cluster Operator starts a rolling update of the Kafka cluster, which updates the configuration of the listeners.
Note
|
A rolling update is also started if you update a Kafka listener certificate in a Secret that is already used by a listener.
|
15.1.5. Specifying SANs for custom listener certificates
In order to use TLS hostname verification with custom Kafka listener certificates, you must specify the correct Subject Alternative Names (SANs) for each listener.
The certificate SANs must specify hostnames for the following:
You can use wildcard certificates if they are supported by your CA.
Examples of SANs for internal listeners
Use the following examples to help you specify hostnames of the SANs in your certificates for your internal listeners.
Replace <cluster-name>
with the name of the Kafka cluster and <namespace>
with the Kubernetes namespace where the cluster is running.
Wildcards example for a type: internal
listener
//Kafka brokers
*.<cluster_name>-kafka-brokers
*.<cluster_name>-kafka-brokers.<namespace>.svc
// Bootstrap service
<cluster_name>-kafka-bootstrap
<cluster_name>-kafka-bootstrap.<namespace>.svc
Non-wildcards example for a type: internal
listener
// Kafka brokers
<cluster_name>-kafka-0.<cluster_name>-kafka-brokers
<cluster_name>-kafka-0.<cluster_name>-kafka-brokers.<namespace>.svc
<cluster_name>-kafka-1.<cluster_name>-kafka-brokers
<cluster_name>-kafka-1.<cluster_name>-kafka-brokers.<namespace>.svc
# ...
// Bootstrap service
<cluster_name>-kafka-bootstrap
<cluster_name>-kafka-bootstrap.<namespace>.svc
Non-wildcards example for a type: cluster-ip
listener
// Kafka brokers
<cluster_name>-kafka-<listener-name>-0
<cluster_name>-kafka-<listener-name>-0.<namespace>.svc
<cluster_name>-kafka-_listener-name>-1
<cluster_name>-kafka-<listener-name>-1.<namespace>.svc
# ...
// Bootstrap service
<cluster_name>-kafka-<listener-name>-bootstrap
<cluster_name>-kafka-<listener-name>-bootstrap.<namespace>.svc
Examples of SANs for external listeners
For external listeners which have TLS encryption enabled, the hostnames you need to specify in certificates depends on the external listener type
.
Table 19. SANs for each type of external listener
External listener type |
In the SANs, specify… |
ingress
|
Addresses of all Kafka broker Ingress resources and the address of the bootstrap Ingress .
You can use a matching wildcard name. |
route
|
Addresses of all Kafka broker Routes and the address of the bootstrap Route .
You can use a matching wildcard name. |
loadbalancer
|
Addresses of all Kafka broker loadbalancers and the bootstrap loadbalancer address.
You can use a matching wildcard name. |
nodeport
|
Addresses of all Kubernetes worker nodes that the Kafka broker pods might be scheduled to.
You can use a matching wildcard name. |
15.2. Configuring authorized access to Kafka
Configure authorized access to a Kafka cluster using the Kafka.spec.kafka.authorization
property in the Kafka
resource.
If the authorization
property is missing, no authorization is enabled and clients have no restrictions.
When enabled, authorization is applied to all enabled listeners.
The authorization method is defined in the type
field.
Supported authorization options:
Figure 5. Kafka cluster authorization options
15.2.1. Designating super users
Super users can access all resources in your Kafka cluster regardless of any access restrictions,
and are supported by all authorization mechanisms.
To designate super users for a Kafka cluster, add a list of user principals to the superUsers
property.
If a user uses mTLS authentication, the username is the common name from the TLS certificate subject prefixed with CN=
.
If you are not using the User Operator and using your own certificates for mTLS, the username is the full certificate subject.
A full certificate subject can include the following fields:
-
CN=<common_name>
-
OU=<organizational_unit>
-
O=<organization>
-
L=<locality>
-
ST=<state>
-
C=<country_code>
Omit any fields that are not applicable.
An example configuration with super users
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
authorization:
type: simple
superUsers:
- CN=user-1
- user-2
- CN=user-3
- CN=user-4,OU=my-ou,O=my-org,L=my-location,ST=my-state,C=US
- CN=user-5,OU=my-ou,O=my-org,C=GB
- CN=user-6,O=my-org
# ...
15.3. Configuring user (client-side) security mechanisms
When configuring security mechanisms in clients, the clients are represented as users.
Use the KafkaUser
resource to configure the authentication, authorization, and access rights for Kafka clients.
Authentication permits user access, and authorization constrains user access to permissible actions.
You can also create super users that have unconstrained access to Kafka brokers.
15.3.1. Associating users with Kafka clusters
A KafkaUser
resource includes a label that defines the appropriate name of the Kafka cluster (derived from the name of the Kafka
resource) to which it belongs.
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
The label enables the User Operator to identify the KafkaUser
resource and create and manager the user.
If the label does not match the Kafka cluster, the User Operator cannot identify the KafkaUser
, and the user is not created.
If the status of the KafkaUser
resource remains empty, check your label configuration.
15.3.2. Configuring user authentication
Use the KafkaUser
custom resource to configure authentication credentials for users (clients) that require access to a Kafka cluster.
Configure the credentials using the authentication
property in KafkaUser.spec
.
By specifying a type
, you control what credentials are generated.
Supported authentication types:
-
tls
for mTLS authentication
-
tls-external
for mTLS authentication using external certificates
-
scram-sha-512
for SCRAM-SHA-512 authentication
If tls
or scram-sha-512
is specified, the User Operator creates authentication credentials when it creates the user.
If tls-external
is specified, the user still uses mTLS, but no authentication credentials are created.
Use this option when you’re providing your own certificates.
When no authentication type is specified, the User Operator does not create the user or its credentials.
You can use tls-external
to authenticate with mTLS using a certificate issued outside the User Operator.
The User Operator does not generate a TLS certificate or a secret.
You can still manage ACL rules and quotas through the User Operator in the same way as when you’re using the tls
mechanism.
This means that you use the CN=USER-NAME
format when specifying ACL rules and quotas.
USER-NAME is the common name given in a TLS certificate.
mTLS authentication
To use mTLS authentication, you set the type
field in the KafkaUser
resource to tls
.
Example user with mTLS authentication enabled
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: tls
# ...
The authentication type must match the equivalent configuration for the Kafka
listener used to access the Kafka cluster.
When the user is created by the User Operator, it creates a new secret with the same name as the KafkaUser
resource.
The secret contains a private and public key for mTLS.
The public key is contained in a user certificate, which is signed by a clients CA (certificate authority) when it is created.
All keys are in X.509 format.
Note
|
If you are using the clients CA generated by the Cluster Operator, the user certificates generated by the User Operator are also renewed when the clients CA is renewed by the Cluster Operator.
|
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
ca.crt: <public_key> # Public key of the clients CA used to sign this user certificate
user.crt: <user_certificate> # Public key of the user
user.key: <user_private_key> # Private key of the user
user.p12: <store> # PKCS #12 store for user certificates and keys
user.password: <password_for_store> # Protects the PKCS #12 store
When you configure a client, you specify the following:
The configuration depends on the file format (PEM or PKCS #12).
This example uses PKCS #12 stores, and the passwords required to access the credentials in the stores.
Example client configuration using mTLS in PKCS #12 format
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)
-
The bootstrap server address to connect to the Kafka cluster.
-
The security protocol option when using TLS for encryption.
-
The truststore location contains the public key certificate (ca.p12
) for the Kafka cluster. A cluster CA certificate and password is generated by the Cluster Operator in the <cluster_name>-cluster-ca-cert
secret when the Kafka cluster is created.
-
The password (ca.password
) for accessing the truststore.
-
The keystore location contains the public key certificate (user.p12
) for the Kafka user.
-
The password (user.password
) for accessing the keystore.
mTLS authentication using a certificate issued outside the User Operator
To use mTLS authentication using a certificate issued outside the User Operator, you set the type
field in the KafkaUser
resource to tls-external
.
A secret and credentials are not created for the user.
Example user with mTLS authentication that uses a certificate issued outside the User Operator
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: tls-external
# ...
SCRAM-SHA-512 authentication
To use the SCRAM-SHA-512 authentication mechanism, you set the type
field in the KafkaUser
resource to scram-sha-512
.
Example user with SCRAM-SHA-512 authentication enabled
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: scram-sha-512
# ...
When the user is created by the User Operator, it creates a new secret with the same name as the KafkaUser
resource.
The secret contains the generated password in the password
key, which is encoded with base64.
In order to use the password, it must be decoded.
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
password: Z2VuZXJhdGVkcGFzc3dvcmQ= (1)
sasl.jaas.config: b3JnLmFwYWNoZS5rYWZrYS5jb21tb24uc2VjdXJpdHkuc2NyYW0uU2NyYW1Mb2dpbk1vZHVsZSByZXF1aXJlZCB1c2VybmFtZT0ibXktdXNlciIgcGFzc3dvcmQ9ImdlbmVyYXRlZHBhc3N3b3JkIjsK (2)
-
The generated password, base64 encoded.
-
The JAAS configuration string for SASL SCRAM-SHA-512 authentication, base64 encoded.
Decoding the generated password:
echo "Z2VuZXJhdGVkcGFzc3dvcmQ=" | base64 --decode
Custom password configuration
When a user is created, Strimzi generates a random password.
You can use your own password instead of the one generated by Strimzi. To do so, create a secret with the password and reference it in the KafkaUser
resource.
Example user with a password set for SCRAM-SHA-512 authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: scram-sha-512
password:
valueFrom:
secretKeyRef:
name: my-secret # (1)
key: my-password # (2)
# ...
-
The name of the secret containing the predefined password.
-
The key for the password stored inside the secret.
15.3.3. Configuring user authorization
Use the KafkaUser
custom resource to configure authorization rules for users (clients) that require access to a Kafka cluster.
Configure the rules using the authorization
property in KafkaUser.spec
.
By specifying a type
, you control what rules are used.
To use simple authorization, you set the type
property to simple
in KafkaUser.spec.authorization
.
The simple authorization uses the Kafka Admin API to manage the ACL rules inside your Kafka cluster.
Whether ACL management in the User Operator is enabled or not depends on your authorization configuration in the Kafka cluster.
-
For simple authorization, ACL management is always enabled.
-
For OPA authorization, ACL management is always disabled.
Authorization rules are configured in the OPA server.
-
For Keycloak authorization, you can manage the ACL rules directly in Keycloak.
You can also delegate authorization to the simple authorizer as a fallback option in the configuration.
When delegation to the simple authorizer is enabled, the User Operator will enable management of ACL rules as well.
-
For custom authorization using a custom authorization plugin, use the supportsAdminApi
property in the .spec.kafka.authorization
configuration of the Kafka
custom resource to enable or disable the support.
Authorization is cluster-wide.
The authorization type must match the equivalent configuration in the Kafka
custom resource.
If ACL management is not enabled, Strimzi rejects a resource if it contains any ACL rules.
If you’re using a standalone deployment of the User Operator, ACL management is enabled by default.
You can disable it using the STRIMZI_ACLS_ADMIN_API_SUPPORTED
environment variable.
If no authorization is specified, the User Operator does not provision any access rights for the user.
Whether such a KafkaUser
can still access resources depends on the authorizer being used.
For example, for simple
authorization, this is determined by the allow.everyone.if.no.acl.found
configuration in the Kafka cluster.
ACL rules
simple
authorization uses ACL rules to manage access to Kafka brokers.
ACL rules grant access rights to the user, which you specify in the acls
property.
Super user access to Kafka brokers
If a user is added to a list of super users in a Kafka broker configuration,
the user is allowed unlimited access to the cluster regardless of any authorization constraints defined in ACLs in KafkaUser
.
15.3.4. Configuring user quotas
Configure the spec
for the KafkaUser
resource to enforce quotas so that a user does not overload Kafka brokers.
Set size-based network usage and time-based CPU utilization thresholds.
Partition mutations occur in response to the following types of user requests:
-
Creating partitions for a new topic
-
Adding partitions to an existing topic
-
Deleting partitions from a topic
You can also add a partition mutation quota to control the rate at which requests to change partitions are accepted.
Example KafkaUser
with user quotas
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
# ...
quotas:
producerByteRate: 1048576 # (1)
consumerByteRate: 2097152 # (2)
requestPercentage: 55 # (3)
controllerMutationRate: 10 # (4)
-
Byte-per-second quota on the amount of data the user can push to a Kafka broker.
-
Byte-per-second quota on the amount of data the user can fetch from a Kafka broker.
-
CPU utilization limit as a percentage of time for a client group.
-
Number of concurrent partition creation and deletion operations (mutations) allowed per second.
Using quotas for Kafka clients might be useful in a number of situations.
Consider a wrongly configured Kafka producer which is sending requests at too high a rate.
Such misconfiguration can cause a denial of service to other clients, so the problematic client ought to be blocked.
By using a network limiting quota, it is possible to prevent this situation from significantly impacting other clients.
Note
|
Strimzi supports user-level quotas, but not client-level quotas.
|
15.4. Example: Setting up secure client access
This procedure shows how to configure client access to a Kafka cluster from outside Kubernetes or from another Kubernetes cluster.
It’s split into two parts:
Resource configuration
Client access to the Kafka cluster is secured with the following configuration:
-
An external listener is configured with TLS encryption and mutual TLS (mTLS) authentication in the Kafka
resource, as well as simple
authorization.
-
A KafkaUser
is created for the client, utilizing mTLS authentication, and Access Control Lists (ACLs) are defined for simple
authorization.
At least one listener supporting the desired authentication must be configured for the KafkaUser
.
Listeners can be configured for mutual TLS
, SCRAM-SHA-512
, or OAuth
authentication.
While mTLS always uses encryption, it’s also recommended when using SCRAM-SHA-512 and OAuth 2.0 authentication.
Authorization options for Kafka include simple
, OAuth
, OPA
, or custom
.
When enabled, authorization is applied to all enabled listeners.
To ensure compatibility between Kafka and clients, configuration of the following authentication and authorization mechanisms must align:
-
For type: tls
and type: scram-sha-512
authentication types, Kafka.spec.kafka.listeners[*].authentication
must match KafkaUser.spec.authentication
-
For type: simple
authorization,Kafka.spec.kafka.authorization
must match KafkaUser.spec.authorization
For example, mTLS authentication for a user is only possible if it’s also enabled in the Kafka configuration.
Automation and certificate management
Strimzi operators automate the configuration process and create the certificates required for authentication:
-
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 User Operator creates the user representing the client and the security credentials used for client authentication, based on the chosen authentication type.
You add the certificates to your client configuration.
Certificates are available in PEM (.crt) and PKCS #12 (.p12) formats.
This procedure uses PEM certificates.
Use PEM certificates with clients that support the X.509 certificate format.
15.4.1. Securing Kafka brokers
-
Configure the Kafka cluster with a Kafka listener.
-
Apply the changes to the Kafka
resource configuration.
The Kafka cluster is configured with a Kafka broker listener using mTLS authentication.
A service is created for each Kafka broker pod.
A service is created to serve as the bootstrap address for connection to the Kafka cluster.
A service is also created as the external bootstrap address for external connection to the Kafka cluster using nodeport
listeners.
The cluster CA certificate to verify the identity of the kafka brokers is also created in the secret <cluster_name>-cluster-ca-cert
.
Note
|
If you scale your Kafka cluster while using external listeners, it might trigger a rolling update of all Kafka brokers. This depends on the configuration.
|
-
Retrieve the bootstrap address you can use to access the Kafka cluster from the status of the Kafka
resource.
kubectl get kafka <kafka_cluster_name> -o=jsonpath='{.status.listeners[?(@.name=="<listener_name>")].bootstrapServers}{"\n"}'
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external")].bootstrapServers}{"\n"}'
Use the bootstrap address in your Kafka client to connect to the Kafka cluster.
15.4.2. Securing user access to Kafka
-
Create or modify a user representing the client that requires access to the Kafka cluster.
-
Apply the changes to the KafkaUser
resource configuration.
The user is created, as well as a secret with the same name as the KafkaUser
resource.
The secret contains a public and private key for mTLS authentication.
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
ca.crt: <public_key> # Public key of the clients CA used to sign this user certificate
user.crt: <user_certificate> # Public key of the user
user.key: <user_private_key> # Private key of the user
user.p12: <store> # PKCS #12 store for user certificates and keys
user.password: <password_for_store> # Protects the PKCS #12 store
-
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
-
Extract the user CA certificate from the <user_name>
secret.
kubectl get secret <user_name> -o jsonpath='{.data.user\.crt}' | base64 -d > user.crt
-
Extract the private key of the user from the <user_name>
secret.
kubectl get secret <user_name> -o jsonpath='{.data.user\.key}' | base64 -d > user.key
-
Configure your client with the bootstrap address hostname and port for connecting to the Kafka cluster:
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "<hostname>:<port>");
-
Configure your client with the truststore credentials to verify the identity of the Kafka cluster.
Specify the public cluster CA certificate.
Example truststore configuration
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
props.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PEM");
props.put(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, "<ca.crt_file_content>");
SSL is the specified security protocol for mTLS authentication.
Specify SASL_SSL
for SCRAM-SHA-512 authentication over TLS.
PEM is the file format of the truststore.
-
Configure your client with the keystore credentials to verify the user when connecting to the Kafka cluster.
Specify the public certificate and private key.
Example keystore configuration
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
props.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PEM");
props.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, "<user.crt_file_content>");
props.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, "<user.key_file_content>");
Add the keystore certificate and the private key directly to the configuration.
Add as a single-line format.
Between the BEGIN CERTIFICATE
and END CERTIFICATE
delimiters, start with a newline character (\n
).
End each line from the original certificate with \n
too.
Example keystore configuration
props.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, "-----BEGIN CERTIFICATE----- \n<user_certificate_content_line_1>\n<user_certificate_content_line_n>\n-----END CERTIFICATE---");
props.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, "----BEGIN PRIVATE KEY-----\n<user_key_content_line_1>\n<user_key_content_line_n>\n-----END PRIVATE KEY-----");
15.5. Troubleshooting TLS hostname verification with node ports
Off-cluster access using node ports with TLS encryption enabled does not support TLS hostname verification.
Consequently, clients that perform hostname verification will fail to connect.
For example, a Java client will fail with the following exception:
Exception for TLS hostname verification
Caused by: java.security.cert.CertificateException: No subject alternative names matching IP address 168.72.15.231 found
...
To connect, you must disable hostname verification.
In the Java client, set the ssl.endpoint.identification.algorithm
configuration option 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", "");
16. Enabling OAuth 2.0 token-based access
Strimzi supports OAuth 2.0 for securing Kafka clusters by integrating with an OAUth 2.0 authorization server.
Kafka brokers and clients both need to be configured to use OAuth 2.0.
OAuth 2.0 enables standardized token-based authentication and authorization between applications, using a central authorization server to issue tokens that grant limited access to resources.
You can define specific scopes for fine-grained access control.
Scopes correspond to different levels of access to Kafka topics or operations within the cluster.
OAuth 2.0 also supports single sign-on and integration with identity providers.
16.1. Configuring an OAuth 2.0 authorization server
Before you can use OAuth 2.0 token-based access, you must configure an authorization server for integration with Strimzi.
The steps are dependent on the chosen authorization server.
Consult the product documentation for the authorization server for information on how to set up OAuth 2.0 access.
Prepare the authorization server to work with Strimzi by defining OAUth 2.0 clients for Kafka and each Kafka client component of your application.
In relation to the authorization server, the Kafka cluster and Kafka clients are both regarded as OAuth 2.0 clients.
In general, configure OAuth 2.0 clients in the authorization server with the following client credentials enabled:
-
Client ID (for example, kafka
for the Kafka cluster)
-
Client ID and secret as the authentication mechanism
Note
|
You only need to use a client ID and secret when using a non-public introspection endpoint of the authorization server.
The credentials are not typically required when using public authorization server endpoints, as with fast local JWT token validation.
|
16.2. Using OAuth 2.0 token-based authentication
Strimzi supports the use of OAuth 2.0 for token-based authentication.
An OAuth 2.0 authorization server handles the granting of access and inquiries about access.
Kafka clients authenticate to Kafka brokers.
Brokers and clients communicate with the authorization server, as necessary, to obtain or validate access tokens.
For a deployment of Strimzi, OAuth 2.0 integration provides the following support:
-
Server-side OAuth 2.0 authentication for Kafka brokers
-
Client-side OAuth 2.0 authentication for Kafka MirrorMaker, Kafka Connect, and the Kafka Bridge
16.2.1. Configuring OAuth 2.0 authentication on listeners
To secure Kafka brokers with OAuth 2.0 authentication, configure a listener in the Kafka
resource to use OAUth 2.0 authentication and a client authentication mechanism, and add further configuration depending on the authentication mechanism and type of token validation used in the authentication.
Configuring listeners to use oauth
authentication
Specify a listener in the Kafka
resource with an oauth
authentication type.
You can configure internal and external listeners.
We recommend using OAuth 2.0 authentication together with TLS encryption (tls: true
).
Without encryption, the connection is vulnerable to network eavesdropping and unauthorized access through token theft.
Example listener configuration with OAuth 2.0 authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: oauth
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
#...
Enabling SASL authentication mechanisms
Use one or both of the following SASL mechanisms for clients to exchange credentials and establish authenticated sessions with Kafka.
OAUTHBEARER
-
Using the OAUTHBEARER
authentication mechanism, credentials exchange uses a bearer token provided by an OAuth callback handler.
Token provision can be configured to use the following methods:
-
Client ID and secret (using the OAuth 2.0 client credentials mechanism)
-
Client ID and client assertion
-
Long-lived access token or Service account token
-
Long-lived refresh token obtained manually
OAUTHBEARER
is recommended as it provides a higher level of security than PLAIN
, though it can only be used by Kafka clients that support the OAUTHBEARER
mechanism at the protocol level.
Client credentials are never shared with Kafka.
PLAIN
-
PLAIN
is a simple authentication mechanism used by all Kafka client tools.
Consider using PLAIN
only with Kafka clients that do not support OAUTHBEARER
.
Using the PLAIN
authentication mechanism, credentials exchange can be configured to use the following methods:
-
Client ID and secret (using the OAuth 2.0 client credentials mechanism)
-
Long-lived access token
Regardless of the method used, the client must provide username
and password
properties to Kafka.
Credentials are handled centrally behind a compliant authorization server, similar to how OAUTHBEARER
authentication is used.
The username extraction process depends on the authorization server configuration.
OAUTHBEARER
is automatically enabled in the oauth
listener configuration for the Kafka broker.
To use the PLAIN
mechanism, you must set the enablePlain
property to true
.
In the following example, the PLAIN
mechanism is enabled, and the OAUTHBEARER
mechanism is disabled on a listener using the enableOauthBearer
property.
Example listener configuration for the PLAIN
mechanism
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: oauth
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
enablePlain: true
enableOauthBearer: false
#...
When you have defined the type of authentication as OAuth 2.0, you add configuration based on the type of validation, either as fast local JWT validation or token validation using an introspection endpoint.
Configuring fast local JWT token validation
Fast local JWT token validation involves checking a JWT token signature locally to ensure that the token meets the following criteria:
-
Contains a typ
(type) or token_type
header claim value of Bearer
to indicate it is an access token
-
Is currently valid and not expired
-
Has an issuer that matches a validIssuerURI
You specify a validIssuerURI
attribute when you configure the listener, so that any tokens not issued by the authorization server are rejected.
The authorization server does not need to be contacted during fast local JWT token validation.
You activate fast local JWT token validation by specifying a jwksEndpointUri
attribute, the endpoint exposed by the OAuth 2.0 authorization server.
The endpoint contains the public keys used to validate signed JWT tokens, which are sent as credentials by Kafka clients.
All communication with the authorization server should be performed using TLS encryption.
You can configure a certificate truststore as a Kubernetes Secret
in your Strimzi project namespace, and use the tlsTrustedCertificates
property to point to the Kubernetes secret containing the truststore file.
You might want to configure a userNameClaim
to properly extract a username from the JWT token.
If required, you can use a JsonPath expression like "['user.info'].['user.id']"
to retrieve the username from nested JSON attributes within a token.
If you want to use Kafka ACL authorization, identify the user by their username during authentication. (The sub
claim in JWT tokens is typically a unique ID, not a username.)
Example configuration for fast local JWT token validation
#...
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth # (1)
validIssuerUri: https://<auth_server_address>/<issuer-context> # (2)
jwksEndpointUri: https://<auth_server_address>/<path_to_jwks_endpoint> # (3)
userNameClaim: preferred_username # (4)
maxSecondsWithoutReauthentication: 3600 # (5)
tlsTrustedCertificates: # (6)
- secretName: oauth-server-cert
pattern: "*.crt"
disableTlsHostnameVerification: true # (7)
jwksExpirySeconds: 360 # (8)
jwksRefreshSeconds: 300 # (9)
jwksMinRefreshPauseSeconds: 1 # (10)
-
Listener type set to oauth
.
-
URI of the token issuer used for authentication.
-
URI of the JWKS certificate endpoint used for local JWT validation.
-
The token claim (or key) that contains the actual username used to identify the user. Its value depends on the authorization server. If necessary, a JsonPath expression like "['user.info'].['user.id']"
can be used to retrieve the username from nested JSON attributes within a token.
-
(Optional) Activates the Kafka re-authentication mechanism that enforces session expiry to the same length of time as the access token. If the specified value is less than the time left for the access token to expire, then the client will have to re-authenticate before the actual token expiry. By default, the session does not expire when the access token expires, and the client does not attempt re-authentication.
-
(Optional) Certificates stored in X.509 format within the specified secrets for TLS connection to the authorization server.
-
(Optional) Disable TLS hostname verification. Default is false
.
-
The duration the JWKS certificates are considered valid before they expire. Default is 360
seconds. If you specify a longer time, consider the risk of allowing access to revoked certificates.
-
The period between refreshes of JWKS certificates. The interval must be at least 60 seconds shorter than the expiry interval. Default is 300
seconds.
-
The minimum pause in seconds between consecutive attempts to refresh JWKS public keys. When an unknown signing key is encountered, the JWKS keys refresh is scheduled outside the regular periodic schedule with at least the specified pause since the last refresh attempt. The refreshing of keys follows the rule of exponential backoff, retrying on unsuccessful refreshes with ever increasing pause, until it reaches jwksRefreshSeconds
. The default value is 1.
Configuring fast local JWT token validation with Kubernetes service accounts
To configure the listener for Kubernetes service accounts, the Kubernetes API server must be used as the authorization server.
Example configuration for fast local JWT token validation using Kubernetes API server as authorization server
#...
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
validIssuerUri: https://kubernetes.default.svc.cluster.local # (1)
jwksEndpointUri: https://kubernetes.default.svc.cluster.local/openid/v1/jwks # (2)
serverBearerTokenLocation: /var/run/secrets/kubernetes.io/serviceaccount/token # (3)
checkAccessTokenType: false # (4)
includeAcceptHeader: false # (5)
tlsTrustedCertificates: # (6)
- secretName: oauth-server-cert
pattern: "*.crt"
maxSecondsWithoutReauthentication: 3600
customClaimCheck: "@.['kubernetes.io'] && @.['kubernetes.io'].['namespace'] in ['myproject']" # (7)
-
URI of the token issuer used for authentication. Must use FQDN, including the .cluster.local
extension, which may vary based on the Kubernetes cluster configuration.
-
URI of the JWKS certificate endpoint used for local JWT validation. Must use FQDN, including the .cluster.local
extension, which may vary based on the Kubernetes cluster configuration.
-
Location to the access token used by the Kafka broker to authenticate to the Kubernetes API server in order to access the jwksEndpointUri
.
-
Skip the access token type check, as the claim for this is not present in service account tokens.
-
Skip sending Accept
header in HTTP requests to the JWKS endpoint, as the Kubernetes API server does not support it.
-
Trusted certificates to connect to authorization server. This should point to a manually created Secret that contains the Kubernetes API server public certificate, which is mounted to the running pods under /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
. You can use the following command to create the Secret:
kubectl get cm kube-root-ca.crt -o jsonpath="{['data']['ca\.crt']}" > /tmp/ca.crt
kubectl create secret generic oauth-server-cert --from-file=ca.crt=/tmp/ca.crt
-
(Optional) Additional constraints that JWT token has to fulfill in order to be accepted, expressed as JsonPath filter query. In this example the service account has to belong to myproject
namespace in order to be allowed to authenticate.
The above configuration uses the sub
claim from the service account JWT token as the user ID. For example, the default service account for pods deployed in the myproject
namespace has the username: system:serviceaccount:myproject:default
.
When configuring ACLs the general form of how to refer to the ServiceAccount user should in that case be: User:system:serviceaccount:<Namespace>:<ServiceAccount-name>
Configuring token validation using an introspection endpoint
Token validation using an OAuth 2.0 introspection endpoint treats a received access token as opaque. The Kafka broker sends an access token to the introspection endpoint, which responds with the token information necessary for validation.
Importantly, it returns up-to-date information if the specific access token is valid, and also information about when the token expires.
To configure OAuth 2.0 introspection-based validation, you specify an introspectionEndpointUri attribute rather than the jwksEndpointUri
attribute specified for fast local JWT token validation.
Depending on the authorization server, you typically have to specify a clientId
and clientSecret
, because the introspection endpoint is usually protected.
Example token validation configuration using an introspection endpoint
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
validIssuerUri: https://<auth_server_address>/<issuer-context>
introspectionEndpointUri: https://<auth_server_address>/<path_to_introspection_endpoint> # (1)
clientId: kafka-broker # (2)
clientSecret: # (3)
secretName: my-cluster-oauth
key: clientSecret
userNameClaim: preferred_username # (4)
maxSecondsWithoutReauthentication: 3600 # (5)
tlsTrustedCertificates:
- secretName: oauth-server-cert
pattern: "*.crt"
-
URI of the token introspection endpoint.
-
Client ID to identify the client.
-
Client Secret and client ID is used for authentication.
-
The token claim (or key) that contains the actual username used to identify the user. Its value depends on the authorization server. If necessary, a JsonPath expression like "['user.info'].['user.id']"
can be used to retrieve the username from nested JSON attributes within a token.
-
(Optional) Activates the Kafka re-authentication mechanism that enforces session expiry to the same length of time as the access token. If the specified value is less than the time left for the access token to expire, then the client will have to re-authenticate before the actual token expiry. By default, the session does not expire when the access token expires, and the client does not attempt re-authentication.
Authenticating brokers to the authorization server protected endpoints
Usually, the certificates endpoint of the authorization server (jwksEndpointUri
) is publicly accessible, while the introspection endpoint (introspectionEndpointUri
) is protected.
However, this may vary depending on the authorization server configuration.
The Kafka broker can authenticate to the authorization server’s protected endpoints in one of two ways using HTTP authentication schemes:
To configure HTTP Basic authentication, set the following properties:
For HTTP Bearer authentication, set the following property:
Including additional configuration options
Specify additional settings depending on the authentication requirements and the authorization server you are using.
Some of these properties apply only to certain authentication mechanisms or when used in combination with other properties.
For example, when using OAUth over PLAIN
, access tokens are passed as password
property values with or without an $accessToken:
prefix.
-
If you configure a token endpoint (tokenEndpointUri
) in the listener configuration, you need the prefix.
-
If you don’t configure a token endpoint in the listener configuration, you don’t need the prefix.
The Kafka broker interprets the password as a raw access token.
If the password
is set as the access token, the username
must be set to the same principal name that the Kafka broker obtains from the access token.
You can specify username extraction options in your listener using the userNameClaim
, usernamePrefix
, fallbackUserNameClaim
, fallbackUsernamePrefix
, and userInfoEndpointUri
properties.
The username extraction process also depends on your authorization server; in particular, how it maps client IDs to account names.
Note
|
The PLAIN mechanism does not support password grant authentication.
Use either client credentials (client ID + secret) or an access token for authentication.
|
Example optional configuration settings
# ...
authentication:
type: oauth
# ...
checkIssuer: false # (1)
checkAudience: true # (2)
usernamePrefix: user- # (3)
fallbackUserNameClaim: client_id # (4)
fallbackUserNamePrefix: client-account- # (5)
serverBearerTokenLocation: path/to/access/token # (6)
validTokenType: bearer # (7)
userInfoEndpointUri: https://<auth_server_address>/<path_to_userinfo_endpoint> # (8)
enableOauthBearer: false # (9)
enablePlain: true # (10)
tokenEndpointUri: https://<auth_server_address>/<path_to_token_endpoint> # (11)
customClaimCheck: "@.custom == 'custom-value'" # (12)
clientAudience: audience # (13)
clientScope: scope # (14)
connectTimeoutSeconds: 60 # (15)
readTimeoutSeconds: 60 # (16)
httpRetries: 2 # (17)
httpRetryPauseMs: 300 # (18)
groupsClaim: "$.groups" # (19)
groupsClaimDelimiter: "," # (20)
includeAcceptHeader: false # (21)
-
If your authorization server does not provide an iss
claim, it is not possible to perform an issuer check. In this situation, set checkIssuer
to false
and do not specify a validIssuerUri
. Default is true
.
-
If your authorization server provides an aud
(audience) claim, and you want to enforce an audience check, set checkAudience
to true
. Audience checks identify the intended recipients of tokens. As a result, the Kafka broker will reject tokens that do not have its clientId
in their aud
claim. Default is false
.
-
The prefix used when constructing the user ID. This only takes effect if userNameClaim
is configured.
-
An authorization server may not provide a single attribute to identify both regular users and clients. When a client authenticates in its own name, the server might provide a client ID. When a user authenticates using a username and password to obtain a refresh token or an access token, the server might provide a username attribute in addition to a client ID. Use this fallback option to specify the username claim (attribute) to use if a primary user ID attribute is not available. If necessary, a JsonPath expression like "['client.info'].['client.id']"
can be used to retrieve the fallback username to retrieve the username from nested JSON attributes within a token.
-
In situations where fallbackUserNameClaim
is applicable, it may also be necessary to prevent name collisions between the values of the username claim, and those of the fallback username claim. Consider a situation where a client called producer
exists, but also a regular user called producer
exists. In order to differentiate between the two, you can use this property to add a prefix to the user ID of the client.
-
The location of the access token used by the Kafka broker to authenticate to the Kubernetes API server for accessing protected endpoints. The authorization server must support OAUTHBEARER
authentication. This is an alternative to specifying clientId
and clientSecret
, which uses PLAIN
authentication.
-
(Only applicable when using introspectionEndpointUri
) Depending on the authorization server you are using, the introspection endpoint may or may not return the token type attribute, or it may contain different values. You can specify a valid token type value that the response from the introspection endpoint has to contain.
-
(Only applicable when using introspectionEndpointUri
) The authorization server may be configured or implemented in such a way to not provide any identifiable information in an introspection endpoint response. In order to obtain the user ID, you can configure the URI of the userinfo
endpoint as a fallback. The userNameClaim
, fallbackUserNameClaim
, and fallbackUserNamePrefix
settings are applied to the response of userinfo
endpoint.
-
Set this to false
to disable the OAUTHBEARER
mechanism on the listener. At least one of PLAIN
or OAUTHBEARER
has to be enabled. Default is true
.
-
Set to true
to enable PLAIN
authentication on the listener, which is supported for clients on all platforms.
-
Additional configuration for the PLAIN
mechanism. If specified, clients can authenticate over PLAIN
by passing an access token as the password
using an $accessToken:
prefix.
For production, always use https://
urls.
-
Additional custom rules can be imposed on the JWT access token during validation by setting this to a JsonPath filter query. If the access token does not contain the necessary data, it is rejected. When using the introspectionEndpointUri
, the custom check is applied to the introspection endpoint response JSON.
-
An audience
parameter passed to the token endpoint. An audience is used when obtaining an access token for inter-broker authentication. It is also used in the name of a client for OAuth 2.0 over PLAIN
client authentication using a clientId
and secret
. This only affects the ability to obtain the token, and the content of the token, depending on the authorization server. It does not affect token validation rules by the listener.
-
A scope
parameter passed to the token endpoint. A scope is used when obtaining an access token for inter-broker authentication. It is also used in the name of a client for OAuth 2.0 over PLAIN
client authentication using a clientId
and secret
. This only affects the ability to obtain the token, and the content of the token, depending on the authorization server. It does not affect token validation rules by the listener.
-
The connect timeout in seconds when connecting to the authorization server. The default value is 60.
-
The read timeout in seconds when connecting to the authorization server. The default value is 60.
-
The maximum number of times to retry a failed HTTP request to the authorization server. The default value is 0
, meaning that no retries are performed. To use this option effectively, consider reducing the timeout times for the connectTimeoutSeconds
and readTimeoutSeconds
options. However, note that retries may prevent the current worker thread from being available to other requests, and if too many requests stall, it could make the Kafka broker unresponsive.
-
The time to wait before attempting another retry of a failed HTTP request to the authorization server. By default, this time is set to zero, meaning that no pause is applied. This is because many issues that cause failed requests are per-request network glitches or proxy issues that can be resolved quickly. However, if your authorization server is under stress or experiencing high traffic, you may want to set this option to a value of 100 ms or more to reduce the load on the server and increase the likelihood of successful retries.
-
A JsonPath query that is used to extract groups information from either the JWT token or the introspection endpoint response. This option is not set by default. By configuring this option, a custom authorizer can make authorization decisions based on user groups.
-
A delimiter used to parse groups information when it is returned as a single delimited string. The default value is ',' (comma).
-
Some authorization servers have issues with client sending Accept: application/json
header. By setting includeAcceptHeader: false
the header will not be sent. Default is true
.
16.2.2. Configuring OAuth 2.0 on client applications
To configure OAuth 2.0 on client applications, you must specify the following:
-
SASL (Simple Authentication and Security Layer) security protocols
-
SASL mechanisms
-
A JAAS (Java Authentication and Authorization Service) module
-
Authentication properties to access the authorization server
Configuring SASL protocols
Specify SASL protocols in the client configuration:
Use SASL_SSL
for production and SASL_PLAINTEXT
for local development only.
When using SASL_SSL
, additional ssl.truststore
configuration is needed.
The truststore configuration is required for secure connection (https://
) to the OAuth 2.0 authorization server.
To verify the OAuth 2.0 authorization server, add the CA certificate for the authorization server to the truststore in your client configuration.
You can configure a truststore in PEM or PKCS #12 format.
Configuring SASL authentication mechanisms
Specify SASL mechanisms in the client configuration:
Configuring a JAAS module
Specify a JAAS module that implements the SASL authentication mechanism as a sasl.jaas.config
property value:
Note
|
For the OAUTHBEARER mechanism, Strimzi provides a callback handler for clients that use Kafka Client Java libraries to enable credentials exchange.
For clients in other languages, custom code may be required to obtain the access token.
For the PLAIN mechanism, Strimzi provides server-side callbacks to enable credentials exchange.
|
To be able to use the OAUTHBEARER
mechanism, you must also add the custom io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
class as the callback handler.
JaasClientOauthLoginCallbackHandler
handles OAuth callbacks to the authorization server for access tokens during client login.
This enables automatic token renewal, ensuring continuous authentication without user intervention.
Additionally, it handles login credentials for clients using the OAuth 2.0 password grant method.
Configuring authentication properties
Configure the client to use credentials or access tokens for OAuth 2.0 authentication.
- Using client credentials
-
Using client credentials involves configuring the client with the necessary credentials (client ID and secret, or client ID and client assertion) to obtain a valid access token from an authorization server. This is the simplest mechanism.
- Using access tokens
-
Using access tokens, the client is configured with a valid long-lived access token or refresh token obtained from an authorization server.
Using access tokens adds more complexity because there is an additional dependency on authorization server tools.
If you are using long-lived access tokens, you may need to configure the client in the authorization server to increase the maximum lifetime of the token.
The only information ever sent to Kafka is the access token.
The credentials used to obtain the token are never sent to Kafka.
When a client obtains an access token, no further communication with the authorization server is needed.
SASL authentication properties support the following authentication methods:
-
OAuth 2.0 client credentials
-
Access token or Service account token
-
Refresh token
-
OAuth 2.0 password grant (deprecated)
Add the authentication properties as JAAS configuration (sasl.jaas.config
and sasl.login.callback.handler.class
).
If the client application is not configured with an access token directly, the client exchanges one of the following sets of credentials for an access token during Kafka session initiation:
-
Client ID and secret
-
Client ID and client assertion
-
Client ID, refresh token, and (optionally) a secret
-
Username and password, with client ID and (optionally) a secret
Note
|
You can also specify authentication properties as environment variables, or as Java system properties.
For Java system properties, you can set them using setProperty and pass them on the command line using the -D option.
|
Example client credentials configuration using the client secret
security.protocol=SASL_SSL # (1)
sasl.mechanism=OAUTHBEARER # (2)
ssl.truststore.location=/tmp/truststore.p12 (3)
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \ # (4)
oauth.client.id="<client_id>" \ # (5)
oauth.client.secret="<client_secret>" \ # (6)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \ # (7)
oauth.ssl.truststore.password="$STOREPASS" \ # (8)
oauth.ssl.truststore.type="PKCS12" \ # (9)
oauth.scope="<scope>" \ # (10)
oauth.audience="<audience>" ; # (11)
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
SASL_SSL
security protocol for TLS-encrypted connections. Use SASL_PLAINTEXT
over unencrypted connections for local development only.
-
The SASL mechanism specified as OAUTHBEARER
or PLAIN
.
-
The truststore configuration for secure access to the Kafka cluster.
-
URI of the authorization server token endpoint.
-
Client ID, which is the name used when creating the client in the authorization server.
-
Client secret created when creating the client in the authorization server.
-
The location contains the public key certificate (truststore.p12
) for the authorization server.
-
The password for accessing the truststore.
-
The truststore type.
-
(Optional) The scope
for requesting the token from the token endpoint.
An authorization server may require a client to specify the scope.
-
(Optional) The audience
for requesting the token from the token endpoint.
An authorization server may require a client to specify the audience.
Example client credentials configuration using the client assertion
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \
oauth.client.id="<client_id>" \
oauth.client.assertion.location="<path_to_client_assertion_token_file>" \ # (1)
oauth.client.assertion.type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \ # (2)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.scope="<scope>" \
oauth.audience="<audience>" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Path to the client assertion file used for authenticating the client. This file is a private key file as an alternative to the client secret.
Alternatively, use the oauth.client.assertion
option to specify the client assertion value in clear text.
-
(Optional) Sometimes you may need to specify the client assertion type. In not specified, the default value is urn:ietf:params:oauth:client-assertion-type:jwt-bearer
.
Example password grants configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \
oauth.client.id="<client_id>" \ # (1)
oauth.client.secret="<client_secret>" \ # (2)
oauth.password.grant.username="<username>" \ # (3)
oauth.password.grant.password="<password>" \ # (4)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.scope="<scope>" \
oauth.audience="<audience>" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Client ID, which is the name used when creating the client in the authorization server.
-
(Optional) Client secret created when creating the client in the authorization server.
-
Username for password grant authentication. OAuth password grant configuration (username and password) uses the OAuth 2.0 password grant method. To use password grants, create a user account for a client on your authorization server with limited permissions. The account should act like a service account. Use in environments where user accounts are required for authentication, but consider using a refresh token first.
-
Password for password grant authentication.
Note
|
SASL PLAIN does not support passing a username and password (password grants) using the OAuth 2.0 password grant method.
|
Example access token configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.access.token="<access_token>" ; # (1)
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Long-lived access token for Kafka clients. Alternatively, oauth.access.token.location
can be used to specify the file that contains the access token.
Example Kubernetes service account token configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.access.token.location="/var/run/secrets/kubernetes.io/serviceaccount/token"; # (1)
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Location to the service account token on the filesystem (assuming that the client is deployed as a Kubernetes pod)
Example refresh token configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \
oauth.client.id="<client_id>" \ # (1)
oauth.client.secret="<client_secret>" \ # (2)
oauth.refresh.token="<refresh_token>" \ # (3)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Client ID, which is the name used when creating the client in the authorization server.
-
(Optional) Client secret created when creating the client in the authorization server.
-
Long-lived refresh token for Kafka clients.
SASL extensions for custom OAUTHBEARER
implementations
If your Kafka broker uses a custom OAUTHBEARER
implementation, you may need to pass additional SASL extension options.
These extensions can include attributes or information required as client context by the authorization server.
The options are passed as key-value pairs and are sent to the Kafka broker when a new session is started.
Pass SASL extension values using oauth.sasl.extension.
as a key prefix.
Example configuration to pass SASL extension values
oauth.sasl.extension.key1="value1"
oauth.sasl.extension.key2="value2"
16.2.3. OAuth 2.0 client authentication flows
OAuth 2.0 authentication flows depend on the underlying Kafka client and Kafka broker configuration.
The flows must also be supported by the authorization server used.
The Kafka broker listener configuration determines how clients authenticate using an access token.
The client can pass a client ID and secret to request an access token.
If a listener is configured to use PLAIN
authentication, the client can authenticate with a client ID and secret or username and access token.
These values are passed as the username
and password
properties of the PLAIN
mechanism.
Listener configuration supports the following token validation options:
-
You can use fast local token validation based on JWT signature checking and local token introspection, without contacting an authorization server.
The authorization server provides a JWKS endpoint with public certificates that are used to validate signatures on the tokens.
-
You can use a call to a token introspection endpoint provided by an authorization server.
Each time a new Kafka broker connection is established, the broker passes the access token received from the client to the authorization server.
The Kafka broker checks the response to confirm whether the token is valid.
Note
|
An authorization server might only allow the use of opaque access tokens, which means that local token validation is not possible.
|
Kafka client credentials can also be configured for the following types of authentication:
-
Direct local access using a previously generated long-lived access token
-
Contact with the authorization server for a new access token to be issued (using a client ID and credentials, or a refresh token, or a username and a password)
Example client authentication flows using the SASL OAUTHBEARER
mechanism
You can use the following communication flows for Kafka authentication using the SASL OAUTHBEARER
mechanism.
Client using client ID and credentials, with broker delegating validation to authorization server
-
The Kafka client requests an access token from the authorization server using a client ID and credentials, and optionally a refresh token. Alternatively, the client may authenticate using a username and a password.
-
The authorization server generates a new access token.
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the access token.
-
The Kafka broker validates the access token by calling a token introspection endpoint on the authorization server using its own client ID and secret.
-
A Kafka client session is established if the token is valid.
Client using client ID and credentials, with broker performing fast local token validation
-
The Kafka client authenticates with the authorization server from the token endpoint, using a client ID and credentials, and optionally a refresh token. Alternatively, the client may authenticate using a username and a password.
-
The authorization server generates a new access token.
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the access token.
-
The Kafka broker validates the access token locally using a JWT token signature check, and local token introspection.
Client using long-lived access token, with broker delegating validation to authorization server
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the long-lived access token.
-
The Kafka broker validates the access token by calling a token introspection endpoint on the authorization server, using its own client ID and secret.
-
A Kafka client session is established if the token is valid.
Client using long-lived access token, with broker performing fast local validation
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the long-lived access token.
-
The Kafka broker validates the access token locally using a JWT token signature check and local token introspection.
Warning
|
Fast local JWT token signature validation is suitable only for short-lived tokens as there is no check with the authorization server if a token has been revoked.
Token expiration is written into the token, but revocation can happen at any time, so cannot be accounted for without contacting the authorization server.
Any issued token would be considered valid until it expires.
|
Example client authentication flows using the SASL PLAIN
mechanism
You can use the following communication flows for Kafka authentication using the OAuth PLAIN
mechanism.
Client using a client ID and secret, with the broker obtaining the access token for the client
-
The Kafka client passes a clientId
as a username and a secret
as a password.
-
The Kafka broker uses a token endpoint to pass the clientId
and secret
to the authorization server.
-
The authorization server returns a fresh access token or an error if the client credentials are not valid.
-
The Kafka broker validates the token in one of the following ways:
-
If a token introspection endpoint is specified, the Kafka broker validates the access token by calling the endpoint on the authorization server.
A session is established if the token validation is successful.
-
If local token introspection is used, a request is not made to the authorization server.
The Kafka broker validates the access token locally using a JWT token signature check.
Client using a long-lived access token without a client ID and secret
-
The Kafka client passes a username and password. The password provides the value of an access token that was obtained manually and configured before running the client.
-
The password is passed with or without an $accessToken:
string prefix depending on whether or not the Kafka broker listener is configured with a token endpoint for authentication.
-
If the token endpoint is configured, the password should be prefixed by $accessToken:
to let the broker know that the password parameter contains an access token rather than a client secret. The Kafka broker interprets the username as the account username.
-
If the token endpoint is not configured on the Kafka broker listener (enforcing a no-client-credentials mode
), the password should provide the access token without the prefix. The Kafka broker interprets the username as the account username.
In this mode, the client doesn’t use a client ID and secret, and the password
parameter is always interpreted as a raw access token.
-
The Kafka broker validates the token in one of the following ways:
-
If a token introspection endpoint is specified, the Kafka broker validates the access token by calling the endpoint on the authorization server. A session is established if token validation is successful.
-
If local token introspection is used, there is no request made to the authorization server. Kafka broker validates the access token locally using a JWT token signature check.
16.2.4. Re-authenticating sessions
Configure oauth
listeners to use Kafka session re-authentication for OAuth 2.0 sessions between Kafka clients and Kafka.
This mechanism enforces the expiry of an authenticated session between the client and the broker after a defined period of time.
When a session expires, the client immediately starts a new session by reusing the existing connection rather than dropping it.
Session re-authentication is disabled by default.
To enable it, you set a time value for maxSecondsWithoutReauthentication
in the oauth
listener configuration.
The same property is used to configure session re-authentication for OAUTHBEARER
and PLAIN
authentication.
For an example configuration, see Configuring OAuth 2.0 authentication on listeners.
Session re-authentication must be supported by the Kafka client libraries used by the client.
Session re-authentication can be used with fast local JWT or introspection endpoint token validation.
Client re-authentication
When the broker’s authenticated session expires, the client must re-authenticate to the existing session by sending a new, valid access token to the broker, without dropping the connection.
If token validation is successful, a new client session is started using the existing connection.
If the client fails to re-authenticate, the broker will close the connection if further attempts are made to send or receive messages.
Java clients that use Kafka client library 2.2 or later automatically re-authenticate if the re-authentication mechanism is enabled on the broker.
Session re-authentication also applies to refresh tokens, if used.
When the session expires, the client refreshes the access token by using its refresh token.
The client then uses the new access token to re-authenticate to the existing session.
Session expiry
When session re-authentication is configured, session expiry works differently for OAUTHBEARER
and PLAIN
authentication.
For OAUTHBEARER
and PLAIN
, using the client ID and secret method:
For PLAIN
using the long-lived access token method:
-
The broker’s authenticated session will expire at the configured maxSecondsWithoutReauthentication
.
-
Re-authentication will fail if the access token expires before the configured time.
Although session re-authentication is attempted, PLAIN
has no mechanism for refreshing tokens.
If maxSecondsWithoutReauthentication
is not configured, OAUTHBEARER
and PLAIN
clients can remain connected to brokers indefinitely, without needing to re-authenticate.
Authenticated sessions do not end with access token expiry.
However, this can be considered when configuring authorization, for example, by using keycloak
authorization or installing a custom authorizer.
16.2.5. Example: Enabling OAuth 2.0 authentication
This example shows how to configure client access to a Kafka cluster using OAUth 2.0 authentication.
The procedures describe the configuration required to set up OAuth 2.0 authentication on Kafka listeners, Kafka Java clients, and Kafka components.
Setting up OAuth 2.0 authentication on listeners
Configure Kafka listeners so that they are enabled to use OAuth 2.0 authentication using an authorization server.
We advise using OAuth 2.0 over an encrypted interface through through a listener with tls: true
.
Plain listeners are not recommended.
If the authorization server is using certificates signed by the trusted CA and matching the OAuth 2.0 server hostname, TLS connection works using the default settings.
Otherwise, you may need to configure the truststore with proper certificates or disable the certificate hostname validation.
Procedure
-
Specify a listener in the Kafka
resource with an oauth
authentication type.
Example listener configuration with OAuth 2.0 authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: oauth
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
#...
-
Configure the OAuth listener depending on the authorization server and validation type:
-
Apply the changes to the Kafka
configuration.
-
Check the update in the logs or by watching the pod state transitions:
kubectl logs -f ${POD_NAME} -c ${CONTAINER_NAME}
kubectl get pod -w
The rolling update configures the brokers to use OAuth 2.0 authentication.
Setting up OAuth 2.0 on Kafka Java clients
Configure Kafka producer and consumer APIs to use OAuth 2.0 for interaction with Kafka brokers.
Add a callback plugin to your client pom.xml
file, then configure your client for OAuth 2.0.
How you configure the authentication properties depends on the authentication method you are using to access the OAuth 2.0 authorization server.
In this procedure, the properties are specified in a properties file, then loaded into the client configuration.
Prerequisites
-
Strimzi and Kafka are running
-
An OAuth 2.0 authorization server is deployed and configured for OAuth access to Kafka brokers
-
Kafka brokers are configured for OAuth 2.0
Procedure
-
Add the client library with OAuth 2.0 support to the pom.xml
file for the Kafka client:
<dependency>
<groupId>io.strimzi</groupId>
<artifactId>kafka-oauth-client</artifactId>
<version>0.15.0</version>
</dependency>
-
Configure the client depending on the OAuth 2.0 authentication method:
For example, specify the properties for the authentication method in a client.properties
file.
-
Input the client properties for OAUTH 2.0 authentication into the Java client code.
Example showing input of client properties
Properties props = new Properties();
try (FileReader reader = new FileReader("client.properties", StandardCharsets.UTF_8)) {
props.load(reader);
}
-
Verify that the Kafka client can access the Kafka brokers.
Setting up OAuth 2.0 on Kafka components
This procedure describes how to set up Kafka components to use OAuth 2.0 authentication using an authorization server.
You can configure OAuth 2.0 authentication for the following components:
-
Kafka Connect
-
Kafka MirrorMaker
-
Kafka Bridge
In this scenario, the Kafka component and the authorization server are running in the same cluster.
Prerequisites
-
Strimzi and Kafka are running
-
An OAuth 2.0 authorization server is deployed and configured for OAuth access to Kafka brokers
-
Kafka brokers are configured for OAuth 2.0
Procedure
-
Create a client secret and mount it to the component as an environment variable.
For example, here we are creating a client Secret
for the Kafka Bridge:
apiVersion: kafka.strimzi.io/v1beta2
kind: Secret
metadata:
name: my-bridge-oauth
type: Opaque
data:
clientSecret: MGQ1OTRmMzYtZTllZS00MDY2LWI5OGEtMTM5MzM2NjdlZjQw # (1)
-
The clientSecret
key must be in base64 format.
-
Create or edit the resource for the Kafka component so that OAuth 2.0 authentication is configured for the authentication property.
For OAuth 2.0 authentication, you can use the following options:
For example, here OAuth 2.0 is assigned to the Kafka Bridge client using a client ID and secret, and TLS:
Example OAuth 2.0 authentication configuration using the client secret
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
authentication:
type: oauth # (1)
tokenEndpointUri: https://<auth_server_address>/<path_to_token_endpoint> # (2)
clientId: kafka-bridge
clientSecret:
secretName: my-bridge-oauth
key: clientSecret
tlsTrustedCertificates: # (3)
- secretName: oauth-server-cert
pattern: "*.crt"
-
Authentication type set to oauth
.
-
URI of the token endpoint for authentication.
-
Certificates stored in X.509 format within the specified secrets for TLS connection to the authorization server.
In this example, OAuth 2.0 is assigned to the Kafka Bridge client using a client ID and the location of a client assertion file, with TLS to connect to the authorization server:
Example OAuth 2.0 authentication configuration using client assertion
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
authentication:
type: oauth
tokenEndpointUri: https://<auth_server_address>/<path_to_token_endpoint>
clientId: kafka-bridge
clientAssertionLocation: /var/run/secrets/sso/assertion # (1)
tlsTrustedCertificates:
- secretName: oauth-server-cert
pattern: "*.crt"
-
Filesystem path to the client assertion file used for authenticating the client.
This file is typically added to the deployed pod by an external operator service.
Alternatively, use clientAssertion
to refer to a secret containing the client assertion value.
Here, OAuth 2.0 is assigned to the Kafka Bridge client using a service account token:
Example OAuth 2.0 authentication configuration using the service account token
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
authentication:
type: oauth
accessTokenLocation: /var/run/secrets/kubernetes.io/serviceaccount/token # (1)
-
Path to the service account token file location.
Depending on how you apply OAuth 2.0 authentication, and the type of authorization server, there are additional configuration options you can use:
Additional configuration options
# ...
spec:
# ...
authentication:
# ...
disableTlsHostnameVerification: true # (1)
accessTokenIsJwt: false # (2)
scope: any # (3)
audience: kafka # (4)
connectTimeoutSeconds: 60 # (5)
readTimeoutSeconds: 60 # (6)
httpRetries: 2 # (7)
httpRetryPauseMs: 300 # (8)
includeAcceptHeader: false # (9)
-
(Optional) Disable TLS hostname verification. Default is false
.
-
If you are using opaque tokens, you can apply accessTokenIsJwt: false
so that access tokens are not treated as JWT tokens.
-
(Optional) The scope
for requesting the token from the token endpoint.
An authorization server may require a client to specify the scope.
In this case it is any
.
-
(Optional) The audience
for requesting the token from the token endpoint.
An authorization server may require a client to specify the audience.
In this case it is kafka
.
-
(Optional) The connect timeout in seconds when connecting to the authorization server. The default value is 60.
-
(Optional) The read timeout in seconds when connecting to the authorization server. The default value is 60.
-
(Optional) The maximum number of times to retry a failed HTTP request to the authorization server. The default value is 0
, meaning that no retries are performed. To use this option effectively, consider reducing the timeout times for the connectTimeoutSeconds
and readTimeoutSeconds
options. However, note that retries may prevent the current worker thread from being available to other requests, and if too many requests stall, it could make the Kafka broker unresponsive.
-
(Optional) The time to wait before attempting another retry of a failed HTTP request to the authorization server. By default, this time is set to zero, meaning that no pause is applied. This is because many issues that cause failed requests are per-request network glitches or proxy issues that can be resolved quickly. However, if your authorization server is under stress or experiencing high traffic, you may want to set this option to a value of 100 ms or more to reduce the load on the server and increase the likelihood of successful retries.
-
(Optional) Some authorization servers have issues with client sending Accept: application/json
header. By setting includeAcceptHeader: false
the header will not be sent. Default is true
.
-
Apply the changes to the resource configuration of the component.
-
Check the update in the logs or by watching the pod state transitions:
kubectl logs -f ${POD_NAME} -c ${CONTAINER_NAME}
kubectl get pod -w
The rolling updates configure the component for interaction with Kafka brokers using OAuth 2.0 authentication.
16.3. Using OAuth 2.0 token-based authorization
Strimzi supports the use of OAuth 2.0 token-based authorization through Keycloak Authorization Services,
which lets you manage security policies and permissions centrally.
Security policies and permissions defined in Keycloak grant access to Kafka resources.
Users and clients are matched against policies that permit access to perform specific actions on Kafka brokers.
Kafka allows all users full access to brokers by default, but also provides the AclAuthorizer
and StandardAuthorizer
plugins to configure authorization based on Access Control Lists (ACLs).
The ACL rules managed by these plugins are used to grant or deny access to resources based on username, and these rules are stored within the Kafka cluster itself.
However, OAuth 2.0 token-based authorization with Keycloak offers far greater flexibility on how you wish to implement access control to Kafka brokers.
In addition, you can configure your Kafka brokers to use OAuth 2.0 authorization and ACLs.
16.3.1. Example: Enabling OAuth 2.0 authorization
This example procedure shows how to configure Kafka to use OAuth 2.0 authorization using Keycloak Authorization Services.
To enable OAuth 2.0 authorization using Keycloak, configure the Kafka
resource to use keycloak
authorization and specify the properties required to access the authorization server and Keycloak Authorization Services.
Keycloak server Authorization Services REST endpoints extend token-based authentication with Keycloak by applying defined security policies on a particular user,
and providing a list of permissions granted on different resources for that user.
Policies use roles and groups to match permissions to users.
OAuth 2.0 authorization enforces permissions locally based on the received list of grants for the user from Keycloak Authorization Services.
A Keycloak authorizer (KeycloakAuthorizer
) is provided with Strimzi.
The authorizer fetches a list of granted permissions from the authorization server as needed,
and enforces authorization locally on Kafka, making rapid authorization decisions for each client request.
Before you begin
Consider the access you require or want to limit for certain users.
You can use a combination of Keycloak groups, roles, clients, and users to configure access in Keycloak.
Typically, groups are used to match users based on organizational departments or geographical locations.
And roles are used to match users based on their function.
With Keycloak, you can store users and groups in LDAP, whereas clients and roles cannot be stored this way.
Storage and access to user data may be a factor in how you choose to configure authorization policies.
Note
|
Super users always have unconstrained access to Kafka regardless of the authorization implemented.
|
Prerequisites
-
Strimzi must be configured to use OAuth 2.0 with Keycloak for token-based authentication.
You use the same Keycloak server endpoint when you set up authorization.
-
OAuth 2.0 authentication must be configured with the maxSecondsWithoutReauthentication
option to enable re-authentication.
Procedure
-
Access the Keycloak Admin Console or use the Keycloak Admin CLI to enable Authorization Services for the OAuth 2.0 client for Kafka you created when setting up OAuth 2.0 authentication.
-
Use Authorization Services to define resources, authorization scopes, policies, and permissions for the client.
-
Bind the permissions to users and clients by assigning them roles and groups.
-
Configure the kafka
resource to use keycloak
authorization, and to be able to access the authorization server and Authorization Services.
Example OAuth 2.0 authorization configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
authorization:
type: keycloak (1)
tokenEndpointUri: <https://<auth-server-address>/realms/external/protocol/openid-connect/token> (2)
clientId: kafka (3)
delegateToKafkaAcls: false (4)
disableTlsHostnameVerification: false (5)
superUsers: (6)
- CN=user-1
- user-2
- CN=user-3
tlsTrustedCertificates: (7)
- secretName: oauth-server-cert
pattern: "*.crt"
grantsRefreshPeriodSeconds: 60 (8)
grantsRefreshPoolSize: 5 (9)
grantsMaxIdleSeconds: 300 (10)
grantsGcPeriodSeconds: 300 (11)
grantsAlwaysLatest: false (12)
connectTimeoutSeconds: 60 (13)
readTimeoutSeconds: 60 (14)
httpRetries: 2 (15)
enableMetrics: false (16)
includeAcceptHeader: false (17)
#...
-
Type keycloak
enables Keycloak authorization.
-
URI of the Keycloak token endpoint. For production, always use https://
urls.
When you configure token-based oauth
authentication, you specify a jwksEndpointUri
as the URI for local JWT validation.
The hostname for the tokenEndpointUri
URI must be the same.
-
The client ID of the OAuth 2.0 client definition in Keycloak that has Authorization Services enabled. Typically, kafka
is used as the ID.
-
(Optional) Delegate authorization to Kafka AclAuthorizer
and StandardAuthorizer
if access is denied by Keycloak Authorization Services policies.
Default is false
.
-
(Optional) Disable TLS hostname verification. Default is false
.
-
(Optional) Designated super users.
-
(Optional) Certificates stored in X.509 format within the specified secrets for TLS connection to the authorization server.
-
(Optional) The time between two consecutive grants refresh runs. That is the maximum time for active sessions to detect any permissions changes for the user on Keycloak. The default value is 60.
-
(Optional) The number of threads to use to refresh (in parallel) the grants for the active sessions. The default value is 5.
-
(Optional) The time, in seconds, after which an idle grant in the cache can be evicted. The default value is 300.
-
(Optional) The time, in seconds, between consecutive runs of a job that cleans stale grants from the cache. The default value is 300.
-
(Optional) Controls whether the latest grants are fetched for a new session. When enabled, grants are retrieved from Keycloak and cached for the user. The default value is false
.
-
(Optional) The connect timeout in seconds when connecting to the Keycloak token endpoint. The default value is 60.
-
(Optional) The read timeout in seconds when connecting to the Keycloak token endpoint. The default value is 60.
-
(Optional) The maximum number of times to retry (without pausing) a failed HTTP request to the authorization server. The default value is 0
, meaning that no retries are performed. To use this option effectively, consider reducing the timeout times for the connectTimeoutSeconds
and readTimeoutSeconds
options. However, note that retries may prevent the current worker thread from being available to other requests, and if too many requests stall, it could make Kafka unresponsive.
-
(Optional) Enable or disable OAuth metrics. The default value is false
.
-
(Optional) Some authorization servers have issues with client sending Accept: application/json
header. By setting includeAcceptHeader: false
the header will not be sent. Default is true
.
-
Apply the changes to the Kafka
configuration.
-
Check the update in the logs or by watching the pod state transitions:
kubectl logs -f ${POD_NAME} -c kafka
kubectl get pod -w
The rolling update configures the brokers to use OAuth 2.0 authorization.
-
Verify the configured permissions by accessing Kafka brokers as clients or users with specific roles, ensuring they have the necessary access and do not have unauthorized access.
16.4. Setting up permissions in Keycloak
When using Keycloak as the OAuth 2.0 authorization server, Kafka permissions are granted to user accounts or service accounts using authorization permissions.
To grant permissions to access Kafka, create an OAuth client specification in Keycloak that maps the authorization models of Keycloak Authorization Services and Kafka.
16.4.1. Kafka and Keycloak authorization models
Kafka and Keycloak use different authorization models.
Kafka authorization model
Kafka’s authorization model uses resource types and operations to describe ACLs for a user.
When a Kafka client performs an action on a broker, the broker uses the configured KeycloakAuthorizer
to check the client’s permissions, based on the action and resource type.
Each resource type has a set of available permissions for operations.
For example, the Topic
resource type has Create
and Write
permissions among others.
Keycloak authorization model
Keycloak’s authorization services model has four concepts for defining and granting permissions:
-
Resources
-
Scopes
-
Policies
-
Permissions
16.4.2. Mapping authorization models
The Kafka authorization model is used as a basis for defining the Keycloak roles and resources that control access to Kafka.
To grant Kafka permissions to user accounts or service accounts, you first create an OAuth client specification in Keycloak for the Kafka cluster.
You then specify Keycloak Authorization Services rules on the client.
Typically, the client ID of the OAuth client that represents the Kafka cluster is kafka
.
The example configuration files provided with Strimzi use kafka
as the OAuth client id.
Note
|
If you have multiple Kafka clusters, you can use a single OAuth client (kafka ) for all of them.
This gives you a single, unified space in which to define and manage authorization rules.
However, you can also use different OAuth client ids (for example, my-cluster-kafka or cluster-dev-kafka ) and define authorization rules for each cluster within each client configuration.
|
The kafka
client definition must have the Authorization Enabled option enabled in the Keycloak Admin Console.
For information on enabling authorization services, see the guide to Keycloak Authorization Services.
All permissions exist within the scope of the kafka
client.
If you have different Kafka clusters configured with different OAuth client IDs, they each need a separate set of permissions even though they’re part of the same Keycloak realm.
When the Kafka client uses OAUTHBEARER authentication, the Keycloak authorizer (KeycloakAuthorizer
) uses the access token of the current session to retrieve a list of grants from the Keycloak server.
To grant permissions, the authorizer evaluates the grants list (received and cached) from Keycloak Authorization Services based on the access token owner’s policies and permissions.
Uploading authorization scopes for Kafka permissions
An initial Keycloak configuration usually involves uploading authorization scopes to create a list of all possible actions that can be performed on each Kafka resource type.
This step is performed once only, before defining any permissions.
You can add authorization scopes manually instead of uploading them.
Authorization scopes should contain the following Kafka permissions regardless of the resource type:
-
Create
-
Write
-
Read
-
Delete
-
Describe
-
Alter
-
DescribeConfigs
-
AlterConfigs
-
ClusterAction
-
IdempotentWrite
If you’re certain you won’t need a permission (for example, IdempotentWrite
), you can omit it from the list of authorization scopes.
However, that permission won’t be available to target on Kafka resources.
Note
|
The All permission is not supported.
|
Resource patterns for permissions checks
Resource patterns are used for pattern matching against the targeted resources when performing permission checks.
The general pattern format is <resource_type>:<pattern_name>
.
The resource types mirror the Kafka authorization model.
The pattern allows for two matching options:
Example patterns for resources
Topic:my-topic
Topic:orders-*
Group:orders-*
Cluster:*
Additionally, the general pattern format can be prefixed by kafka-cluster:<cluster_name>
followed by a comma, where <cluster_name>
refers to the metadata.name
in the Kafka custom resource.
Example patterns for resources with cluster prefix
kafka-cluster:my-cluster,Topic:*
kafka-cluster:*,Group:b_*
When the kafka-cluster
prefix is missing, it is assumed to be kafka-cluster:*
.
When defining a resource, you can associate it with a list of possible authorization scopes which are relevant to the resource.
Set whatever actions make sense for the targeted resource type.
Though you may add any authorization scope to any resource, only the scopes supported by the resource type are considered for access control.
Policies for applying access permission
Policies are used to target permissions to one or more user accounts or service accounts.
Targeting can refer to:
A policy is given a unique name and can be reused to target multiple permissions to multiple resources.
Permissions to grant access
Use fine-grained permissions to pull together the policies, resources, and authorization scopes that grant access to users.
The name of each permission should clearly define which permissions it grants to which users.
For example, Dev Team B can read from topics starting with x
.
16.4.3. Permissions for common Kafka operations
The following examples demonstrate the user permissions required for performing common operations on Kafka.
Create a topic
To create a topic, the Create
permission is required for the specific topic, or for Cluster:kafka-cluster
.
bin/kafka-topics.sh --create --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
List topics
If a user has the Describe
permission on a specified topic, the topic is listed.
bin/kafka-topics.sh --list \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Display topic details
To display a topic’s details, Describe
and DescribeConfigs
permissions are required on the topic.
bin/kafka-topics.sh --describe --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Produce messages to a topic
To produce messages to a topic, Describe
and Write
permissions are required on the topic.
If the topic hasn’t been created yet, and topic auto-creation is enabled, the permissions to create a topic are required.
bin/kafka-console-producer.sh --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --producer.config=/tmp/config.properties
Consume messages from a topic
To consume messages from a topic, Describe
and Read
permissions are required on the topic.
Consuming from the topic normally relies on storing the consumer offsets in a consumer group, which requires additional Describe
and Read
permissions on the consumer group.
Two resources
are needed for matching. For example:
Topic:my-topic
Group:my-group-*
bin/kafka-console-consumer.sh --topic my-topic --group my-group-1 --from-beginning \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --consumer.config /tmp/config.properties
Produce messages to a topic using an idempotent producer
As well as the permissions for producing to a topic, an additional IdempotentWrite
permission is required on the
Cluster:kafka-cluster
resource.
Two resources
are needed for matching. For example:
Topic:my-topic
Cluster:kafka-cluster
bin/kafka-console-producer.sh --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --producer.config=/tmp/config.properties --producer-property enable.idempotence=true --request-required-acks -1
List consumer groups
When listing consumer groups, only the groups on which the user has the Describe
permissions are returned.
Alternatively, if the user has the Describe
permission on the Cluster:kafka-cluster
, all the consumer groups are returned.
bin/kafka-consumer-groups.sh --list \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Display consumer group details
To display a consumer group’s details, the Describe
permission is required on the group and the topics associated with the group.
bin/kafka-consumer-groups.sh --describe --group my-group-1 \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Change topic configuration
To change a topic’s configuration, the Describe
and Alter
permissions are required on the topic.
bin/kafka-topics.sh --alter --topic my-topic --partitions 2 \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Display Kafka broker configuration
In order to use kafka-configs.sh
to get a broker’s configuration, the DescribeConfigs
permission is required on the
Cluster:kafka-cluster
.
bin/kafka-configs.sh --entity-type brokers --entity-name 0 --describe --all \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Change Kafka broker configuration
To change a Kafka broker’s configuration, DescribeConfigs
and AlterConfigs
permissions are required on Cluster:kafka-cluster
.
bin/kafka-configs --entity-type brokers --entity-name 0 --alter --add-config log.cleaner.threads=2 \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Delete a topic
To delete a topic, the Describe
and Delete
permissions are required on the topic.
bin/kafka-topics.sh --delete --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Select a lead partition
To run leader selection for topic partitions, the Alter
permission is required on the Cluster:kafka-cluster
.
bin/kafka-leader-election.sh --topic my-topic --partition 0 --election-type PREFERRED /
--bootstrap-server my-cluster-kafka-bootstrap:9092 --admin.config /tmp/config.properties
Reassign partitions
To generate a partition reassignment file, Describe
permissions are required on the topics involved.
bin/kafka-reassign-partitions.sh --topics-to-move-json-file /tmp/topics-to-move.json --broker-list "0,1" --generate \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config /tmp/config.properties > /tmp/partition-reassignment.json
To execute the partition reassignment, Describe
and Alter
permissions are required on Cluster:kafka-cluster
. Also,
Describe
permissions are required on the topics involved.
bin/kafka-reassign-partitions.sh --reassignment-json-file /tmp/partition-reassignment.json --execute \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config /tmp/config.properties
To verify partition reassignment, Describe
, and AlterConfigs
permissions are required on Cluster:kafka-cluster
, and on each
of the topics involved.
bin/kafka-reassign-partitions.sh --reassignment-json-file /tmp/partition-reassignment.json --verify \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config /tmp/config.properties
16.4.4. Example: Setting up Keycloak Authorization Services
If you are using OAuth 2.0 with Keycloak for token-based authentication,
you can also use Keycloak to configure authorization rules to constrain client access to Kafka brokers.
This example explains how to use Keycloak Authorization Services with keycloak
authorization.
Set up Keycloak Authorization Services to enforce access restrictions on Kafka clients.
Keycloak Authorization Services use authorization scopes, policies and permissions to define and apply access control to resources.
Keycloak Authorization Services REST endpoints provide a list of granted permissions on resources for authenticated users.
The list of grants (permissions) is fetched from the Keycloak server as the first action after an authenticated session is established by the Kafka client.
The list is refreshed in the background so that changes to the grants are detected.
Grants are cached and enforced locally on the Kafka broker for each user session to provide fast authorization decisions.
kafka-ephemeral-oauth-single-keycloak-authz.yaml
-
An example Kafka
custom resource configured for OAuth 2.0 token-based authorization using Keycloak.
You can use the custom resource to deploy a Kafka cluster that uses keycloak
authorization and token-based oauth
authentication.
kafka-authz-realm.json
-
An example Keycloak realm configured with sample groups, users, roles and clients.
You can import the realm into a Keycloak instance to set up fine-grained permissions to access Kafka.
If you want to try the example with Keycloak, use these files to perform the tasks outlined in this section in the order shown.
Authentication
When you configure token-based oauth
authentication, you specify a jwksEndpointUri
as the URI for local JWT validation.
When you configure keycloak
authorization, you specify a tokenEndpointUri
as the URI of the Keycloak token endpoint.
The hostname for both URIs must be the same.
Targeted permissions with group or role policies
In Keycloak, confidential clients with service accounts enabled can authenticate to the server in their own name using a client ID and a secret.
This is convenient for microservices that typically act in their own name, and not as agents of a particular user (like a web site).
Service accounts can have roles assigned like regular users.
They cannot, however, have groups assigned.
As a consequence, if you want to target permissions to microservices using service accounts, you cannot use group policies, and should instead use role policies.
Conversely, if you want to limit certain permissions only to regular user accounts where authentication with a username and password is required, you can achieve that as a side effect of using the group policies rather than the role policies.
This is what is used in this example for permissions that start with ClusterManager
.
Performing cluster management is usually done interactively using CLI tools.
It makes sense to require the user to log in before using the resulting access token to authenticate to the Kafka broker.
In this case, the access token represents the specific user, rather than the client application.
Setting up permissions in Keycloak
Set up Keycloak, then connect to its Admin Console and add the preconfigured realm.
Use the example kafka-authz-realm.json
file to import the realm.
You can check the authorization rules defined for the realm in the Admin Console.
The rules grant access to the resources on the Kafka cluster configured to use the example Keycloak realm.