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

Flux Schema CLI로 Kubernetes 매니페스트 검증하기

원문 보기 위키 갱신

flux schema validate 명령은 YAML 매니페스트 파일들이 시작부터 올바른지 잡아내 데 도움을 줘요. 파일이나 디렉터리 단위의 Kubernetes 매니페스트를, 각 문서의 apiVersion과 kind에서 해석한 JSON Schema에 대조해서 검증할 수 있습니다.

출처: 문서

본문

flux schema validate 명령은 하나 이상의 파일 또는 디렉터리의 Kubernetes YAML 매니페스트를, 각 문서의 apiVersion과 kind에서 해석한 JSON Schema에 대조해 검증해요.

예시:

# Validate plain YAML files and build kustomize directories in a tree
flux schema validate ./manifests --skip-missing-schemas

# Validate a Helm chart by piping the rendered output
helm template ./charts/app | flux schema validate --verbose

어떤 문서라도 유효하지 않거나 오류가 있으면 0이 아닌 종료 코드를 반환해요.

Kustomize build

kustomization.yaml, kustomization.yml, 또는 Kustomization을 포함한 디렉터리는 kustomize-controller처럼 kustomize로 빌드되고, 개별 파일 대신 렌더링된 리소스가 검증돼요. 인자로 전달된 kustomization 파일은 해당 디렉터리를 빌드해요:

flux schema validate ./clusters/production --verbose

빌드가 실패하면 kustomize-build-error라는 사유로 유효하지 않은 결과 하나가 생성돼요. kustomize가 컴포넌트를 단독으로는 빌드하지 못하므로 kind: Component 디렉터리도 여기에 포함돼요. 그런 디렉터리는 --skip-file로 제외하면 돼요.

빌드는 kustomize build --load-restrictor=LoadRestrictionsNone과 같은 옵션을 사용해요:

  • 빌드된 디렉터리 밖의 파일을 참조할 수 있어요(예: ../base).
  • 원격 베이스를 가져와요. Git 기반 참조는 PATH에 git이 필요해요.
  • 내장(builtin) 생성기와 변환기가 실행돼요. Exec과 KRM 함수 플러그인은 비활성화돼요.

빌드 결과는 빌드된 디렉터리를 source로 사용해요. 리소스가 파일에서 온 경우 origin에 빌드 디렉터리와 결합된 경로가 들어가요. 원격 파일은 //?ref= 형식을 사용해요.

렌더링된 리소스를 출력하려면 flux schema build를 사용해 주세요.

변수 치환 (Variable substitution)

--envsubst-file을 사용하면 kustomize-controller의 spec.postBuild.substitute처럼, 검증 전에 모든 문서가 치환돼요:

flux schema validate ./clusters/production --envsubst-file .env
  • 변수는 dotenv 파일에서만 가져오며 프로세스 환경에서는 가져오지 않아요. 값은 Flux가 postBuild.substitute 값을 사용하는 것과 같은 방식으로 그대로 사용돼요. 따옴표는 유지되고, $ 참조는 확장되지 않으며, export는 지원되지 않아요. 빈 줄과 # 주석은 건너뛰고, 그 외 유효하지 않은 줄은 오류예요. 빈 파일도 치환을 활성화해요.
  • 정의되지 않은 변수는 빈 문자열이 되고, ${VAR:=default}는 기본값을 설정해요. --envsubst-strict를 쓰면 기본값이 없는 정의되지 않은 변수는 오류가 돼요.
  • 각 리소스는 치환 전에 재직렬화되므로, 주석은 치환되지 않고 따옴표로 묶인 "${VAR}"는 값의 타입을 따라가요. 예를 들어 replicas: "${REPLICAS}"는 정수가 돼요.
  • kustomize.toolkit.fluxcd.io/substitute: disabled로 라벨 또는 annotation 된 리소스는 치환되지 않아요.
  • 형식이 잘못된 표현식은 envsubst-error 사유로 유효하지 않은 결과가 돼요.

