본문 바로가기
카테고리 없음

Policy-as-Code 통합 전략: Open Policy Agent(OPA) + Gatekeeper + GitOps

by frontier12 2025. 5. 28.

쿠버네티스 보안·거버넌스 자동화


✅ 왜 Policy-as-Code인가?

클라우드 인프라가 커질수록 “규칙 없는 자유”는 오히려 위험합니다.
RBAC만으로는 부족하고, 네이티브 K8s 리소스만으로는 환경·보안·컴플라이언스를 통제하기 어렵습니다.

**Policy-as-Code(PaC)**는 “사람 대신 정책이 자동 감시하고 조치하는 체계”입니다.
특히 **Open Policy Agent (OPA)**와 Gatekeeper는 다음을 해결합니다:
• 누가 어떤 네임스페이스에 어떤 리소스를 배포할 수 있는가?
• PVC는 반드시 storageClass를 명시해야 하는가?
• 서비스는 반드시 특정 레이블을 포함해야 하는가?
• 파드는 privileged 모드를 사용할 수 있는가?



🧱 핵심 구성요소

구성요소 설명
OPA (Open Policy Agent) 선언적 정책을 위한 Rego 언어 기반 엔진
Gatekeeper OPA를 K8s admission webhook으로 연결하는 컨트롤러
ConstraintTemplate 정책 템플릿 (Rego 코드 포함)
Constraint 실제 적용할 정책 인스턴스
Kyverno (선택) OPA 외 K8s 원어민형 대안 PaC 툴




📦 설치 및 기본 구성

kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

설치 후 gatekeeper-system 네임스페이스에 관련 컨트롤러가 배포됩니다.



🛡 기본 정책 예제: 이미지 레지스트리 제한

ConstraintTemplate 정의 (Rego 포함)

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8sallowedrepos
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRepos
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sallowedrepos
        violation[{"msg": msg}] {
          not startswith(input.review.object.spec.containers[_].image, "gcr.io/my-safe-registry")
          msg := "Only gcr.io/my-safe-registry is allowed"
        }

Constraint 생성

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
  name: restrict-image-repo
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]

이제 gcr.io/my-safe-registry 외의 이미지를 사용하는 Pod은 배포 거부됩니다.



🧠 고급 정책 예시: privileged 사용 금지

package k8spsp

violation[{"msg": msg}] {
  input.review.object.spec.containers[_].securityContext.privileged == true
  msg := "Privileged containers are not allowed"
}

이렇게 정의하면 쿠버네티스 PSP(Pod Security Policy)가 없어져도 동일한 보안 수준을 유지할 수 있습니다.



🔁 GitOps 통합 전략

GitOps 흐름
1. GitHub에 모든 ConstraintTemplate / Constraint 정의 커밋
2. ArgoCD / Flux가 이를 감지해 클러스터에 동기화
3. 정책 변경도 PR 리뷰 + 승인 거쳐 배포 (정책 거버넌스 강화)

Git 디렉토리 구조 예시

policies/
├── constraints/
│   └── restrict-image-repo.yaml
├── templates/
│   └── allowed-repos.yaml




📊 정책 감사 및 트러블슈팅

Gatekeeper는 위반 리소스를 자동 추적합니다.

kubectl get constrainttemplates
kubectl get k8sallowedrepos
kubectl get violations

또한 audit 모드를 활성화하면 실시간 거부 없이 감시만 가능 → Soft rollout 가능

spec:
  enforcementAction: dryrun




🔐 Kyverno vs OPA 간단 비교

항목 OPA + Gatekeeper Kyverno
정책 언어 Rego (비직관적) YAML 기반 (직관적)
커뮤니티 CNCF graduated CNCF incubating
커스터마이징 매우 강력 상대적으로 제한
리소스 변형 지원 제한적 가능 (generate/ mutate/ validate)

OPA는 강력하고 확장성이 있지만 학습 비용이 높고,
Kyverno는 Kubernetes 친화적 문법으로 운영이 쉬운 편입니다.

실전에서는 정책 검증 → OPA, 자동 수리(예: label 추가) → Kyverno를 혼합 운영하기도 합니다.



🧩 결론: PaC는 “보안+개발+플랫폼”의 접점이다

Policy-as-Code는 단순한 보안 툴이 아닌
DevSecOps 관점의 코드 기반 인프라 거버넌스의 핵심입니다.
• 모든 보안 규칙은 Git으로 버전 관리
• 배포 전 정책 리뷰 → 변경 이력 추적
• 운영 중 실시간 위반 감지 + 자동 차단
• Drift 없는 규칙 통합 → 재현 가능한 보안 체계

Gatekeeper는 단순 거절이 아니라,
“우리가 배포할 리소스가 조직 정책에 적합한지를 코드로 검증하는 체계”를 가능케 합니다.