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

Konnect Kong Mesh 배포를 Terraform으로 가져오기

원문 보기 위키 갱신

Konnect Kong Mesh 배포를 Terraform으로 가져오기 (Konnect Kong Mesh deployment to Terraform)

이 문서는 이미 운영 중인 Konnect Kong Mesh 배포를 Terraform으로 가져오는 방법을 안내해요. Control Plane이나 Mesh, MeshTrafficPermission 같은 리소스의 이름과 ID를 import 블록에 담는 방법을 예시와 함께 보여줘요. 그리고 Konnect API를 활용해 가져오기 목록을 자동으로 만들어 주는 import.sh 스크립트 사용법도 소개해요. 마지막에는 terraform plan과 terraform apply로 리소스를 실제로 가져오는 흐름까지 확인할 수 있어요

출처: 문서

본문

기존 Konnect Kong Mesh 배포를 Terraform으로 가져오기

기존 Konnect Kong Mesh 배포를 Terraform으로 가져오려면, 각 리소스의 이름과 ID를 Terraform 구성 파일에 추가해야 해요.

아래는 가져오기 방법의 예시예요:

  • Mesh Control Plane
  • another-name이라는 이름의 Mesh
  • allow-all이라는 이름의 MeshTrafficPermission
  • example-with-tags라는 이름의 MeshTrafficPermission
import {
  provider = "konnect-beta"
  to = konnect_mesh_control_plane.my_meshcontrolplane
  id = "c9fd8f76-6460-45fb-9a64-a981d8a512d7"
}

import {
    provider = "konnect-beta"
    to = konnect_mesh.another-name
    id = "{ \"cp_id\": \"c9fd8f76-6460-45fb-9a64-a981d8a512d7\", \"name\": \"another-name\"}"
}

import {
  provider = "konnect-beta"
  to = konnect_mesh_traffic_permission.allow-all
  id = "{ \"cp_id\": \"c9fd8f76-6460-45fb-9a64-a981d8a512d7\", \"mesh\": \"another-name\", \"name\": \"allow-all\" }"
}

import {
  provider = "konnect-beta"
  to = konnect_mesh_traffic_permission.example-with-tags
  id = "{ \"cp_id\": \"c9fd8f76-6460-45fb-9a64-a981d8a512d7\", \"mesh\": \"another-name\", \"name\": \"example-with-tags\" }"
}

리소스의 이름과 ID는 Konnect의 Mesh UI에서 확인할 수 있어요. import 블록의 id 필드는 리소스를 식별하는 데 필요한 정보를 담고 있는 JSON 문자열이에요.

이어서 다음을 실행하세요:

terraform plan -generate-config-out="generated_resources.tf"

그다음 generated_resources.tf 파일을 검토해서 리소스가 올바르게 가져와졌는지 확인하세요. 그 후 terraform apply를 실행하면 리소스를 가져올 수 있어요.

가져오기 프로세스 자동화

가져올 리소스 목록을 손으로 직접 만드는 건 시간이 많이 걸려요. Konnect API를 사용하면 가져오기 목록을 생성할 수 있어요.

import.sh 사용하기

아래는 Mesh Control Plane의 모든 리소스에 대해 가져오기 프로세스를 자동화하는 스크립트예요.

이 스크립트는 Control Plane ID와 리전을 인자로 받고, Konnect API 인증을 위해 $KONNECT_TOKEN 환경 변수를 사용해요. 이 스크립트는 최선을 다해 제공되는 것이므로, 상황에 따라 조정이 필요할 수 있어요.

펼쳐서 import.sh 보기

#!/bin/bash

set -euo pipefail  # Exit on error, undefined variables, and failed pipes

# Ensure script is run with required arguments
if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <cp_id> <region>" >&2
  exit 1
fi

# Capture arguments
CP_ID="$1"
REGION="$2"

# Ensure KONNECT_TOKEN is set
if [ -z "${KONNECT_TOKEN:-}" ]; then
  echo "Error: KONNECT_TOKEN environment variable is not set." >&2
  exit 1
fi

# Define API base URL with dynamic cp_id
BASE_URL="https://${REGION}.api.konghq.com/v1/mesh/control-planes/${CP_ID}/api"
AUTH_HEADER="Authorization: Bearer ${KONNECT_TOKEN}"

# Resources that are not mesh-scoped
RESOURCE_TYPES=(
  hostnamegenerators
)

