본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

폴백 구성으로 손상된 객체 백필

원문 보기 위키 갱신

폴백 구성으로 손상된 객체 백필 (Backfill broken objects with fallback configuration)

Kong Ingress Controller에서 설정 객체가 손상됐을 때 마지막으로 유효했던 구성을 자동으로 대신 사용하게 해주는 Fallback 구성 기능을 소개해요. FallbackConfiguration feature gate와 CONTROLLER_USE_LAST_VALID_CONFIG_FOR_FALLBACK 환경 변수를 활성화하면 broken 객체가 생겨도 전체 설정이 중단되지 않고 마지막 정상 구성으로 백필돼요. 이 튜토리얼에서는 라우트와 컨슈머를 만들고, 일부러 라우트를 손상시킨 뒤 백필 동작을 확인하고, 객체를 수정해 다시 정상 상태로 돌리는 과정을 Konnect 배포와 온프레미스 배포 두 환경에서 단계별로 따라 해봐요

출처: 문서

본문

TL;DR

Kong Ingress Controller 구성의 일부에 대해 마지막으로 정상 동작했던 구성을 자동으로 사용하려면 어떻게 해야 하나요? Kong Ingress Controller에서 FallbackConfiguration 기능 게이트와 CONTROLLER_USE_LAST_VALID_CONFIG_FOR_FALLBACK=true 환경 변수를 활성화하세요

사전 준비 사항

Konnect 배포: Kong Konnect

Konnect 계정이 아직 없다면 온보딩 마법사를 통해 빠르게 시작할 수 있어요.

  1. 이 튜토리얼을 완료하려면 다음의 Konnect 항목들이 필요해요:

    • 개인 액세스 토큰(PAT): Konnect PAT 페이지를 열고 Generate Token을 선택해서 새 개인 액세스 토큰을 생성하세요.
  2. 개인 액세스 토큰을 환경 변수로 설정하세요:

    export KONNECT_TOKEN='YOUR KONNECT TOKEN'
    

Gateway API 활성화

  1. Kong Ingress Controller를 설치하기 전에 Gateway API CRD를 설치하세요.

    kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/standard-install.yaml
    

    {: data-test-prereq="block" }

  2. 사용할 Gateway와 GatewayClass 인스턴스를 생성하세요.

    echo "
    apiVersion: v1
    kind: Namespace
    metadata:
      name: kong
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: GatewayClass
    metadata:
      name: kong
      annotations:
        konghq.com/gatewayclass-unmanaged: 'true'
    spec:
      controllerName: konghq.com/kic-gateway-controller
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: Gateway
    metadata:
      name: kong
    spec:
      gatewayClassName: kong
      listeners:
      - name: proxy
        port: 80
        protocol: HTTP
        allowedRoutes:
          namespaces:
            from: All
    " | kubectl apply -n kong -f -
    

    {: data-test-prereq="block" }

Konnect 배포: KIC 컨트롤 플레인 생성

Konnect API를 사용해서 새로운 CLUSTER_TYPE_K8S_INGRESS_CONTROLLER 컨트롤 플레인을 생성하세요:

CONTROL_PLANE_DETAILS=$(curl -X POST "https://us.api.konghq.com/v2/control-planes" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "My KIC CP",
       "cluster_type": "CLUSTER_TYPE_K8S_INGRESS_CONTROLLER"
     }'
)

나중에 values.yaml 파일을 작성할 때 id와 telemetry_endpoint가 필요해요. 환경 변수로 저장해 두세요:

CONTROL_PLANE_ID=$(echo $CONTROL_PLANE_DETAILS | jq -r .id)
CONTROL_PLANE_TELEMETRY=$(echo $CONTROL_PLANE_DETAILS | jq -r '.config.telemetry_endpoint | sub("https://";"")')

mTLS 인증서 생성

Kong Ingress Controller는 TLS 인증서로 보호되는 연결을 통해 Konnect와 통신해요.

openssl을 사용해서 새 인증서를 생성하세요:

openssl req -new -x509 -nodes -newkey rsa:2048 -subj "/CN=kongdp/C=US" -keyout ./tls.key -out ./tls.crt

인증서를 curl로 Konnect API에 전송하려면 한 줄짜리 문자열이어야 해요. awk를 사용해서 인증서를 포맷하세요:

export CERT=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' tls.crt);

다음으로, 인증서를 Konnect에 업로드하세요:

curl -X POST "https://us.api.konghq.com/v2/control-planes/$CONTROL_PLANE_ID/dp-client-certificates" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "cert": "'$CERT'"
     }'

마지막으로, Kong Ingress Controller가 읽을 수 있도록 인증서를 Kubernetes 시크릿에 저장하세요:

kubectl create namespace kong -o yaml --dry-run=client | kubectl apply -f -
kubectl create secret tls konnect-client-tls -n kong --cert=./tls.crt --key=./tls.key

Konnect 배포: Kong Ingress Controller 실행 (Konnect에 연결)

  1. Kong Helm 차트를 추가하세요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. values.yaml 파일을 생성하세요:

    cat <<EOF > values.yaml
    controller:
      ingressController:
        image:
          tag: "3.5"
        env:
          feature_gates: "FillIDs=true"
        konnect:
          license:
            enabled: true
          enabled: true
          controlPlaneID: "$CONTROL_PLANE_ID"
          tlsClientCertSecretName: konnect-client-tls
          apiHostname: "us.kic.api.konghq.com"
    gateway:
      image:
        repository: kong
        tag: "3.9.3"
      env:
        konnect_mode: 'on'
        vitals: "off"
        cluster_mtls: pki
        cluster_telemetry_endpoint: "$CONTROL_PLANE_TELEMETRY:443"
        cluster_telemetry_server_name: "$CONTROL_PLANE_TELEMETRY"
        cluster_cert: /etc/secrets/konnect-client-tls/tls.crt
        cluster_cert_key: /etc/secrets/konnect-client-tls/tls.key
        lua_ssl_trusted_certificate: system
        proxy_access_log: "off"
        dns_stale_ttl: "3600"
      secretVolumes:
         - konnect-client-tls
    EOF
    

    {: data-test-prereq="block" }

  3. Helm으로 Kong Ingress Controller를 설치하세요:

    helm install kong kong/ingress -n kong --create-namespace --set controller.ingressController.env.feature_gates="FallbackConfiguration=true" --set controller.ingressController.env.dump_config=true --set controller.ingressController.env.use_last_valid_config_for_fallback=true --values ./values.yaml --wait 
    

    {: data-test-prereq="block" }

  4. 이후 명령에서 사용할 수 있도록 $PROXY_IP를 환경 변수로 설정하세요:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

온프레미스 배포: Kong Ingress Controller 실행

  1. Kong Helm 차트를 추가하세요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. Helm으로 Kong Ingress Controller를 설치하세요:

    helm install kong kong/ingress -n kong --create-namespace --set controller.ingressController.env.feature_gates="FallbackConfiguration=true" --set controller.ingressController.env.dump_config=true --set controller.ingressController.env.use_last_valid_config_for_fallback=true --wait 
    

    {: data-test-prereq="block" }

  3. 이후 명령에서 사용할 수 있도록 $PROXY_IP를 환경 변수로 설정하세요:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

필요한 Kubernetes 리소스

이 가이드에서는 클러스터에서 몇 가지 Kubernetes 서비스를 사용할 수 있어야 해요. 이 가이드에서 생성하는 리소스들이 이 서비스들을 사용하게 돼요.

kubectl apply -f https://developer.konghq.com/manifests/kic/echo-service.yaml -n kong

{: data-test-prereq="block" }

서비스들의 pod이 준비될 때까지 기다리세요:

kubectl wait --for=condition=Ready pod --all -n kong --timeout=300s

{: data-test-prereq="block" }

손상된 객체 백필하기

Fallback Configuration은 손상된 객체를 마지막 유효 버전으로 백필하는 기능을 지원해요. 이를 시연하기 위해 기본 모드와 동일한 설정을 사용하되, 이번에는 CONTROLLER_USE_LAST_VALID_CONFIG_FOR_FALLBACK 환경 변수를 true로 설정한 상태로 테스트해 볼 거예요.

플러그인 구성하기