플래그 (Flags)

| Flag | Description | | -s, --schema-location | URL or file path for schemas (repeatable, tried in order); default points at the built-in catalog, ecosystem at the CNCF ecosystem catalog. | | --envsubst-file | Path to a dotenv file supplying Flux post-build substitution variables. | | --envsubst-strict | Fail on undefined substitution variables that have no default; requires --envsubst-file. | | --skip-missing-schemas | Skip documents for which no schema can be found. | | --skip-kind | Skip documents matching kind or apiVersion/kind (repeatable). | | --skip-json-path | Strip a JSON Pointer field before validation, optionally scoped: [apiVersion/kind:]/path (repeatable). | | --skip-json-path-if-absent | Skip missing required-field errors for a JSON Pointer field, optionally scoped: [apiVersion/kind:]/path (repeatable). | | --skip-file | Basename glob for files and dirs; skipping a kustomization file, even as an argument, restores per-file validation (repeatable, default: .*). | | --skip-cel-rules | Skip evaluation of x-kubernetes-validations CEL rules. | | --fail-fast | Exit after the first invalid document. | | --concurrent | Number of concurrent workers (default 8). | | --insecure-skip-tls-verify | Disable TLS certificate verification when fetching schemas over HTTPS. | | -v, --verbose | Print a line for every document, including valid and skipped ones. | | -o, --output | Output format, one of text, json, yaml or junit (default: text). | | -d, --output-dir | Output directory where structured report files are written (created if missing). | | --config | Path to a YAML file supplying default values for validate flags (env: FLUX_SCHEMA_CONFIG). |

Schema 위치 (Schema location)

--schema-location을 주지 않으면 validate는 최신 Kubernetes·OpenShift API와 Gateway API의 안정 채널, Flux 생태계 CRD를 포함하는 Flux Schema 카탈로그를 사용해요:

flux schema validate ./manifests

flux schema extract로 생성한 자체 스키마로 검증하려면 --schema-location으로 디렉터리를 전달해 주세요. 단순 경로와 URL은 카탈로그 레이아웃 {{.Group}}/{{.Kind}}_{{.Version}}.json으로 자동 확장돼요:

flux schema validate ./manifests --schema-location ./my-schemas

다른 레이아웃을 쓰려면 .json으로 끝나는 전체 Go 템플릿을 전달해 주세요:

flux schema validate ./manifests \
  --schema-location './schemas/{{.Kind}}-{{.GroupPrefix}}-{{.Version}}.json'

템플릿 변수는 .Group, .GroupPrefix, .Kind, .Version이에요.

--schema-location 플래그는 반복 가능하고, 위치는 순서대로 시도돼요(첫 번째 일치가 이김). 리터럴 값 default를 전달하면 자체 스키마와 함께 Flux Schema 카탈로그를 포함해요:

flux schema validate ./manifests \
  --schema-location default \
  --schema-location ecosystem \
  --schema-location './schemas/{{.Kind}}-{{.GroupPrefix}}-{{.Version}}.json'

리터럴 값 ecosystem은 https://schemas.fluxoperator.dev/catalog/에서 제공되는 CNCF 생태계 카탈로그로 해석돼요. 이 카탈로그는 수백 개 CNCF 프로젝트의 CRD를 포함하며 업스트림 릴리즈에서 매일 다시 빌드돼요.

자체 스키마 카탈로그를 빌드하고 호스팅하는 방법은 커스텀 카탈로그(custom catalogs)를 참고해 주세요.

검증 중에 리소스 루트 metadata는 Kubernetes ObjectMeta로 취급돼요. 축약된 CRD 스키마가 metadata.properties의 일부만 선언하면, Flux Schema가 로드된 스키마를 메모리에서 완성해서 namespace·labels·annotations 같은 표준 필드가 추가 속성(additional properties)으로 실패하지 않게 해요. metadata.name·metadata.generateName 같은 필드에 대한 기존 스키마 제약은 유지돼요. CEL 규칙은 여전히 루트 metadata의 Kubernetes 구조적 스키마 뷰를 사용하며, 거기선 name과 generateName만 암시적으로 보여요.