# Resources that are mesh-scoped
MESH_RESOURCE_TYPES=(
  meshexternalservices
  meshmultizoneservices
  meshservices
  meshaccesslogs
  meshcircuitbreakers
  meshfaultinjections
  meshhealthchecks
  meshhttproutes
  meshloadbalancingstrategies
  meshmetrics
  meshpassthroughs
  meshproxypatches
  meshratelimits
  meshretries
  meshtcproutes
  meshtimeouts
  meshtlses
  meshtraces
  meshtrafficpermissions
)

# Print import block for the Control Plane itself
cat <<EOF

import {
  provider = konnect-beta
  to = konnect_mesh_control_plane.my_meshcontrolplane
  id = "${CP_ID}"
}

EOF

# Fetch all meshes first
MESHES=$(curl -s "$BASE_URL/meshes" -H "$AUTH_HEADER" | jq -r '.items[].name' || true)

# Function to convert PascalCase to snake_case
pascal_to_snake() {
  echo "$1" | perl -pe 's/([a-z0-9])([A-Z])/\1_\L\2/g' | tr '[:upper:]' '[:lower:]' | tr -d '\n'
}

# Loop over each non-mesh-scoped resource
for RESOURCE in "${RESOURCE_TYPES[@]}"; do
  OUTPUT=$(curl -s "$BASE_URL/$RESOURCE" -H "$AUTH_HEADER")
  NAMES=()  # Initialize NAMES as an empty array
  NAMES=$(echo "$OUTPUT" | jq -r '.items[].name' || true)
  TYPE=$(echo "$OUTPUT" | jq -r '.items[0].type' || true)
  TYPE_SNAKE=$(pascal_to_snake "$TYPE")

  # Generate and print import blocks
  for NAME in $NAMES; do
    cat <<EOF

import {
  provider = konnect-beta
  to = konnect_mesh_${TYPE_SNAKE}.${NAME}
  id = "{ \"cp_id\": \"${CP_ID}\", \"name\": \"$NAME\" }"
}

EOF
  done
done

# Loop over each mesh
for MESH in $MESHES; do
  # Print mesh import block separately
  cat <<EOF

import {
  provider = konnect-beta
  to = konnect_mesh.${MESH}
  id = "{ \"cp_id\": \"${CP_ID}\", \"name\": \"$MESH\"}"
}

EOF

  # Loop over each mesh-scoped resource type
  for RESOURCE in "${MESH_RESOURCE_TYPES[@]}"; do
    RESOURCES_OUTPUT=$(curl -s "$BASE_URL/meshes/${MESH}/$RESOURCE" -H "$AUTH_HEADER")
    NAMES=()  # Initialize NAMES as an empty array
    NAMES=$(echo "$RESOURCES_OUTPUT" | jq -r '.items[].name' || true)
    TYPE=$(echo "$RESOURCES_OUTPUT" | jq -r '.items[0].type' || true)
    TYPE_SNAKE=$(pascal_to_snake "$TYPE")

    # Generate and print import blocks for mesh-specific resources
    for NAME in $NAMES; do
      cat <<EOF

import {
  provider = konnect-beta
  to = konnect_${TYPE_SNAKE}.${NAME}
  id = "{ \"cp_id\": \"${CP_ID}\", \"mesh\": \"$MESH\", \"name\": \"$NAME\" }"
}

EOF
    done
  done
done

사용 예시:

# Usage: import.sh <Mesh Control Plane ID> <Region>
bash import.sh c9fd8f76-6460-45fb-9a64-a981d8a512d7 us > imports.tf

이제 imports.tf에서 Terraform 매니페스트를 생성할 수 있어요:

terraform plan -generate-config-out="generated_resources.tf"

terraform apply를 실행하기 전에 generated_resources.tf에서 가져온 리소스를 검토하세요.

직접 가져오기 도구 만들기

직접 자동화를 구축하고 싶다면, Kong Mesh API에서 특정 Mesh Control Plane에 있는 특정 타입의 모든 리소스를 나열하는 엔드포인트를 제공해요. 이 엔드포인트를 사용하면 가져오기 프로세스를 자동화할 수 있어요. 아래는 ID가 c9fd8f76-6460-45fb-9a64-a981d8a512d7인 Control Plane에서 another-name이라는 Mesh의 모든 HostnameGenerators를 나열하는 방법의 예시예요:

curl -H "Authorization: Bearer $KONNECT_TOKEN" -s https://us.api.konghq.com/v1/mesh/control-planes/c9fd8f76-6460-45fb-9a64-a981d8a512d7/api/meshes/another-name/hostnamegenerators

다음 단계

Kong Mesh Policy Catalog에서 사용 가능한 모든 정책을 살펴보세요.

관련 리소스

더 알아보기 (Learn more)