fallback configuration이 어떻게 동작하는지 시연하려면 이 가이드에 세 개의 플러그인이 필요해요.

  1. 예제에서 Consumer를 사용하기 때문에, 들어오는 요청을 식별하기 위한 인증 플러그인을 만들어야 해요:

    echo "
    apiVersion: configuration.konghq.com/v1
    kind: KongPlugin
    metadata:
      name: key-auth
      namespace: kong
      annotations:
        kubernetes.io/ingress.class: kong
    plugin: key-auth
    " | kubectl apply -f -
    
  2. 식별되지 않은 트래픽에는 초당 요청 1개라는 기본 rate limit이 적용돼요:

    echo "
    apiVersion: configuration.konghq.com/v1
    kind: KongPlugin
    metadata:
      name: rate-limit-base
      namespace: kong
      annotations:
        kubernetes.io/ingress.class: kong
    plugin: rate-limiting
    config:
      second: 1
      policy: local
    " | kubectl apply -f -
    
  3. 식별된 Consumer에는 초당 요청 5개라는 rate limit이 적용돼요:

    echo "
    apiVersion: configuration.konghq.com/v1
    kind: KongPlugin
    metadata:
      name: rate-limit-consumer
      namespace: kong
      annotations:
        kubernetes.io/ingress.class: kong
    plugin: rate-limiting
    config:
      second: 5
      policy: local
    " | kubectl apply -f -
    

Route 생성하기

테스트를 위해 두 개의 Route를 만들어 봐요:

  • route-a에는 플러그인이 연결되어 있지 않아요
  • route-b에는 위에서 만든 세 개의 플러그인이 연결되어 있어요

Gateway API

echo "
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: route-a
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  parentRefs:
  - name: kong
    namespace: kong
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: '/route-a'
    backendRefs:
    - name: echo
      kind: Service
      port: 1027
" | kubectl apply -f -

{: data-test-step="block" }

Ingress

echo "
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: route-a
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  ingressClassName: kong
  rules:
  - http:
      paths:
      - path: '/route-a'
        pathType: ImplementationSpecific
        backend:
          service:
            name: echo
            port:
              number: 1027
" | kubectl apply -f -

Gateway API

echo "
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: route-b
  namespace: kong
  annotations:
    konghq.com/plugins: key-auth,rate-limit-base,rate-limit-consumer
    konghq.com/strip-path: 'true'
spec:
  parentRefs:
  - name: kong
    namespace: kong
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: '/route-b'
    backendRefs:
    - name: echo
      kind: Service
      port: 1027
" | kubectl apply -f -

{: data-test-step="block" }

Ingress

echo "
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: route-b
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  ingressClassName: kong
  rules:
  - http:
      paths:
      - path: '/route-b'
        pathType: ImplementationSpecific
        backend:
          service:
            name: echo
            port:
              number: 1027
" | kubectl apply -f -

Consumer 생성하기

마지막으로, credential을 포함하는 KongConsumer를 만들고 rate-limit-consumer KongPlugin을 연결해 봐요.

key-auth credential을 담고 있는 Secret을 만드세요:

echo 'apiVersion: v1
kind: Secret
metadata:
  name: bob-key-auth
  namespace: kong
  labels:
    konghq.com/credential: key-auth
stringData:
  key: bob-password
' | kubectl apply -f -

그런 다음 이 Secret을 참조하는 KongConsumer를 만드세요:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongConsumer
metadata:
  name: bob
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
    konghq.com/plugins: rate-limit-consumer
username: bob
credentials:
- bob-key-auth
" | kubectl apply -f -

Route 검증하기

이 시점에서 Route가 기대한 대로 동작하는지 검증할 수 있어요.

Route A

route-a는 인증 없이 접근할 수 있고 HTTP 200을 반환해요:

Konnect 배포

curl "$PROXY_IP/route-a" \
     --no-progress-meter --fail-with-body 

온프레미스 배포

curl "$PROXY_IP/route-a" \
     --no-progress-meter --fail-with-body 

결과는 다음과 같아야 해요:

Welcome, you are connected to node orbstack.
Running on Pod echo-74c66b778-szf8f.
In namespace default.
With IP address 192.168.194.13.

{:.no-copy-code}

Route B

route-b에 유효한 apikey 헤더를 포함한 인증된 요청은 수락돼야 해요:

Konnect 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body  \
     -H "apikey:bob-password"

온프레미스 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body  \
     -H "apikey:bob-password"

결과는 다음과 같아야 해요:

Welcome, you are connected to node orbstack.
Running on Pod echo-74c66b778-szf8f.
In namespace default.
With IP address 192.168.194.13.

{:.no-copy-code}

apikey 헤더가 없는 요청은 거부돼야 해요:

Konnect 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body 

온프레미스 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body 

결과는 다음과 같이 보여야 해요:

{
  "message":"No API key found in request",
  "request_id":"520c396c6c32b0400f7c33531b7f9b2c"
}

{:.no-copy-code}

라우트 깨뜨리기

두 HTTPRoute가 모두 정상 동작하는 것을 확인했으니, 이제 KongConsumer에서 rate-limit-consumer KongPlugin을 제거해서 route-b를 다시 깨뜨려 봐요:

kubectl annotate -n kong kongconsumer bob konghq.com/plugins-

깨진 라우트가 백필되었는지 확인하기

깨진 HTTPRoute를 마지막 유효 버전으로 백필했으므로, 라우트는 마지막 유효한 동작 상태로 복원되었을 거예요. 즉, breaking change 이전과 같이 route-b에 접근할 수 있어야 해요:

Konnect 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body 

온프레미스 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body 

결과는 다음과 같이 보여야 해요:

{
  "message":"No API key found in request",
  "request_id":"4604f84de6ed0b1a9357e935da5cea2c"
}

진단 엔드포인트 살펴보기

진단 엔드포인트를 사용하면 이제 설정에서 제외되고 백필된 객체들을 살펴볼 수 있어요:

kubectl port-forward -n kong deploy/kong-controller 10256 &
sleep 0.5; curl localhost:10256/debug/config/fallback | jq

결과는 다음과 같이 보여야 해요:

{
  "status": "triggered",
  "brokenObjects": [
    {
      "group": "configuration.konghq.com",
      "kind": "KongPlugin",
      "namespace": "default",
      "name": "rate-limit-consumer",
      "id": "7167315d-58f5-4aea-8aa5-a9d989f33a49"
    }
  ],
  "excludedObjects": [
    {
      "group": "configuration.konghq.com",
      "kind": "KongPlugin",
      "version": "v1",
      "namespace": "default",
      "name": "rate-limit-consumer",
      "id": "7167315d-58f5-4aea-8aa5-a9d989f33a49",
      "causingObjects": [
        "configuration.konghq.com/KongPlugin:default/rate-limit-consumer"
      ]
    },
    {
      "group": "gateway.networking.k8s.io",
      "kind": "HTTPRoute",
      "version": "v1",
      "namespace": "default",
      "name": "route-b",
      "id": "fc82aa3d-512c-42f2-b7c3-e6f0069fcc94",
      "causingObjects": [
        "configuration.konghq.com/KongPlugin:default/rate-limit-consumer"
      ]
    }
  ],
  "backfilledObjects": [
    {
      "group": "configuration.konghq.com",
      "kind": "KongPlugin",
      "version": "v1",
      "namespace": "default",
      "name": "rate-limit-consumer",
      "id": "7167315d-58f5-4aea-8aa5-a9d989f33a49",
      "causingObjects": [
        "configuration.konghq.com/KongPlugin:default/rate-limit-consumer"
      ]
    },
    {
      "group": "configuration.konghq.com",
      "kind": "KongConsumer",
      "version": "v1",
      "namespace": "default",
      "name": "bob",
      "id": "deecb7c5-a3f6-4b88-a875-0e1715baa7c3",
      "causingObjects": [
        "configuration.konghq.com/KongPlugin:default/rate-limit-consumer"
      ]
    },
    {
      "group": "gateway.networking.k8s.io",
      "kind": "HTTPRoute",
      "version": "v1",
      "namespace": "default",
      "name": "route-b",
      "id": "fc82aa3d-512c-42f2-b7c3-e6f0069fcc94",
      "causingObjects": [
        "configuration.konghq.com/KongPlugin:default/rate-limit-consumer",
        "gateway.networking.k8s.io/HTTPRoute:default/route-b"
      ]
    }
  ]
}

{:.no-copy-code}

Kong Gateway가 rate-limit-consumer와 route-b를 깨진 상태로 보고했기 때문에, 이 객체들은 설정에서 제외되었어요. 하지만 Fallback Configuration 메커니즘이 마지막 유효 버전으로 이들을 백필해서 라우트를 동작 상태로 복원했어요. KongConsumer도 함께 백필된 것을 눈치챘을 수도 있어요. 이는 마지막 유효 상태에서 KongConsumer가 rate-limit-consumer 플러그인에 의존하고 있었기 때문이에요.

