297-298. JSON PATH - Prerequisites

JSONPath가 왜 필요한가?

“kubectl의 기본 출력만으론 원하는 정보만 뽑아내기 어렵기 때문”

상황 예시:

  • “노드 이름과 Internal IP만 깔끔히 표로 보고 싶다”
  • “Running 상태 Pod 개수만 세고 싶다”
  • “재시작이 가장 많은 Pod를 찾아라” (시험 단골)
  • “PVC의 용량별로 정렬”

기본 kubectl get -o wide로는 한계. -o json | jq로 파싱할 수도 있지만 jq가 시험 환경에 없을 수 있음.

JSONPath는 kubectl 자체에 내장되어 있어서:

  • -o jsonpath='...' — 원하는 필드만 추출
  • -o custom-columns=... — 테이블로 출력
  • --sort-by=... — 특정 필드로 정렬
  • --field-selector — 서버 측에서 필터링

시험에서는 jsonpath + custom-columns + sort-by 조합이 자주 나옴.

JSON PATH 기본 문법

표현식의미
$루트 요소
.자식 요소
[0]배열 첫 번째 요소
[-1]배열 마지막 요소
[0:3]배열 슬라이싱 (0~2)
[*]배열 모든 요소
?(@.key == "val")필터 조건
# 예시 JSON
{
  "car": {
    "color": "blue",
    "price": "$20,000"
  },
  "bus": {
    "color": "white",
    "price": "$120,000"
  }
}
 
# 쿼리 예시
$.car.color          # → "blue"
$.bus.price          # → "$120,000"

배열 쿼리

# JSON
{
  "vehicles": [
    {"model": "Tesla", "color": "red"},
    {"model": "BMW",   "color": "blue"},
    {"model": "Audi",  "color": "silver"}
  ]
}
 
$.vehicles[0].model       # → "Tesla"
$.vehicles[-1].color      # → "silver"
$.vehicles[*].model       # → ["Tesla", "BMW", "Audi"]
$.vehicles[?(@.color == "blue")].model  # → ["BMW"]

299. JSON PATH in Kubernetes

kubectl -o jsonpath 기본 사용

# Pod 이름 출력
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
 
# 노드 이름 출력
kubectl get nodes -o jsonpath='{.items[*].metadata.name}'
 
# 여러 필드 동시 출력
kubectl get nodes -o jsonpath='{.items[*].metadata.name}{"\t"}{.items[*].status.capacity.cpu}'
 
# 줄바꿈 포함 출력
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.capacity.cpu}{"\n"}{end}'

range로 반복 출력

# 모든 노드의 이름과 CPU 출력
kubectl get nodes -o jsonpath='{range .items[*]}
Name: {.metadata.name}
CPU:  {.status.capacity.cpu}
{end}'

특정 값 필터링

# Running 상태의 파드 이름만 출력
kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
 
# 특정 노드의 파드 목록
kubectl get pods -o jsonpath='{.items[?(@.spec.nodeName=="node01")].metadata.name}'
 
# 이미지 이름 목록
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'

custom-columns

# 커스텀 컬럼으로 테이블 출력
kubectl get nodes -o custom-columns=\
NAME:.metadata.name,\
CPU:.status.capacity.cpu,\
MEMORY:.status.capacity.memory
 
# 출력 예시:
# NAME      CPU   MEMORY
# master    2     2048Mi
# node01    1     1024Mi

300. Lab - Advanced kubectl Commands

정렬

# 이름순 정렬
kubectl get pods --sort-by=.metadata.name
 
# 생성 시간 역순 정렬 (최신 것이 위)
kubectl get pods --sort-by=.metadata.creationTimestamp
 
# 노드를 CPU 용량 기준 정렬
kubectl get nodes --sort-by=.status.capacity.cpu

유용한 출력 조합

# 모든 네임스페이스의 파드, 노드별로 보기
kubectl get pods -A -o wide
 
# 파드의 이미지 정보만 추출
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[0].image}{"\n"}{end}'
 
# 모든 파드의 상태를 컬럼으로 출력
kubectl get pods -o custom-columns=\
POD:.metadata.name,\
STATUS:.status.phase,\
NODE:.spec.nodeName
 
# 특정 라벨 파드의 IP만 추출
kubectl get pods -l app=nginx -o jsonpath='{.items[*].status.podIP}'
 
# PersistentVolume을 용량 기준 정렬
kubectl get pv --sort-by=.spec.capacity.storage

kubectl explain - 시험의 숨은 치트키

“YAML 필드가 헷갈릴 때 공식 문서 대신 터미널에서 바로 확인”