문서와 필드 건너뛰기

매니페스트를 파이프로 넣고 --skip-kind으로 특정 문서를 건너뛸 수 있어요:

kustomize build . | flux schema validate \
  --skip-kind 'Service' \ # matches any Service kind regardless of apiVersion
  --skip-kind 'source.toolkit.fluxcd.io/v1/ExternalArtifact'

일부 매니페스트에는 적용 시점에 Flux가 제거하는 도구 주입 필드가 있어요(예: SOPS로 암호화된 Secret). --skip-json-path를 사용해 그 필드를 검증에서 제거하면 나머지 문서는 계속 확인돼요:

flux schema validate ./manifests \
  --skip-json-path 'v1/Secret:/sops' \
  --skip-json-path 'Deployment:/sops'

Kyverno나 MutatingAdmissionPolicy 같은 admission 훅이 API 서버 검증 전에 기본값을 추가한다면, Git에서 생략될 수 있는 필수 필드에는 --skip-json-path-if-absent를 사용해 주세요. 누락 필드 오류만 건너뛰고, 필드가 있으면 값은 여전히 스키마와 CEL 규칙에 대해 검증돼요:

flux schema validate ./manifests \
  --skip-json-path-if-absent 'Widget:/spec/replicas'

일치하는 경로가 없으면 해당 문서의 CEL 평가도 건너뛰어요. Flux Schema는 CEL을 실행하기 전에 대역외(out-of-band) admission 기본값을 적용할 수 없기 때문이에요.

출력 (Output)

기본 출력(-o text)은 문서당 한 줄씩 검증 결과를 출력하고 끝에 요약을 보여줘요. 유효한 문서와 건너뛴 문서도 잘못된 문서와 함께 출력하려면 --verbose를 전달해 주세요:

$ flux schema validate ./manifests --verbose

manifests/releases.yaml - helm.toolkit.fluxcd.io/v2/HelmRelease/apps/frontend is invalid: cel violation
  - /spec: Invalid value: either 'chart' or 'chartRef' must be set
manifests/sources.yaml - source.toolkit.fluxcd.io/v1/Bucket/apps/frontend-config is invalid: schema violation
  - /spec: missing property 'bucketName'
  - /spec/interval: got number, want string
  - /spec/secretRef/name: got object, want string
  - /spec: additional properties 'force' not allowed
manifests/sources.yaml - source.toolkit.fluxcd.io/v1/OCIRepository/apps/frontend is invalid: yaml parse error
  - line 10: key "app.kubernetes.io/name" already set in map
manifests/sources.yaml - source.toolkit.fluxcd.io/v1/HelmChart/apps/frontend is valid
manifests/sources.yaml - v1/Secret/apps/auth-sops is skipped: kind skipped
Summary: 5 resources found in 2 files - Valid: 1, Invalid: 3, Skipped: 1

CI 파이프라인과 도구를 위해 -o로 구조화된 출력 형식(json, yaml, junit)을 선택할 수 있어요:

flux schema validate ./manifests -o json

json과 yaml 형식은 report-v1beta1.json이 설명하는 구조화된 검증 보고서를 내보내요. junit 형식은 임의의 CI 시스템이 검증 실패를 테스트 결과로 나타내도록 소비할 수 있는 JUnit XML을 내보내서, CI 인터페이스에서 직접 확인하기 쉽게 해 줘요.

구조화된 보고서는 -d 플래그로 디렉터리에 파일로 내보낼 수도 있어요: -d /report-dir. 디렉터리가 없으면 생성돼요.

예시 JSON 출력:

{
  "apiVersion": "schema.plugin.fluxcd.io/v1beta1",
  "kind": "Report",
  "$schema": "https://raw.githubusercontent.com/fluxcd/flux-schema/main/docs/report-v1beta1.json",
  "report": {
    "reporter": "flux-schema/v0.1.0",
    "timestamp": "2026-05-20T12:00:00Z",
    "summary": {
      "total": 4,
      "valid": 1,
      "invalid": 3,
      "skipped": 0
    },
    "results": [
      {
        "resource": {
          "apiVersion": "v1",
          "kind": "Namespace",
          "name": "apps"
        },
        "source": "apps/staging",
        "origin": "apps/base/namespace.yaml",
        "idx": 1,
        "status": "valid"
      },
      {
        "resource": {
          "apiVersion": "helm.toolkit.fluxcd.io/v2",
          "kind": "HelmRelease",
          "name": "frontend",
          "namespace": "apps"
        },
        "source": "apps/staging",
        "origin": "apps/base/release.yaml",
        "idx": 2,
        "status": "invalid",
        "reason": "cel-violation",
        "violations": [
          {
            "path": "/spec",
            "message": "Invalid value: either 'chart' or 'chartRef' must be set"
          }
        ]
      },
      {
        "resource": {
          "apiVersion": "source.toolkit.fluxcd.io/v1",
          "kind": "OCIRepository",
          "name": "frontend",
          "namespace": "apps"
        },
        "source": "apps/staging",
        "origin": "apps/base/repository.yaml",
        "idx": 3,
        "status": "invalid",
        "reason": "schema-violation",
        "violations": [
          {
            "path": "/spec",
            "message": "additional properties 'force' not allowed"
          },
          {
            "path": "/spec/interval",
            "message": "got number, want string"
          }
        ]
      },
      {
        "resource": {
          "apiVersion": "apps/v1",
          "kind": "Deployment",
          "name": "web",
          "namespace": "apps"
        },
        "source": "apps/staging",
        "origin": "apps/base/deployment.yaml",
        "idx": 4,
        "status": "invalid",
        "reason": "envsubst-error",
        "violations": [
          {
            "message": "variable substitution failed: missing closing brace"
          }
        ]
      }
    ]
  }
}

전체 봉투 형태, reason 열거형, 모든 결과 타입을 다루는 예시는 검증 보고서 참조(validation report reference)를 참고해 주세요. 보고서는 게시된 JSON Schema로 버전이 매겨져요.

검증 규칙 (Validation rules)

  • 중복 키가 있는 YAML 문서는 Flux 동작과 일치하게 거부돼요.
  • metadata.name과 metadata.generateName이 모두 없는 문서는 Kubernetes API 동작과 일치하게 유효하지 않다고 표시돼요.
  • metadata.name, generateName, namespace, labels/annotations 키·값은 Kubernetes API 서버의 ObjectMeta 규칙(DNS-1123, qualified names)에 맞게 검사돼요.
  • flux schema extract crd가 생성한 스키마는 additionalProperties: false로 객체를 닫으므로, spec 아래에 문서화되지 않은 필드는 검증에 실패해요.
  • 임베디드 리소스와 목록 토폴로지에 대해 Kubernetes admission 확장이 강제돼요: x-kubernetes-embedded-resource는 중첩된 apiVersion, kind, metadata를 검증하고, x-kubernetes-list-type: map|set은 map 목록에 x-kubernetes-list-map-keys를 사용해 중복 목록 항목을 거부해요.
  • 문자열 형식 duration, date, datetime/date-time, time은 Kubernetes OpenAPI 규약에 맞게 검증돼요.

CEL 검증 규칙 (CEL validation rules)

기본적으로 validate 명령은 스키마에서 x-kubernetes-validations 규칙을 추출해서 Kubernetes API와 같은 엔진으로 CEL 표현식으로 평가해요.