참고: Fallback Configuration 메커니즘은 깨진 모든 객체와 그 객체들의 직접 및 간접 의존 객체를 함께 백필하려고 시도해요. 의존성은 마지막 유효한 Kubernetes 객체의 캐시 상태를 기준으로 해석돼요.

영향을 받은 객체 수정하기

이제 깨진 객체와 그 의존 객체들의 마지막 유효 버전에 의존하고 있기 때문에, 문제를 해결하기 전까지는 이들을 효과적으로 수정할 수 없어요. bob KongConsumer에 키를 하나 더 추가해 봐요.

새 키가 담긴 새 Secret을 만들어요:

echo 'apiVersion: v1
kind: Secret
metadata:
  name: bob-key-auth-new
  namespace: kong
  labels:
    konghq.com/credential: key-auth
stringData:
  key: bob-new-password' | kubectl apply -f -

새 Secret을 KongConsumer와 연결해요:

kubectl patch -n kong kongconsumer bob --type merge -p '{"credentials":["bob-key-auth", "bob-key-auth-new"]}'

HTTPRoute와 KongPlugin이 아직 깨져 있어서 이 변경은 적용되지 않아요. 새 키로 route-b에 접근을 시도해서 이를 확인해 볼 수 있어요:

Konnect 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body  \
     -H "apikey:bob-new-password"

온프레미스 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body  \
     -H "apikey:bob-new-password"

결과는 다음과 같이 보여야 해요:

{
  "message":"Unauthorized",
  "request_id":"4c706c7e4e06140e56453b22e169df0a"
}

정상 동작하는 라우트 수정하기

반면에, 정상 동작하는 HTTPRoute는 여전히 수정할 수 있어요:

kubectl patch -n kong httproute route-a --type merge -p '{"spec":{"rules":[{"matches":[{"path":{"type":"PathPrefix","value":"/route-a-modified"}}],"backendRefs":[{"name":"echo","port":1027}]}]}}'

업데이트된 HTTPRoute를 확인해 봐요:

Konnect 배포

curl "$PROXY_IP/route-a-modified" \
     --no-progress-meter --fail-with-body 

온프레미스 배포

curl "$PROXY_IP/route-a-modified" \
     --no-progress-meter --fail-with-body 

결과는 다음과 같이 보여야 해요:

Welcome, you are connected to node orbstack.
Running on Pod echo-bf9d56995-r8c86.
In namespace default.
With IP address 192.168.194.8.

{:.no-copy-code}

깨진 라우트 수정하기

깨진 HTTPRoute를 고치려면 rate-limit-consumer KongPlugin을 다시 KongConsumer와 연결해야 해요:

kubectl annotate -n kong kongconsumer bob konghq.com/plugins=rate-limit-consumer

이러면 bob-key-auth Secret에 가했던 변경이 막힘없이 적용될 거예요. 새 키로 route-b에 접근해서 확인해 봐요:

Konnect 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body  \
     -H "apikey:bob-new-password"

온프레미스 배포

curl "$PROXY_IP/route-b" \
     --no-progress-meter --fail-with-body  \
     -H "apikey:bob-new-password"

이제 결과는 다음과 같이 보여야 해요:

Welcome, you are connected to node orbstack.
Running on Pod echo-bf9d56995-r8c86.
In namespace default.
With IP address 192.168.194.8.

{:.no-copy-code}

정리

생성한 Kubernetes 리소스 삭제하기

kubectl delete -n kong -f https://developer.konghq.com/manifests/kic/echo-service.yaml

클러스터에서 KIC 제거하기

helm uninstall kong -n kong

관련 리소스

더 알아보기 (Learn more)

  • Fallback 구성 기능의 개념과 동작 방식을 전체적으로 설명하는 개요 문서예요 — Fallback configuration overview
  • 백필 대상에서 제외할 손상된 구성을 지정하는 방법을 다루는 문서예요 — Exclude broken configuration
  • 이 튜토리얼에서 직접 만들어 사용하는 Consumer 엔티티의 상세 스펙을 확인할 수 있어요 — Consumer