시험장에는 인터넷 접속이 제한되어 있어서 쿠버네티스 공식 문서만 열 수 있음. 그보다 빠른 건 kubectl explain.

# ── 리소스 기본 구조 확인 ──────────────────────────────────
kubectl explain pod
kubectl explain deployment
 
# ── 하위 필드까지 추적 ────────────────────────────────────
kubectl explain pod.spec
kubectl explain pod.spec.containers
kubectl explain pod.spec.containers.resources
kubectl explain deployment.spec.strategy
 
# ── 전체 필드 재귀 표시 (YAML 작성 참고용) ─────────────────
kubectl explain pod --recursive | less
kubectl explain deployment.spec.template.spec.containers --recursive
 
# ── API 버전 지정 ─────────────────────────────────────────
kubectl explain ingress --api-version=networking.k8s.io/v1
 
# ── 출력 예시 ─────────────────────────────────────────────
# KIND:     Pod
# VERSION:  v1
# FIELD:    spec <Object>
# DESCRIPTION:
#   Specification of the desired behavior of the pod.
# FIELDS:
#   containers	<[]Object> -required-
#     List of containers...

시험에서 “Probe 설정” 같은 문제가 나오면 kubectl explain pod.spec.containers.livenessProbe --recursive로 모든 옵션 확인 가능.

field-selector 실사용

서버 측에서 필터링되므로 | grep보다 정확하고 빠름.

# ── 상태 기반 ─────────────────────────────────────────────
kubectl get pods --field-selector=status.phase=Running
kubectl get pods --field-selector=status.phase!=Running
kubectl get pods --field-selector=status.phase=Pending
 
# ── 노드 기반 ─────────────────────────────────────────────
kubectl get pods --field-selector=spec.nodeName=worker01
kubectl get pods --field-selector=spec.nodeName!=worker01
 
# ── namespace 제외 ────────────────────────────────────────
kubectl get pods -A --field-selector=metadata.namespace!=kube-system
 
# ── 조합 (AND) ────────────────────────────────────────────
kubectl get pods --field-selector=status.phase=Running,spec.nodeName=worker01
 
# ── 이벤트 필터링 ─────────────────────────────────────────
kubectl get events --field-selector type=Warning
kubectl get events --field-selector involvedObject.kind=Pod

field-selector는 리소스별로 지원하는 필드가 다름. Pod는 spec.nodeName, status.phase, metadata.name, metadata.namespace 정도.

실전 문제 패턴

# 1. 특정 조건 파드 개수 세기
kubectl get pods --field-selector=status.phase=Running | grep -c Running
 
# 2. Deployment의 이미지 이름만 추출
kubectl get deployment my-app -o jsonpath='{.spec.template.spec.containers[0].image}'
 
# 3. 모든 노드의 taints 확인
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.taints}{"\n"}{end}'
 
# 4. 서비스의 ClusterIP 추출
kubectl get svc my-service -o jsonpath='{.spec.clusterIP}'
 
# 5. Secret 값 디코딩
kubectl get secret my-secret -o jsonpath='{.data.password}' | base64 --decode
 
# 6. ConfigMap 전체 데이터 확인
kubectl get configmap my-config -o jsonpath='{.data}'
 
# 7. 노드 레이블 확인
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.labels}{"\n"}{end}'
 
# 8. 특정 네임스페이스의 ServiceAccount 목록
kubectl get sa -n kube-system -o jsonpath='{.items[*].metadata.name}'

kubectl 기타 유용한 옵션

# 변경 사항 실시간 감시
kubectl get pods -w
 
# 리소스 즉시 삭제 (grace period 무시)
kubectl delete pod <name> --force --grace-period=0
 
# 여러 리소스 한 번에 조회
kubectl get pods,svc,deploy
 
# 특정 리소스 전체 YAML 출력
kubectl get pod <name> -o yaml
 
# 이벤트 시간순 정렬
kubectl get events --sort-by=.lastTimestamp
 
# 특정 네임스페이스의 모든 리소스 확인
kubectl get all -n <namespace>
 
# 리소스 사용량 확인 (metrics-server 필요)
kubectl top nodes
kubectl top pods
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory

JSON PATH 빠른 참조

JSONPath 트리 구조:

  • $ (루트) → .items[*]
    • .metadata.name
    • .spec.containers[0].image
    • .status.phase

필터 / 정렬:

  • ?(@.status.phase=='Running') — 조건 필터
  • --sort-by=.metadata.name — 정렬
  • range ... end — 반복