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

Terraform으로 퍼블릭 Dedicated Cloud Gateway 관리형 캐시 플러시하기

원문 보기 위키 갱신

Terraform으로 퍼블릭 Dedicated Cloud Gateway 관리형 캐시 플러시하기 (Flush a public Dedicated Cloud Gateway managed cache using Terraform)

이 문서는 Terraform을 사용해 퍼블릭 Dedicated Cloud Gateway의 AWS 관리형 캐시를 플러시하는 방법을 안내해요. AWS STS로 관리형 캐시에 인증해 FLUSHDB를 실행하는 커스텀 플러그인을 배포하고, 이를 서비스와 라우트로 노출한 뒤 Terraform 출력 URL을 호출해서 플러시를 트리거해요. Konnect 개인 액세스 토큰 설정과 준비된 AWS 관리형 캐시가 필요하고, 플러시 엔드포인트 접근 제한과 적용 시 자동 플러시 설정 같은 권장 구성도 함께 다뤄요

출처: 문서

본문

요약

Terraform을 사용해서 퍼블릭 Dedicated Cloud Gateway AWS 관리형 캐시를 플러시하려면 어떻게 해야 할까요? AWS STS를 통해 관리형 캐시에 인증해서 FLUSHDB를 실행하는 konnect_gateway_custom_plugin_streaming 커스텀 플러그인을 배포해요. 이 플러그인은 konnect_gateway_service와 konnect_gateway_route를 통해 노출되며, Terraform 출력 URL을 호출하면 플러시가 트리거돼요.

사전 준비

Terraform과 Konnect 프로바이더

이 튜토리얼은 Konnect 튜토리얼이며 Konnect 개인 액세스 토큰이 필요해요.

  1. Konnect PAT 페이지를 열고 Generate Token을 선택해서 새 개인 액세스 토큰을 만드세요.

  2. 토큰을 환경 변수로 내보내세요:

    export KONNECT_TOKEN='YOUR_KONNECT_PAT'
    
  3. kong/konnect Terraform 프로바이더를 구성하는 auth.tf 파일을 만드세요. us가 아닌 다른 리전을 사용한다면 server_url을 변경하세요:

    echo '
    terraform {
      required_providers {
        konnect = {
          source  = "kong/konnect"
        }
        konnect-beta = {
          source  = "kong/konnect-beta"
        }
      }
    }
    
    provider "konnect" {
      server_url = "https://us.api.konghq.com"
    }
    
    provider "konnect-beta" {
      server_url            = "https://us.api.konghq.com"
    }
    ' > auth.tf
    
  4. 다음으로, 프로젝트를 초기화하고 프로바이더를 다운로드하세요:

    terraform init
    

프로바이더는 KONNECT_TOKEN 환경 변수가 설정되어 있으면 자동으로 사용해요. 커스텀 인증 토큰을 사용하고 싶다면 provider 블록에서 server_url 옆에 personal_access_token 필드를 설정하세요.

AWS 관리형 캐시

이 튜토리얼에는 라이브 데이터 플레인이 있는, 준비된 상태의 퍼블릭 Dedicated Cloud Gateway 컨트롤 플레인에 연결된 AWS 관리형 캐시가 필요해요.

아직 구성하지 않았다면 Terraform으로 하나 만드세요.

프로바이더 계정 ID를 가져와야 해요. 먼저, /provider-accounts 엔드포인트를 사용해서 Konnect Cloud Gateways API에 GET 요청을 보내세요:

curl -X GET "https://global.api.konghq.com/v2/cloud-gateways/provider-accounts?filter%5Bprovider%5D%5Beq%5D=aws" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN"\
     -H "Accept: application/json"\
     -H "Content-Type: application/json"

출력의 id를 Terraform 변수로 내보내세요:

export TF_VAR_provider_id='YOUR_PROVIDER_ACCOUNT_ID'

출력의 id를 사용하세요. provider_account_id가 아니에요.

지원되는 리전, 가용 영역, CIDR 블록은 프로바이더 계정에 따라 달라져요. availability 엔드포인트에서 AWS가 지원하는 값들을 나열해 보세요:

curl -s -H "Authorization: Bearer $KONNECT_TOKEN" \
  https://global.api.konghq.com/v2/cloud-gateways/availability.json | \
  jq '.providers[] | select(.provider == "aws") | .regions[] | {region, availability_zones, cidr_blocks}'

