EventGatewaySchemaRegistry로 Kafka 메시지 스키마 검증하기
이 튜토리얼에서는 Kong Operator의 EventGatewaySchemaRegistry 리소스로 스키마 레지스트리를 연결하고, 가상 클러스터의 프로듀스·컨슈머 정책에 schemaValidation 설정을 넣어 Kafka 메시지 스키마 검증을 적용하는 방법을 배워요. Bitnami Helm 차트로 3브로커 Kafka 클러스터를 준비하고, 그 위에 Confluent Schema Registry를 배포한 뒤 Konnect 기반 Event Gateway 환경을 구성해요. 마지막에는 검증 규칙이 실제로 동작해서 스키마에 맞지 않는 메시지가 거부되는지 확인해봐요
출처: 문서
본문
TL;DR
Kong Operator로 Kafka 메시지 스키마는 어떻게 검증하나요?
스키마 레지스트리를 가리키는 EventGatewaySchemaRegistry 리소스를 만든 다음, schemaValidation 설정과 함께 EventGatewayVirtualClusterConsumePolicy 또는 EventGatewayVirtualClusterProducePolicy에서 이 리소스를 참조해요.
사전 준비
Kubernetes 네임스페이스
이 튜토리얼 전반에서 사용할 네임스페이스를 만들어요:
kubectl create namespace kong
kubectl create namespace kafka
Kafka 클러스터
스키마 레지스트리는 스키마를 Kafka에 저장하고, Kong Event Gateway는 프록시할 백엔드 클러스터가 필요해요. Bitnami 차트를 사용해 브로커 3개로 구성된 Kafka 클러스터를 배포해요:
-
Bitnami Helm 저장소를 추가해요:
helm repo add bitnami https://charts.bitnami.com/bitnami helm repo update -
Kafka 설정 파일을 작성해요:
cat <<'EOF' >/tmp/kafka-values.yaml image: registry: docker.io repository: bitnamilegacy/kafka tag: 4.0.0-debian-12-r6 listeners: client: protocol: PLAINTEXT externalAccess: enabled: false kraft: enabled: true controller: replicaCount: 3 broker: replicaCount: 0 EOF -
Kafka를 설치해요:
helm install kafka-cluster bitnami/kafka \ -n kafka \ --version 32.4.3 \ -f /tmp/kafka-values.yaml -
모든 Kafka 브로커가 준비될 때까지 기다려요:
kubectl wait pod -n kafka \ --for=condition=Ready \ --selector app.kubernetes.io/name=kafka \ --timeout=5m
Confluent Schema Registry
Kafka 클러스터를 백엔드로 사용하는 Confluent Schema Registry를 배포해요. 클러스터 안에서 실행하면 Kong Event Gateway가 http://schema-registry.kafka.svc.cluster.local:8081 주소로 레지스트리에 접근할 수 있어요:
-
레지스트리와 Service를 배포해요:
echo ' apiVersion: apps/v1 kind: Deployment metadata: name: schema-registry namespace: kafka spec: replicas: 1 selector: matchLabels: app: schema-registry template: metadata: labels: app: schema-registry spec: enableServiceLinks: false containers: - name: schema-registry image: confluentinc/cp-schema-registry:8.2.1 ports: - containerPort: 8081 env: - name: SCHEMA_REGISTRY_HOST_NAME value: schema-registry - name: SCHEMA_REGISTRY_LISTENERS value: http://0.0.0.0:8081 - name: SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS value: kafka-cluster.kafka.svc.cluster.local:9092 --- apiVersion: v1 kind: Service metadata: name: schema-registry namespace: kafka spec: selector: app: schema-registry ports: - name: http port: 8081 targetPort: 8081 ' | kubectl apply -f - -
레지스트리가 준비될 때까지 기다려요:
kubectl wait pod -n kafka \ --for=condition=Ready \ --selector app=schema-registry \ --timeout=5m
Kong Konnect
Konnect 계정이 없다면 온보딩 마법사를 통해 빠르게 시작할 수 있어요.
-
이 튜토리얼을 완료하려면 다음의 Konnect 항목들이 필요해요:
- 개인 액세스 토큰(PAT): Konnect PAT 페이지를 열고 Generate Token을 선택해서 새 개인 액세스 토큰을 만들어요.
-
개인 액세스 토큰을 환경 변수로 설정해요:
export KONNECT_TOKEN='YOUR KONNECT TOKEN'
Kong Operator 실행
-
Kong Helm 차트를 추가해요:
helm repo add kong https://charts.konghq.com helm repo update -
Helm을 사용해 Kong Operator를 설치해요:
helm upgrade --install kong-operator kong/kong-operator -n kong-system \ --create-namespace \ --set image.tag=2.3 \ --set env.ENABLE_CONTROLLER_KONNECT=true \ --set env.ENABLE_CONTROLLER_KEGDATAPLANE=truecert-manager가 어드미션 및 컨버전 웹훅 인증서를 발급하고 갱신하도록 하려면, 클러스터에 cert-manager를 설치하고 다음 단계에서 설치할 때 다음 인자를 전달해서 cert-manager 통합을 활성화해요:
--set global.webhooks.options.certManager.enabled=true이 기능을 활성화하지 않으면 차트가 자동으로 자체 서명 인증서를 생성하고 주입해요. 이 인증서들의 라이프사이클을 관리할 수 있도록 cert-manager를 활성화하는 것을 권장해요. Kong Operator는 컨트롤 플레인과 데이터 플레인 간 mTLS 통신에 사용할 인증서에 서명해 줄 인증 기관이 필요해요. 이 처리는 Helm 차트가 자동으로 해줘요. 커스텀 CA 인증서를 직접 제공해야 한다면, Helm 차트의
values.yaml에 있는certificateAuthority섹션을 참고해서 자체 CA 인증서를 만들고 참조하는 방법을 알아보세요.
KonnectAPIAuthConfiguration 리소스 생성
kubectl create namespace kong --dry-run=client -o yaml | kubectl apply -f -
echo '
kind: KonnectAPIAuthConfiguration
apiVersion: konnect.konghq.com/v1alpha1
metadata:
name: konnect-api-auth
namespace: kong
spec:
type: token
token: "'$KONNECT_TOKEN'"
serverURL: us.api.konghq.com
' | kubectl apply -f -
Kong Event Gateway 컨트롤 플레인, 백엔드 클러스터, 가상 클러스터
스키마 레지스트리와 스키마 검증 정책은 Kong Event Gateway 컨트롤 플레인과 가상 클러스터에 연결돼요. Kafka를 가리키는 백엔드 클러스터와 함께 이 리소스들을 만들어요:
-
KonnectEventGateway리소스를 만들어요:echo ' apiVersion: konnect.konghq.com/v1alpha1 kind: KonnectEventGateway metadata: name: cp-event-1 namespace: kong spec: apiSpec: name: cp-event-1 description: Event Gateway control plane managed by Kubernetes konnect: authRef: name: konnect-api-auth ' | kubectl apply -f - kubectl wait konnecteventgateway/cp-event-1 -n kong \ --for=condition=Programmed=True \ --timeout=10m -
EventGatewayBackendCluster리소스를 만들어요:echo ' apiVersion: configuration.konghq.com/v1alpha1 kind: EventGatewayBackendCluster metadata: name: default-backend-cluster namespace: kong spec: gatewayRef: type: namespacedRef namespacedRef: name: cp-event-1 apiSpec: name: default_backend_cluster bootstrapServers: - kafka-cluster.kafka.svc.cluster.local:9092 authentication: type: anonymous anonymous: {} insecureAllowAnonymousVirtualClusterAuth: Enabled tls: enabled: Disabled ' | kubectl apply -f -
kubectl wait eventgatewaybackendcluster/default-backend-cluster -n kong
--for=condition=Programmed=True
--timeout=10m
1. `EventGatewayVirtualCluster` 리소스를 생성해요:
```bash
echo '
apiVersion: configuration.konghq.com/v1alpha1
kind: EventGatewayVirtualCluster
metadata:
name: example-virtual-cluster
namespace: kong
spec:
eventGatewayBackendClusterRef:
type: namespacedRef
namespacedRef:
name: default-backend-cluster
apiSpec:
name: example_virtual_cluster
dnsLabel: vcluster-1
aclMode: passthrough
authentication:
- type: anonymous
namespace:
prefix: "vc1_"
mode: hide_prefix
' | kubectl apply -f -
kubectl wait eventgatewayvirtualcluster/example-virtual-cluster -n kong \
--for=condition=Programmed=True \
--timeout=10m
EventGatewaySchemaRegistry는 Kong Event Gateway를 스키마 레지스트리와 연결해서, 레코드가 클라이언트나 백엔드 클러스터에 도달하기 전에 consume 정책과 produce 정책이 Kafka 레코드 스키마를 검증할 수 있도록 해줘요.
아래 예제는 사전 준비에서 만든 cp-event-1 컨트롤 플레인, example-virtual-cluster 가상 클러스터, schema-registry 레지스트리 Service를 사용해요.
EventGatewaySchemaRegistry 생성하기
-
스키마 레지스트리 엔드포인트를 가리키는
EventGatewaySchemaRegistry리소스를 생성해요:echo ' apiVersion: configuration.konghq.com/v1alpha1 kind: EventGatewaySchemaRegistry metadata: name: example-schema-registry namespace: kong spec: gatewayRef: type: namespacedRef namespacedRef: name: cp-event-1 apiSpec: type: confluent confluent: name: example_schema_registry description: Schema registry for example_virtual_cluster config: endpoint: http://schema-registry.kafka.svc.cluster.local:8081 schemaType: json timeoutSeconds: 10 ' | kubectl apply -f - -
리소스가 준비될 때까지 기다려요:
kubectl wait eventgatewayschemaregistry/example-schema-registry -n kong \ --for=condition=Programmed=True \ --timeout=10m
가상 클러스터에 스키마 검증 적용하기
EventGatewayVirtualClusterConsumePolicy에서 type: schemaValidation을 사용해 EventGatewaySchemaRegistry를 참조해요. Kong Event Gateway는 레코드가 직렬화되는 방식에 따라 두 가지 검증 모드를 지원해요.
이 예제는 레코드를 Confluent 와이어 포맷(레코드 헤더에 스키마 ID가 포함된 방식)으로 직렬화하는 프로듀서를 위한 confluentSchemaRegistry를 사용해요. Kong Event Gateway는 레지스트리에서 ID로 스키마를 조회해요:
echo '
apiVersion: configuration.konghq.com/v1alpha1
kind: EventGatewayVirtualClusterConsumePolicy
metadata:
name: example-schema-validation-confluent
namespace: kong
spec:
eventGatewayVirtualClusterRef:
type: namespacedRef
namespacedRef:
name: example-virtual-cluster
apiSpec:
type: schemaValidation
schemaValidation:
name: example_schema_validation_confluent
description: Validate Confluent wire-format records against the registry
config:
type: confluentSchemaRegistry
confluentSchemaRegistry:
schemaRegistry:
kind: EventGatewaySchemaRegistry
name: example-schema-registry
keyValidationAction: mark
valueValidationAction: mark
' | kubectl apply -f -
프로듀서가 와이어 포맷 스키마 ID 없이 일반 JSON 레코드를 보낸다면 대신 json 모드를 사용하세요. 자세한 내용은 FAQ를 확인하세요.
가상 클러스터에는 하나의 일관된 스키마 검증 정책이 있어야 하니, 한 번에
type: schemaValidation이 설정된EventGatewayVirtualClusterConsumePolicy를 하나만 적용하세요. 동일한type: schemaValidation설정은EventGatewayVirtualClusterProducePolicy에서도 사용할 수 있어서, 레코드가 백엔드 클러스터에 도달하기 전에 검증할 수 있어요.
리소스가 준비될 때까지 기다려요:
kubectl wait eventgatewayvirtualclusterconsumepolicy/example-schema-validation-confluent -n kong \
--for=condition=Programmed=True \
--timeout=10m
확인하기
정책이 오류 없이 reconcile됐는지 확인해요:
kubectl describe eventgatewayvirtualclusterconsumepolicy/example-schema-validation-confluent -n kong
Programmed=True 조건이 보이면 Kong Event Gateway가 정책을 수용했고 example-virtual-cluster 가상 클러스터에 스키마 검증을 적용하고 있다는 뜻이에요. 검증에 실패한 레코드는 keyValidationAction과 valueValidationAction에 mark를 설정했는지 skip을 설정했는지에 따라 kong/server 헤더가 붙거나 건너뛰어져서 클라이언트에 전달되지 않아요.
자주 묻는 질문(FAQ)
-
일반 JSON 레코드는 어떻게 검증하나요? 프로듀서가 와이어 포맷 스키마 ID 없이 일반 JSON 레코드를 보낼 때는
confluentSchemaRegistry대신json을 사용하세요. 이 모드는 각 레코드가 유효한 JSON인지만 확인하기 때문에 스키마 레지스트리를 조회하지 않아요.schemaRegistry는 아예 생략하세요.type이json이면 Konnect가 이를 거부해요.이 정책은
confluentSchemaRegistry정책을 대체하는 위치에 적용하세요. 둘을 함께 사용하면 안 돼요:echo ' apiVersion: configuration.konghq.com/v1alpha1 kind: EventGatewayVirtualClusterConsumePolicy metadata: name: example-schema-validation-json namespace: kong spec: eventGatewayVirtualClusterRef: type: namespacedRef namespacedRef: name: example-virtual-cluster apiSpec: type: schemaValidation schemaValidation: name: example_schema_validation_json description: Validate that consumed records are valid JSON config: type: json json: valueValidationAction: skip ' | kubectl apply -f - -
인증이 필요한 스키마 레지스트리에는 어떻게 연결하나요? 사전 준비 단계에서 배포한 레지스트리는 인증 없는 요청도 수락하기 때문에 이 튜토리얼에서는
authentication필드를 생략했어요. 직접 운영하는 레지스트리가 기본 인증을 요구한다면 비밀번호를 Kubernetes Secret에 저장하세요. Kong Operator는konghq.com/secret="true"레이블이 붙은 Secret만 감시해요:kubectl create secret generic schema-registry-password \ --from-literal=password='my-schema-registry-password' \ -n kong kubectl label secret schema-registry-password -n kong konghq.com/secret="true"그다음에는 해당 Secret을 참조하는
authentication블록을config에 추가하세요:config: endpoint: https://schema-registry.example.com schemaType: json timeoutSeconds: 10 authentication: type: basic basic: username: schema-registry-user password: type: secretRef secretRef: name: schema-registry-password key: password
관련 리소스
더 알아보기 (Learn more)
- Kong Operator로 Event Gateway를 구성하는 전체 개념과 흐름을 담은 기본 문서예요 — Kong Event Gateway with Kong Operator
- 스키마 검증 설정이 들어가는 가상 클러스터 정책의 개념과 구성 방법을 설명해요 — Policies
- Event Gateway를 처음 배포할 때 따라 하는 시작 튜토리얼이에요 — Deploy Kong Event Gateway with port mapping
- KonnectAPIAuthConfiguration에 필요한 개인 액세스 토큰을 발급하는 페이지예요 — Konnect PAT page
- Konnect 계정 가입과 조직 설정을 안내하는 온보딩 마법사예요 — onboarding wizard