CEL 평가는 JSON Schema 검증이 통과한 뒤에만 실행되고, 규칙 위반은 cel-violation 사유로 보고돼요. 규칙을 평가하기 전에 flux-schema는 kube-apiserver 순서와 일치하게 스키마의 구조적 기본값을 메모리에서 적용해요. oldSelf를 참조하는 전환 규칙은 이전 상태 없이 평가되는데, 이는 Kubernetes API의 CREATE 동작과 일치해요.

CEL 검증은 --skip-cel-rules 플래그로 비활성화할 수 있어요.

설정 파일 (Config file)

플래그 값을 YAML 설정 파일에 미리 설정하고 --config나 FLUX_SCHEMA_CONFIG 환경 변수로 참조할 수 있어요. 이렇게 하면 긴 호출을 CI 스크립트 밖으로 옮기고, 다양한 환경에서 검증을 재현 가능하게 만들 수 있어요.

flux schema validate ./manifests --config .fluxschema.yml

파일은 Config API 봉투로 감싸지고, 검증 기본값을 위한 validate 섹션이 있어요. 형태는 Config JSON Schema로 문서화돼요.

apiVersion: schema.plugin.fluxcd.io/v1beta1
kind: Config
validate:
  envsubst:
    file: .env
    strict: true
  schemaLocation:
    - default
    - ecosystem
  skipKind:
    - source.toolkit.fluxcd.io/v1/ExternalArtifact
  skipJSONPath:
    - Secret:/sops
  skipJSONPathIfAbsent:
    - Widget:/spec/replicas
  skipFile:
    - '.*'
    - kustomization.yaml
  skipCELRules: false
  skipMissingSchemas: false
  verbose: true
  failFast: false
  concurrent: 8
  insecureSkipTLSVerify: false
  output: text

규칙:

  • CLI 플래그가 설정 값을 덮어써요. --verbose=false를 설정하면 파일의 verbose: true보다 우선해요.
  • 상대 envsubst.file 경로는 설정 파일의 디렉터리 기준으로 해석돼요. CLI --envsubst-file 경로는 작업 디렉터리 기준이며, --envsubst-file=""은 설정이 제공한 값을 비활성화해요.
  • --config를 설정하면 FLUX_SCHEMA_CONFIG를 덮어써요. 둘 다 설정되면 플래그가 이기고 환경 변수는 무시돼요.
  • 매니페스트 경로는 위치 인자로 남아요. 설정 파일은 검증 방식을 구성할 뿐, 경로는 명령줄에 주어요.

CI에서 실행하기 (Running in CI)

GitHub Actions

validate action 참조를 참고해 주세요.

Docker

ghcr.io/fluxcd/flux-schema 이미지는 기본 카탈로그를 /catalog/latest/에 넣어 두므로, GitHub에서 스키마를 가져오지 않고도 오프라인에서 매니페스트를 검증할 수 있어요.

매니페스트 디렉터리를 마운트하고 --schema-location을 내장 카탈로그로 지정해 주세요:

docker run --rm \
  -v "$PWD/manifests:/manifests:ro" \
  ghcr.io/fluxcd/flux-schema:latest validate /manifests \
  --schema-location /catalog/latest

또는 렌더링된 매니페스트를 stdin으로 컨테이너에 파이프해 주세요(stdin을 열어두는 -i 플래그 참고):

kustomize build ./manifests | docker run --rm -i \
  ghcr.io/fluxcd/flux-schema:latest validate \
  --schema-location /catalog/latest \
  --skip-missing-schemas

참고:

  • 차단된(air-gapped) 환경에서는 default 대신 --schema-location /catalog/latest를 사용해 주세요.
  • 이미지를 릴리즈 태그(예: ghcr.io/fluxcd/flux-schema:v0.3.0)로 고정해 주세요.
  • 자체 스키마 카탈로그를 사용하려면 마운트된 다른 디렉터리로 --schema-location을 반복해 주세요.

더 알아보기 (Learn more)