다음 구성에서는 지원되는 region과 해당 availability_zones, 그리고 지원되는 cidr_blocks 중 하나에 속한 CIDR 서브넷을 사용하세요. 이 구성은 퍼블릭 네트워크, 컨트롤 플레인, 그 네트워크 위의 라이브 데이터 플레인, 그리고 관리형 캐시를 만들어요:

echo '
variable "provider_id" {
  type = string
}

resource "konnect_cloud_gateway_network" "my_cloudgatewaynetwork" {
  name   = "Terraform Network"
  region = "us-east-2"
  availability_zones = [
    "use2-az1",
    "use2-az2",
    "use2-az3"
  ]

  cidr_block      = "10.0.0.0/16"

  cloud_gateway_provider_account_id = var.provider_id
}

resource "konnect_gateway_control_plane" "test_cp" {
  name         = "CGW Control Plane"
  cloud_gateway = true
}

resource "konnect_cloud_gateway_configuration" "test_cp_configuration" {
  control_plane_id  = konnect_gateway_control_plane.test_cp.id
  control_plane_geo = "us"
  api_access        = "public"
  version           = "3.15"
  dataplane_groups = [
    {
      provider                  = "aws"
      region                    = "us-east-2"
      cloud_gateway_network_id  = konnect_cloud_gateway_network.my_cloudgatewaynetwork.id
      autoscale = {
        configuration_data_plane_group_autoscale_autopilot = {
          kind     = "autopilot"
          base_rps = 10
        }
      }
    }
  ]
}

resource "konnect_cloud_gateway_addon" "managed_cache" {
  name = "managed-cache"
  owner = {
    control_plane = {
      control_plane_id  = konnect_gateway_control_plane.test_cp.id
      control_plane_geo = "us"
    }
  }
  config = {
    managed_cache = {
      capacity_config = {
        tiered = {
          tier = "micro"
        }
      }
    }
  }
}

output "control_plane_id" {
  value = konnect_gateway_control_plane.test_cp.id
}
' >> main.tf

Terraform으로 리소스를 생성하세요:

terraform apply -auto-approve

중요: 네트워크가 초기화되는 데 30-40분이 걸릴 수 있고, 그 후 관리형 캐시가 준비되기까지 약 15분이 더 걸려요. 계속 진행하기 전에 네트워크와 관리형 캐시 둘 다 Ready로 표시될 때까지 반드시 기다려야 해요.

사이징 권장 사항이나 전체 워크스루가 필요하면 Dedicated Cloud Gateway 컨트롤 플레인용 AWS 관리형 캐시 구성 또는 Dedicated Cloud Gateway 컨트롤 플레인 그룹용 AWS 관리형 캐시 구성을 참고하세요.

이 how-to는 컨트롤 플레인 엔드포인트를 사용해서 캐시를 플러시하기 때문에, 퍼블릭 네트워크가 있는 Dedicated Cloud Gateway를 위한 거예요.

커스텀 플러그인 업로드하기

이 how-to는 게이트웨이에 flush 엔드포인트를 노출하는 커스텀 Kong 플러그인을 배포해요. 엔드포인트를 호출하면 AWS STS에서 파생된 자격 증명으로 관리형 캐시에 인증한 뒤 FLUSHDB를 실행하므로, 엔지니어링 팀의 개입 없이도 여러분(또는 여러분의 CI/CD 파이프라인)이 캐시를 플러시할 수 있어요.

먼저 커스텀 플러그인을 만들고 설정해요:

  1. 플러그인의 설정 필드를 정의하는 schema.lua 파일을 만들어요.

    echo '
    local typedefs = require "kong.db.schema.typedefs"
    
    return {
      name = "cache-flusher",
      fields = {
        { protocols = typedefs.protocols_http },
        {
          config = {
            type = "record",
            fields = {
            { host = typedefs.host({ default = "127.0.0.1", referenceable = true }) },
            { port = typedefs.port({ default = 6379, referenceable = true }) },
            { username = { type = "string", referenceable = true } },
            { ssl = { type = "boolean", default = true } },
            { server_name = { type = "string", referenceable = true } },
            { cloud_authentication = {
                type = "record",
                fields = {
                  { auth_provider = { type = "string", referenceable = true } },
                  { aws_region = { type = "string", referenceable = true } },
                  { aws_assume_role_arn = { type = "string", referenceable = true } },
                  { aws_cache_name = { type = "string", referenceable = true } },
                }
            }},
          }
          },
        },
      },
    }
    ' > schema.lua
    

    {:.collapsible.wrap}

  2. 관리형 캐시에 인증하고 flush를 실행하는 handler.lua 파일을 만들어요.

    echo '
    local AWS = require "resty.aws"
    local redis = require "resty.redis"
    local aws_config = require "resty.aws.config"
    
    local AWS_DEFAULT_ROLE_SESSION_NAME = "KongElasticacheSession"
    local AWS_global_config = aws_config.global
    local aws = AWS({ region = AWS_global_config.region })
    
    local plugin = {
      PRIORITY = 980,
      VERSION  = "1.0.0",
    }
    
    local function get_aws_auth_token(conf, cloud_auth)
        local cachename = cloud_auth.aws_cache_name
        local name = conf.username
        local region = cloud_auth.aws_region
        local assume_role_arn = cloud_auth.aws_assume_role_arn
    
        local credentials = aws.config.credentials
    
        local sts, err = aws:STS({
            region = region,
            credentials = credentials,
            stsRegionalEndpoints = AWS_global_config.sts_regional_endpoints,
        })
        if not sts then
            return nil, err
        end
    
        local creds = aws:ChainableTemporaryCredentials {
            params = {
                RoleArn = assume_role_arn,
                RoleSessionName = AWS_DEFAULT_ROLE_SESSION_NAME,
            },
            sts = sts,
        }
    
        local cache = aws:ElastiCache({ region = region })
    
        local signer = cache:Signer {
            cachename = cachename,
            username = name,
            is_serverless = false,
            region = region,
            credentials = creds,
        }
    
        local auth_token, token_err = signer:getAuthToken()
        if token_err then
            return nil, token_err
        end
    
        return auth_token
    end
    
    local function get_auth_token(conf)
        local cloud_auth = conf.cloud_authentication
        local provider = cloud_auth.auth_provider
    
        if provider == "aws" then
            return get_aws_auth_token(conf, cloud_auth)
        end
    
        return nil, "cloud provider " .. tostring(provider) .. " not implemented"
    end
    
    function plugin:access(conf)
        kong.log.notice("[cache-flusher] starting cache flush")
    
        -- Connect to Cache
        kong.log.notice("[cache-flusher] connecting to Cache at ", conf.host, ":", conf.port)
    
        local red = redis:new()
        local ok, err = red:connect(conf.host, conf.port, {
            ssl = conf.ssl,
            ssl_verify = conf.ssl,
            server_name = conf.server_name,
        })
        if not ok then
            kong.log.err("[cache-flusher] failed to connect to Cache: ", err)
            return kong.response.error(500, "cache flush failed: Cache connect error")
        end
    
        kong.log.notice("[cache-flusher] connected to Cache, obtaining auth token")
    
        -- Authenticate with STS-derived token
        local auth_token, token_err = get_auth_token(conf)
        if not auth_token then
            kong.log.err("[cache-flusher] failed to obtain auth token: ", token_err)
            return kong.response.error(500, "cache flush failed: auth token error")
        end
    
        kong.log.notice("[cache-flusher] auth token obtained, authenticating with Cache")
    
        local res, auth_err = red:auth(conf.username, auth_token)
        if not res then
            kong.log.err("[cache-flusher] failed to authenticate with Cache: ", auth_err)
            return kong.response.error(500, "cache flush failed: Cache auth error")
        end
    
        kong.log.notice("[cache-flusher] authenticated, flushing Cache")
    
        -- Flush Cache
        local flush_res, flush_err = red:flushdb("ASYNC")
        if not flush_res then
            kong.log.err("[cache-flusher] failed to flush Cache: ", flush_err)
            return kong.response.error(500, "cache flush failed: Cache flushdb error")
        end
    
        kong.log.notice("[cache-flusher] cache flush completed successfully")
    
        return kong.response.exit(200, { message = "[cache-flusher] cache flushed" })
    end
    
    return plugin
    ' > handler.lua
    

    {:.collapsible.wrap}

  3. 이 how-to에서 사용하는 변수를 선언하고, 여러분만 아는 값들은 내보내세요:

    echo '
    variable "control_plane_id" {
      type = string
    }
    
    variable "flush_path" {
      type    = string
      default = "/konnect/managed-cache/flush"
    }
    
    variable "ip_allowlist" {
      type    = list(string)
      default = []
    }
    
    variable "auto_flush" {
      type    = bool
      default = false
    }
    
    variable "proxy_hostname" {
      type = string
    }
    ' > variables.tf
    

    {:.collapsible.wrap} 사전 준비 단계에서 컨트롤 플레인을 만들었다면, Terraform state에서 바로 ID를 가져오세요:

    export TF_VAR_control_plane_id=$(terraform output -raw control_plane_id)
    

    그렇지 않다면, 기존 컨트롤 플레인의 ID를 export하세요:

    export TF_VAR_control_plane_id="your-control-plane-id"
    
  4. 컨트롤 플레인의 Konnect 프록시 호스트명을 조회한 뒤, Terraform 변수로 export하세요:

    CONTROL_PLANE_DETAILS=$(curl -X GET "https://us.api.konghq.com/v2/control-planes/$TF_VAR_control_plane_id" \
         --no-progress-meter --fail-with-body  \
         -H "Authorization: Bearer $KONNECT_TOKEN"
    )
    
  5. 프록시 호스트명을 export하세요:

    PROXY_HOSTNAME=$(echo $CONTROL_PLANE_DETAILS | jq -r '.config.control_plane_endpoint | sub("https://";"") | split(".")[0]')
    export TF_VAR_proxy_hostname="${PROXY_HOSTNAME}.gateways.konggateway.com"
    
  6. 커스텀 플러그인, flush 엔드포인트를 노출하는 Gateway Service와 Route, 그리고 플러그인 인스턴스를 정의하세요:

    echo '
    resource "konnect_gateway_custom_plugin_streaming" "cache_flusher" {
      control_plane_id = var.control_plane_id
      name             = "cache-flusher"
      schema           = file("${path.module}/schema.lua")
      handler          = file("${path.module}/handler.lua")
    }
    
    resource "konnect_gateway_service" "cache_flusher_service" {
      control_plane_id = var.control_plane_id
      name             = "managed-cache-flush-service"
      host             = "127.0.0.1"
      port             = 443
      protocol         = "https"
    }
    
    resource "konnect_gateway_route" "cache_flusher_route" {
      control_plane_id = var.control_plane_id
      service = {
        id = konnect_gateway_service.cache_flusher_service.id
      }
      paths = [var.flush_path]
    }
    
    resource "konnect_gateway_custom_plugin" "cache_flusher_instance" {
      name             = "cache-flusher"
      control_plane_id = var.control_plane_id
      enabled          = true
      service = {
        id = konnect_gateway_service.cache_flusher_service.id
      }
      route = {
        id = konnect_gateway_route.cache_flusher_route.id
      }
      config = {
        "cloud_authentication" : {
          "auth_provider" : "{vault://env/ADDON_MANAGED_CACHE_AUTH_PROVIDER}",
          "aws_assume_role_arn" : "{vault://env/ADDON_MANAGED_CACHE_AWS_ASSUME_ROLE_ARN}",
          "aws_cache_name" : "{vault://env/ADDON_MANAGED_CACHE_AWS_CACHE_NAME}",
          "aws_region" : "{vault://env/ADDON_MANAGED_CACHE_AWS_REGION}"
        },
        "host" : "{vault://env/ADDON_MANAGED_CACHE_HOST}",
        "port" : "{vault://env/ADDON_MANAGED_CACHE_PORT}",
        "server_name" : "{vault://env/ADDON_MANAGED_CACHE_SERVER_NAME}",
        "ssl" : true,
        "username" : "{vault://env/ADDON_MANAGED_CACHE_USERNAME}"
      }
    
      depends_on = [konnect_gateway_custom_plugin_streaming.cache_flusher]
    }
    ' >> main.tf
    

    {:.collapsible.wrap}

    관리형 캐시 애드온이 Ready 상태에 도달하면 Konnect가 {vault://env/ADDON_MANAGED_CACHE_*} 참조를 자동으로 채워 주기 때문에, AWS IAM 자격 증명을 직접 구성할 필요는 없어요.

  7. flush URL을 위한 output을 추가하세요:

    echo '
    output "flush_proxy_url" {
      value = "https://${var.proxy_hostname}${var.flush_path}"
    }
    ' > output.tf
    
  8. 구성을 적용하세요:

    terraform apply -auto-approve
    

    다음과 같은 응답을 받게 돼요:

    Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
    

    {:.no-copy-code}

강력 추천: 접근 제한 및 apply 시 자동 flush

다음 섹션들을 활용해 관리형 캐시 flush 동작을 더 구성하세요.

flush를 트리거할 수 있는 IP 제한하기

flush를 트리거할 수 있는 IP를 제한하고 싶다면, ip_allowlist를 IP 또는 CIDR 목록으로 설정하고 flush 라우트에 스코프된 ip-restriction 플러그인을 추가하세요.

  1. IP Restriction 플러그인을 구성하세요:

    echo '
    resource "konnect_gateway_plugin_ip_restriction" "ip-restriction-plugin" {
      count = length(var.ip_allowlist) > 0 ? 1 : 0
    
      config = {
        allow = var.ip_allowlist
    
        message = "NOT ALLOWED"
        status  = 405
      }
    
      control_plane_id = var.control_plane_id
      enabled          = true
      service = {
        id = konnect_gateway_service.cache_flusher_service.id
      }
      route = {
        id = konnect_gateway_route.cache_flusher_route.id
      }
    }
    ' >> main.tf
    

    {:.collapsible.wrap}

  2. 허용 목록에 넣을 IP들을 export하세요:

    export TF_VAR_ip_allowlist='["203.0.113.0/24"]'
    
  3. Terraform 구성을 적용하세요:

    terraform apply -auto-approve
    

허용 목록에 없는 IP에서 온 요청은 405 응답을 받아요.

terraform apply 시 자동 flush

  1. terraform apply를 실행할 때마다 캐시가 자동으로 flush되길 원한다면, auto_flush를 true로 설정하세요:

    echo '
    resource "terraform_data" "flush_cache" {
      count = var.auto_flush ? 1 : 0
    
      triggers_replace = [timestamp()]
    
      provisioner "local-exec" {
        command = "sleep 10 && curl -sf https://${var.proxy_hostname}${var.flush_path}"
      }
    
      depends_on = [
        konnect_gateway_route.cache_flusher_route,
        konnect_gateway_custom_plugin.cache_flusher_instance,
        konnect_gateway_plugin_ip_restriction.ip-restriction-plugin,
      ]
    }
    ' >> main.tf
    

    {:.collapsible.wrap}

  2. 자동 flush 동작을 export하세요:

    export TF_VAR_auto_flush=true
    
  3. Terraform 구성을 적용하세요:

    terraform apply -auto-approve
    

auto_flush가 true이면 첫 번째뿐만 아니라 모든 terraform apply가 캐시 flush를 트리거해요. 이후 apply에서도 terraform_data.flush_cache 리소스가 삭제됐다가 다시 생성되는 과정이 표시돼요. 이는 예상된 동작이므로 안전하게 무시해도 돼요.

검증

이전 단계에서 Terraform이 출력한 URL을 호출해 flush를 트리거하세요:

curl -sf "$(terraform output -raw flush_proxy_url)"

flush가 성공하면 다음이 반환돼요:

{"message": "[cache-flusher] cache flushed"}

{:.no-copy-code}

정리

flush 엔드포인트 제거하기

flush 엔드포인트와 연관된 모든 리소스를 제거하려면:

terraform destroy

FAQ

  • 프라이빗 Dedicated Cloud Gateway의 managed cache는 어떻게 flush하나요? 이 how-to는 퍼블릭 네트워크가 있는 Dedicated Cloud Gateway를 대상으로 해요. flush 엔드포인트는 컨트롤 플레인 엔드포인트를 통해 접근하기 때문이에요. 프라이빗 네트워크 Dedicated Cloud Gateway는 거쳐 갈 컨트롤 플레인 엔드포인트가 없거든요.

    대신, Dedicated Cloud Gateway의 프라이빗 IP 주소에 할당된 FQDN을 통해 flush 엔드포인트에 접근하세요. 예를 들어 CDN을 통하거나 데이터 플레인 앞에 배치한 노드를 거치거나, 내부/프라이빗 네트워크를 통해 접근할 수 있어요. 클라이언트가 그 FQDN에 도달할 수만 있다면, 이 how-to의 나머지 부분(커스텀 플러그인, Terraform 리소스, flush 호출)도 똑같은 방식으로 적용돼요.

관련 리소스

다음 단계

더 알아보기 (Learn more)