Kyverno CLI
Kyverno CLI(Command Line Interface)는 정책과 리소스의 동작을 클러스터에 추가하기 전에 검증하고 테스트하도록 설계된 도구입니다. 기능 상태는 Stable(안정)이며 Kyverno v1.19 기준입니다.
출처: 문서
본문
기능 상태: Stable (안정) • Kyverno v1.19
Kyverno CLI는 리소스에 대한 정책 동작을 클러스터에 추가하기 전에 검증하고 테스트하도록 설계되었습니다.
CLI는 CI/CD 파이프라인에서 리소스를 배포하기 전에 표준을 준수하는지 확인하는 리소스 작성 과정을 지원하는 데 사용할 수 있습니다. 또한 kubectl 플러그인으로도, 독립 실행형(standalone) CLI로도 사용할 수 있습니다.
CLI는 동일한 Kyverno 코드베이스로 구성되어 있지만 용도에 맞게 제작된 바이너리로, 여러 설치 방법을 통해 제공되며 대상 Kubernetes 클러스터에서 Pod으로 실행되는 Kyverno 컨테이너 이미지와는 구별됩니다.
이 페이지에서는 주요 Kyverno CLI 명령을 다룹니다. 다른 명령에 대해서는 Reference 문서를 참고하세요.
kustomize와 함께 사용하기 (Working with kustomize)
kustomize와 함께 Kyverno CLI를 사용할 때는 kubectl에 내장된 버전이 아닌 "standalone(독립 실행형)" 버전을 사용하는 것이 좋습니다.
Homebrew로 설치하기 (Install via Homebrew)
Kyverno CLI는 Homebrew를 통해 formula로도 설치할 수 있습니다.
brew install kyverno
Krew로 설치하기 (Install via Krew)
Krew를 사용해 Kyverno CLI를 설치할 수 있습니다:
# kubectl krew 플러그인 매니저를 사용해 Kyverno CLI 설치
kubectl krew install kyverno
# Kyverno CLI 테스트
kubectl kyverno version
AUR(archlinux)로 설치하기 (Install via AUR)
선호하는 AUR 헬퍼(예: yay)를 통해 Kyverno CLI를 설치할 수 있습니다:
yay -S kyverno-git
GitHub Actions에서 설치하기 (Install in GitHub Actions)
Kyverno CLI는 GitHub Marketplace의 kyverno-cli-installer를 사용해 GitHub Actions에서 설치할 수 있습니다. 자세한 내용은 kyverno-cli-installer를 참고하세요.
수동 바이너리 설치 (Manual Binary Installation)
Kyverno CLI는 release 페이지에서 제공하는 컴파일된 바이너리를 직접 다운로드하여 설치할 수도 있습니다. 아래는 Linux x86_64 시스템에 Kyverno CLI v1.12.0을 설치하는 예시입니다.
curl -LO https://github.com/kyverno/kyverno/releases/download/v1.12.0/kyverno-cli_v1.12.0_linux_x86_64.tar.gz
tar -xvf kyverno-cli_v1.12.0_linux_x86_64.tar.gz
sudo cp kyverno /usr/local/bin/
소스에서 CLI 빌드하기 (Building the CLI from source)
Git 저장소(Go 필요)에서 CLI 바이너리를 빌드할 수도 있습니다.
git clone https://github.com/kyverno/kyverno
cd kyverno
make build-cli
sudo mv ./cmd/cli/kubectl-kyverno/kubectl-kyverno /usr/local/bin/
Apply 명령 (Apply Command)
apply 명령은 주어진 입력 리소스 집합에 대해 하나 이상의 정책을 dry run(예행 검증)하는 데 사용됩니다. 이는 정책을 클러스터에 적용하기 전에 정책의 효과를 판단하는 데 유용합니다. mutate 정책의 경우 apply 명령은 변경(mutate)된 리소스를 출력으로 보여줄 수 있습니다. 입력 리소스는 리소스 매니페스트(하나 또는 여러 개)일 수도 있고 실행 중인 Kubernetes 클러스터에서 가져올 수도 있습니다. apply 명령은 정책과 리소스 모두 URL의 파일을 지원합니다.
리소스에 적용:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml
현재 kubectl 컨텍스트를 기준으로 클러스터의 모든 일치 리소스에 정책 적용:
kyverno apply /path/to/policy.yaml --cluster
리소스는 stdin으로도 전달할 수 있습니다:
kustomize build nginx/overlays/envs/prod/ | kyverno apply /path/to/policy.yaml --resource -
현재 kubectl 컨텍스트를 기준으로 현재 클러스터의 모든 클러스터 정책을 클러스터의 모든 일치 리소스에 적용:
kubectl get clusterpolicies -o yaml | kyverno apply - --cluster
여러 정책을 여러 리소스에 적용:
kyverno apply /path/to/policy1.yaml /path/to/folderFullOfPolicies --resource /path/to/resource1.yaml --resource /path/to/resource2.yaml --cluster
정책 예외(policy exception)를 사용해 정책을 리소스에 적용:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --exception /path/to/exception.yaml
예외를 사용해 여러 정책을 여러 리소스에 적용:
kyverno apply /path/to/policy1.yaml /path/to/folderFullOfPolicies --resource /path/to/resource1.yaml --resource /path/to/resource2.yaml --exception /path/to/exception1.yaml --exception /path/to/exception2.yaml
예외가 제공된 리소스에서 평가되는 방식으로 여러 정책을 여러 리소스에 적용:
kyverno apply /path/to/policy1.yaml /path/to/folderFullOfPolicies --resource /path/to/resource1.yaml --resource /path/to/resource2.yaml --exceptions-with-resources
특정 리소스에 변경(mutate) 정책 적용:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml
applying 1 policy to 1 resource...
mutate policy <policy_name> applied to <resource_name>:<final mutated resource output> applied to
변경된 리소스를 파일로 저장:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml -o newresource.yaml
변경된 리소스를 디렉터리로 저장:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml -o foo/
mutate existing 규칙이 있는 정책을 대상 리소스 그룹에 실행:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --target-resource /path/to/target1.yaml --target-resource /path/to/target2.yaml
Applying 1 policy rule(s) to 1 resource(s)...
mutate policy <policy-name> applied to <trigger-name>:<trigger-resource>
---patched targets:
<patched-target1>
---
<patched-target2>
---
pass: 2, fail: 0, warn: 0, error: 0, skip: 0 applied to
---patched targets:
---
---
pass: 2, fail: 0, warn: 0, error: 0, skip: 0
mutate existing 규칙이 있는 정책을 디렉터리의 대상 리소스에 실행:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --target-resources /path/to/targets/
Applying 1 policy rule(s) to 1 resource(s)...
mutate policy <policy-name> applied to <trigger-name>:<trigger-resource>
---patched targets:
<patched-targets>
pass: 5, fail: 0, warn: 0, error: 0, skip: 0 applied to
---patched targets:
pass: 5, fail: 0, warn: 0, error: 0, skip: 0
--set 또는 -s 플래그를 사용해 값을 전달하면서 변수를 포함하는 정책을 적용합니다. {{request.object}}로 시작하는 변수는 보통 리소스에서 읽히므로 명시적으로 지정할 필요가 없습니다.
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --set <variable1>=<value1>,<variable2>=<value2>=,=
-f 또는 --values-file을 사용하면 변수와 그 값을 담은 파일을 전달하면서 여러 정책을 여러 리소스에 적용할 수 있습니다. 지정할 수 있는 변수 유형에는 AdmissionReview 필드, ConfigMap 컨텍스트 데이터, API 호출 컨텍스트 데이터, Global Context Entries가 포함됩니다.
-u 또는 --userinfo를 사용하면 요청 중에 만들어진 필요한 admission 요청 데이터를 포함하는 선택적인 user_info.yaml 파일을 전달하면서 정책을 적용할 수 있습니다.
참고 (Note): values 파일에 ConfigMap 배열 데이터를 전달할 때는 데이터가 여기에 설명된 대로 JSON 형식이어야 합니다.
kyverno apply /path/to/policy1.yaml /path/to/policy2.yaml --resource /path/to/resource1.yaml --resource /path/to/resource2.yaml -f /path/to/value.yaml --userinfo /path/to/user_info.yaml
가능한 모든 필드가 포함된 value.yaml의 형식:
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: <policy1 name>
rules:
- name: <rule1 name>
values:
<context variable1 in policy1 rule1>: <value>
<context variable2 in policy1 rule1>: <value>
- name: <rule2 name>
values:
<context variable1 in policy1 rule2>: <value>
<context variable2 in policy1 rule2>: <value>
resources:
- name: <resource1 name>
values:
<variable1 in policy1>: <value>
<variable2 in policy1>: <value>
- name: <resource2 name>
values:
<variable1 in policy1>: <value>
<variable2 in policy1>: <value>
namespaceSelector:
- name: <namespace1 name>
labels:
<label key>: <label value>
- name: <namespace2 name>
labels:
<label key>: <label value>
user_info.yaml의 형식:
apiVersion: cli.kyverno.io/v1alpha1
kind: UserInfo
metadata:
name: user-info
clusterRoles:
- admin
userInfo:
username: molybdenum@somecorp.com
예시 (Example)
정책 매니페스트(add_network_policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-networkpolicy
spec:
background: false
rules:
- name: default-deny-ingress
match:
any:
- resources:
kinds:
- Namespace
clusterRoles:
- cluster-admin
generate:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
name: default-deny-ingress
namespace: '{{request.object.metadata.name}}'
synchronize: true
data:
spec:
# Select all pods in the namespace
podSelector: {}
policyTypes:
- Ingress
리소스 매니페스트(required_default_network_policy.yaml):
kind: Namespace
apiVersion: v1
metadata:
name: dev
test
--set 또는 -s 플래그를 사용해 변수를 직접 전달하면서 정책을 리소스에 적용:
kyverno apply /path/to/add_network_policy.yaml --resource /path/to/required_default_network_policy.yaml -s request.object.metadata.name=devtest
--values-file 또는 -f 플래그를 사용해 정책을 리소스에 적용:
변수가 포함된 YAML 파일(value.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: add-networkpolicy
resources:
- name: devtest
values:
request.namespace: devtest
kyverno apply /path/to/add_network_policy.yaml --resource /path/to/required_default_network_policy.yaml -f /path/to/value.yaml
위 정책을 언급된 리소스에 적용하면 다음 출력이 생성됩니다:
Applying 1 policy to 1 resource...
(Total number of result count may vary as the policy is mutated by Kyverno. To check the mutated policy please try with log level 5)
pass: 1, fail: 0, warn: 0, error: 0, skip: 0
요약 개수는 리소스 수에 적용된 규칙 수를 기준으로 합니다.
values 파일은 정책이 적용되는 모든 리소스에 전달할 수 있는 전역 값(global values)도 지원합니다.
value.yaml의 형식:
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: <policy1 name>
resources:
- name: <resource1 name>
values:
<variable1 in policy1>: <value>
<variable2 in policy1>: <value>
- name: <resource2 name>
values:
<variable1 in policy1>: <value>
<variable2 in policy1>: <value>
- name: <policy2 name>
resources:
- name: <resource1 name>
values:
<variable1 in policy2>: <value>
<variable2 in policy2>: <value>
- name: <resource2 name>
values:
<variable1 in policy2>: <value>
<variable2 in policy2>: <value>
globalValues:
<global variable1>: <value>
<global variable2>: <value>
리소스별 값과 전역 값이 같은 변수 이름을 가진 경우, 리소스 값이 전역 값보다 우선합니다. 다음 예시의 test-global-prod Pod을 참고하세요.
예시 (Example)
정책 매니페스트(add_dev_pod.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: cm-globalval-example
spec:
background: false
rules:
- name: validate-mode
match:
any:
- resources:
kinds:
- Pod
validate:
failureAction: Enforce
message: "The value {{ request.mode }} for val1 is not equal to 'dev'."
deny:
conditions:
any:
- key: '{{ request.mode }}'
operator: NotEquals
value: dev
리소스 매니페스트(dev_prod_pod.yaml):
apiVersion: v1
kind: Pod
metadata:
name: test-global-prod
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: v1
kind: Pod
metadata:
name: test-global-dev
spec:
containers:
- name: nginx
image: nginx:1.12
변수가 포함된 YAML 파일(value.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: cm-globalval-example
resources:
- name: test-global-prod
values:
request.mode: prod
globalValues:
request.mode: dev
kyverno apply /path/to/add_dev_pod.yaml --resource /path/to/dev_prod_pod.yaml -f /path/to/value.yaml
test-global-dev Pod은 검증을 통과하고, test-global-prod는 실패합니다.
Namespace 선택기로 정책 적용 (Apply a policy with the Namespace selector)
Namespace 세부 정보가 포함된 파일을 전달하려면 --values-file 또는 -f를 사용하세요. Namespace 선택기에 대해 더 알아보려면 여기를 참고하세요.
kyverno apply /path/to/policy1.yaml /path/to/policy2.yaml --resource /path/to/resource1.yaml --resource /path/to/resource2.yaml -f /path/to/value.yaml
value.yaml의 형식:
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
namespaceSelector:
- name: <namespace1 name>
labels:
<namespace label key>: <namespace label value>
- name: <namespace2 name>
labels:
<namespace label key>: <namespace label value>
예시 (Example)
정책 매니페스트(enforce-pod-name.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: enforce-pod-name
spec:
background: true
rules:
- name: validate-name
match:
any:
- resources:
kinds:
- Pod
namespaceSelector:
matchExpressions:
- key: foo.com/managed-state
operator: In
values:
- managed
validate:
failureAction: Audit
message: 'The Pod must end with -nginx'
pattern:
metadata:
name: '*-nginx'
리소스 매니페스트(nginx.yaml):
kind: Pod
apiVersion: v1
metadata:
name: test-nginx
namespace: test1
spec:
containers:
- name: nginx
image: nginx:latest
Namespace 매니페스트(namespace.yaml):
apiVersion: v1
kind: Namespace
metadata:
name: test1
labels:
foo.com/managed-state: managed
변수가 포함된 YAML 파일(value.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
namespaceSelector:
- name: test1
labels:
foo.com/managed-state: managed
위 정책을 테스트하려면 다음 명령을 사용하세요:
kyverno apply /path/to/enforce-pod-name.yaml --resource /path/to/nginx.yaml -f /path/to/value.yaml
컨텍스트 변수를 사용하는 정책에 리소스 적용 (Apply a resource to a policy which uses a context variable)
컨텍스트 변수가 포함된 파일을 전달하려면 --values-file 또는 -f를 사용하세요.
kyverno apply /path/to/policy1.yaml --resource /path/to/resource1.yaml -f /path/to/value.yaml
policy1.yaml:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: cm-variable-example
annotations:
pod-policies.kyverno.io/autogen-controllers: DaemonSet,Deployment,StatefulSet
spec:
background: false
rules:
- name: example-configmap-lookup
context:
- name: dictionary
configMap:
name: mycmap
namespace: default
match:
any:
- resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
metadata:
labels:
my-environment-name: '{{dictionary.data.env}}'
resource1.yaml:
apiVersion: v1
kind: Pod
metadata:
name: nginx-config-test
spec:
containers:
- image: nginx:latest
name: test-nginx
value.yaml:
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: cm-variable-example
rules:
- name: example-configmap-lookup
values:
dictionary.data.env: dev1
변수를 사용해 전역 컨텍스트 항목을 주입할 수도 있습니다. 다음은 전역 컨텍스트 항목을 주입하는 Values 파일의 예시입니다:
apiVersion: cli.kyverno.io/v1alpha1
kind: Value
metadata:
name: values
globalValues:
request.operation: CREATE
policies:
- name: gctx
rules:
- name: main-deployment-exists
values:
deploymentCount: 1
이 예시에서 request.operation은 전역 값으로 설정되고, deploymentCount는 gctx 정책의 특정 규칙에 대해 설정됩니다.
failureAction이 Audit로 설정된 정책은 --audit-warn 플래그를 사용해 실패 대신 경고를 생성하도록 설정할 수 있습니다. 이 경우 시행(Enforce) 정책이 실패하지 않았다면 0이 아닌 종료 코드가 생성됩니다.
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --audit-warn
또한 apply 명령과 함께 --warn-exit-code 플래그를 사용해 경고가 보고될 때의 종료 코드를 제어할 수 있습니다. 이는 CI/CD 시스템에서 --audit-warn 플래그와 함께 사용해 Audit 정책을 경고로 처리할 때 유용합니다. 실패나 오류가 없지만 경고가 있는 경우 CLI는 정의된 종료 코드로 종료됩니다.
kyverno apply disallow-latest-tag.yaml --resource=echo-test.yaml --audit-warn --warn-exit-code 3
echo $?
3
--warn-exit-code를 --warn-no-pass 플래그와 함께 조합해, 정책을 만족하는 객체가 없을 때 CLI가 경고 코드로 종료하도록 할 수도 있습니다. 이는 정책을 처음 개발할 때나 Kubernetes 매니페스트에 객체가 존재하는지 확인하고자 할 때 유용합니다.
kyverno apply disallow-latest-tag.yaml --resource=empty.yaml --warn-exit-code 3 --warn-no-pass
echo $?
3
정책 리포트 생성하기 (Generating Policy Reports)
정책 리포트는 정책 실행과 위반에 대한 정보를 제공합니다. validate 정책에 대한 정책 리포트를 생성하려면 apply 명령과 함께 --policy-report를 사용하세요. mutate와 generate 정책은 정책 리포트를 트리거하지 않습니다.
정책 리포트는 라이브 클러스터에 대해서도 생성할 수 있습니다. 라이브 클러스터에 대한 정책 리포트를 생성할 때 리소스를 선언하는 -r 플래그는 전역적으로 고유한 것으로 간주됩니다. 그리고 리소스 유형 이름을 지정하는 것(예: 클러스터에 같은 이름의 다른 유형 리소스가 있을 때 Pod/foo)은 지원하지 않습니다. 라이브 클러스터에 대한 정책 리포트를 생성하려면 --policy-report와 함께 --cluster를 사용하세요.
kyverno apply policy.yaml --cluster --policy-report
위 예시는 클러스터의 모든 리소스에 policy.yaml을 적용합니다.
다음은 Kyverno CLI에서 정책 리포트를 생성하는 데 사용할 수 있는 입력 조합입니다.
| Policy | Resource | Cluster | Namespace | Interpretation |
|---|---|---|---|---|
| policy.yaml | -r resource.yaml | false | policy.yaml의 정책을 resource.yaml에 지정된 리소스에 적용 | |
| policy.yaml | -r resourceName | true | policy.yaml의 정책을 클러스터에서 주어진 이름의 리소스에 적용 | |
| policy.yaml | true | policy.yaml의 정책을 클러스터의 모든 리소스에 적용 | ||
| policy.yaml | -r resourceName | true | -n=namespaceName | policy.yaml의 정책을 특정 Namespace에서 주어진 이름의 리소스에 적용 |
| policy.yaml | true | -n=namespaceName | policy.yaml의 정책을 특정 Namespace의 모든 리소스에 적용 |
예시 (Example)
다음 정책과 리소스를 고려해 보세요.
policy.yaml:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-pod-requests-limits
spec:
rules:
- name: validate-resources
match:
any:
- resources:
kinds:
- Pod
validate:
failureAction: Audit
message: 'CPU and memory resource requests and limits are required'
pattern:
spec:
containers:
- resources:
requests:
memory: '?*'
cpu: '?*'
limits:
memory: '?*'
resource1.yaml:
apiVersion: v1
kind: Pod
metadata:
name: nginx1
labels:
env: test
spec:
containers:
- name: nginx
image: nginx
imagePullPolicy: IfNotPresent
resources:
requests:
memory: '64Mi'
cpu: '250m'
limits:
memory: '128Mi'
cpu: '500m'
resource2.yaml:
apiVersion: v1
kind: Pod
metadata:
name: nginx2
labels:
env: test
spec:
containers:
- name: nginx
image: nginx
imagePullPolicy: IfNotPresent
사례 1: 정책 매니페스트를 여러 리소스 매니페스트에 적용
kyverno apply policy.yaml -r resource1.yaml -r resource2.yaml --policy-report
사례 2: 정책 매니페스트를 클러스터의 여러 리소스에 적용
먼저 매니페스트 resource1.yaml과 resource2.yaml을 적용해 리소스를 생성합니다.
kyverno apply policy.yaml -r nginx1 -r nginx2 --cluster --policy-report
사례 3: 정책 매니페스트를 클러스터의 모든 리소스에 적용
kyverno apply policy.yaml --cluster --policy-report
앞서 보여준 policy.yaml의 내용을 고려할 때, 이는 클러스터의 모든 Pod을 대상으로 검증하는 리포트를 생성합니다.
사례 4: 정책 매니페스트를 특정 Namespace 내의 이름별 여러 리소스에 적용
kyverno apply policy.yaml -r nginx1 -r nginx2 --cluster --policy-report -n default
사례 5: 정책 매니페스트를 default Namespace 내의 모든 리소스에 적용
kyverno apply policy.yaml --cluster --policy-report -n default
앞서 보여준 policy.yaml의 내용을 고려할 때, 이는 default Namespace 내의 모든 Pod을 검증하는 리포트를 생성합니다.
언급된 리소스에 policy.yaml을 적용하면 다음 리포트가 생성됩니다:
apiVersion: wgpolicyk8s.io/v1alpha1
kind: ClusterPolicyReport
metadata:
name: clusterpolicyreport
results:
- message: Validation rule 'validate-resources' succeeded.
policy: require-pod-requests-limits
resources:
- apiVersion: v1
kind: Pod
name: nginx1
namespace: default
rule: validate-resources
scored: true
status: pass
- message: 'Validation error: CPU and memory resource requests and limits are required; Validation rule validate-resources failed at path /spec/containers/0/resources/limits/'
policy: require-pod-requests-limits
resources:
- apiVersion: v1
kind: Pod
name: nginx2
namespace: default
rule: validate-resources
scored: true
status: fail
summary:
error: 0
fail: 1
pass: 1
skip: 0
warn: 0
정책 예외 적용하기 (Applying Policy Exceptions)
Policy Exception 매니페스트를 전달하는 -e 또는 --exceptions 플래그를 사용해 정책과 함께 Policy Exceptions를 적용할 수 있습니다.
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --exception /path/to/exception.yaml
예시 (Example)
정책 예외와 함께 정책을 리소스에 적용하는 예입니다.
정책 매니페스트(policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: max-containers
spec:
background: false
rules:
- name: max-two-containers
match:
any:
- resources:
kinds:
- Pod
validate:
failureAction: Enforce
message: 'A maximum of 2 containers are allowed inside a Pod.'
deny:
conditions:
any:
- key: '{{request.object.spec.containers[] | length(@)}}'
operator: GreaterThan
value: 2
Policy Exception 매니페스트(exception.yaml):
apiVersion: kyverno.io/v2
kind: PolicyException
metadata:
name: container-exception
spec:
exceptions:
- policyName: max-containers
ruleNames:
- max-two-containers
- autogen-max-two-containers
match:
any:
- resources:
kinds:
- Pod
- Deployment
conditions:
any:
- key: "{{ request.object.metadata.labels.color || '' }}"
operator: Equals
value: blue
리소스 매니페스트(resource.yaml):
PolicyException에 정의된 특성을 일치하는 아래 Deployment는 규칙 정의를 기술적으로 위반하더라도 생성을 허용합니다.
apiVersion: apps/v1
kind: Deployment
metadata:
name: three-containers-deployment
labels:
app: my-app
color: blue
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
color: blue
spec:
containers:
- name: nginx-container
image: nginx:latest
ports:
- containerPort: 80
- name: redis-container
image: redis:latest
ports:
- containerPort: 6379
- name: busybox-container
image: busybox:latest
command: [ '/bin/sh', '-c', "while true; do echo 'Hello from BusyBox'; sleep 10; done", ]
예외와 함께 위 정책을 리소스에 적용합니다:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --exception /path/to/exception.yaml
다음 출력이 생성됩니다:
Applying 3 policy rule(s) to 1 resource(s) with 1 exception(s)...
pass: 0, fail: 0, warn: 0, error: 0, skip: 1
Kubernetes 정책 유형 적용하기 (Applying K8s Policy Types)
kyverno apply 명령을 사용해 네이티브 Kubernetes 정책과 해당 바인딩을 리소스에 적용할 수 있으며, 클러스터 없이 로컬에서 테스트할 수 있습니다.
ValidatingAdmissionPolicy 적용하기
apply 명령으로 Kubernetes ValidatingAdmissionPolicies를 다음과 같이 리소스에 적용할 수 있습니다:
정책 매니페스트(check-deployment-replicas.yaml):
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: check-deployments-replicas
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['deployments']
validations:
- expression: 'object.spec.replicas <= 3'
message: 'Replicas must be less than or equal 3'
리소스 매니페스트(deployment.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-pass
spec:
replicas: 2
selector:
matchLabels:
app: nginx-pass
template:
metadata:
labels:
app: nginx-pass
spec:
containers:
- name: nginx-server
image: nginx
ValidatingAdmissionPolicy를 리소스에 적용:
kyverno apply /path/to/check-deployment-replicas.yaml --resource /path/to/deployment.yaml
다음 출력이 생성됩니다:
Applying 1 policy rule(s) to 1 resource(s)...
pass: 1, fail: 0, warn: 0, error: 0, skip: 0
아래 예시는 ValidatingAdmissionPolicyBinding을 정책과 함께 클러스터의 모든 리소스에 적용합니다.
정책 매니페스트(check-deployment-replicas.yaml):
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: 'check-deployment-replicas'
spec:
matchConstraints:
resourceRules:
- apiGroups:
- apps
apiVersions:
- v1
operations:
- CREATE
- UPDATE
resources:
- deployments
validations:
- expression: object.spec.replicas <= 5
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: 'check-deployment-replicas-binding'
spec:
policyName: 'check-deployment-replicas'
validationActions: [Deny]
matchResources:
namespaceSelector:
matchLabels:
environment: staging
위 정책은 Deployment 레플리카 수가 5보다 크지 않은지 확인하고, environment: staging 레이블의 Namespace로 제한합니다.
environment: staging 레이블이 있는 Namespace를 생성합니다:
kubectl create ns staging
kubectl label ns staging environment=staging
정책을 위반하는 staging Namespace의 Deployment를 포함해 두 개의 Deployment를 생성합니다:
kubectl create deployment nginx-1 --image=nginx --replicas=6 -n staging
kubectl create deployment nginx-2 --image=nginx --replicas=6
클러스터에서 모든 Deployment를 가져옵니다:
kubectl get deployments -A
NAMESPACE NAME READY UP-TO-DATE AVAILABLE AGE
default nginx-2 6/6 6 6 7m26s
kube-system coredns 2/2 2 2 13m
local-path-storage local-path-provisioner 1/1 1 1 13m
staging nginx-1 6/6 6 6 7m44s
ValidatingAdmissionPolicy를 바인딩과 함께 클러스터의 모든 리소스에 적용:
kyverno apply /path/to/check-deployment-replicas.yaml --cluster --policy-report
다음 출력이 생성됩니다:
Applying 1 policy rule(s) to 4 resource(s)...
----------------------------------------------------------------------
POLICY REPORT:
----------------------------------------------------------------------
apiVersion: wgpolicyk8s.io/v1alpha2
kind: ClusterPolicyReport
metadata:
creationTimestamp: null
name: merged
results:
- message: 'failed expression: object.spec.replicas <= 5'
policy: check-deployment-replicas
resources:
- apiVersion: apps/v1
kind: Deployment
name: nginx-1
namespace: staging
uid: a95d1594-44a7-4c8a-9225-04ac34cb9494
result: fail
scored: true
source: kyverno
timestamp:
nanos: 0
seconds: 1707394871
summary:
error: 0
fail: 1
pass: 0
skip: 0
warn: 0
예상대로 정책은 정책 정의와 바인딩을 모두 일치시키므로 nginx-1에만 적용됩니다.
MutatingAdmissionPolicy
마찬가지로 MutatingAdmissionPolicy를 테스트하여 리소스에 적용할 변경 사항을 미리 볼 수 있습니다. CLI는 최종적으로 변경된(mutated) 리소스를 출력합니다.
예시 1: 기본 변경 (Basic Mutation)
예를 들어 ConfigMap에 레이블을 추가하는 MutatingAdmissionPolicy를 테스트할 수 있습니다.
정책 매니페스트(add-label-to-configmap.yaml):
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: MutatingAdmissionPolicy
metadata:
name: 'add-label-to-configmap'
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE']
resources: ['configmaps']
failurePolicy: Fail
reinvocationPolicy: Never
mutations:
- patchType: 'ApplyConfiguration'
applyConfiguration:
expression: >
object.metadata.?labels["lfx-mentorship"].hasValue() ? Object{} :
Object{
metadata: Object.metadata{
labels: {"lfx-mentorship": "kyverno"}
}
}
리소스 매니페스트(configmap.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: game-demo
labels:
app: game
data:
player_initial_lives: '3'
이제 MutatingAdmissionPolicy를 ConfigMap 리소스에 적용합니다:
kyverno apply /path/to/add-label-to-configmap.yaml --resource /path/to/configmap.yaml
출력은 추가된 레이블이 있는 변경된 ConfigMap을 보여줍니다:
Applying 1 policy rule(s) to 1 resource(s)...
policy add-label-to-configmap applied to default/ConfigMap/game-demo:
apiVersion: v1
data:
player_initial_lives: "3"
kind: ConfigMap
metadata:
labels:
app: game
lfx-mentorship: kyverno
name: game-demo
namespace: default
---
Mutation has been applied successfully.
pass: 1, fail: 0, warn: 0, error: 0, skip: 0
출력은 새로운 lfx-mentorship: kyverno 레이블이 있는 ConfigMap을 보여주며, 변경이 올바르게 적용되었음을 확인합니다.
예시 2: 바인딩과 Namespace 선택기를 사용한 변경 (Mutation with a Binding and Namespace Selector)
정책이 적용될 위치를 제어하는 MutatingAdmissionPolicyBinding을 포함하는 정책도 테스트할 수 있습니다. 이 예시는 namespace 선택기를 사용해 특정 Namespace의 ConfigMap에만 정책을 적용합니다.
이를 하려면 리소스가 속한 Namespace의 레이블을 시뮬레이션하는 values.yaml 파일을 제공해야 합니다.
정책 매니페스트(add-label-to-configmap.yaml):
이 파일은 레이블을 추가하는 정책과 이를 environment: staging 또는 environment: production 레이블의 Namespace로 제한하는 바인딩을 정의합니다.
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: MutatingAdmissionPolicy
metadata:
name: 'add-label-to-configmap'
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE']
resources: ['configmaps']
failurePolicy: Fail
reinvocationPolicy: Never
mutations:
- patchType: 'ApplyConfiguration'
applyConfiguration:
expression: >
object.metadata.?labels["lfx-mentorship"].hasValue() ? Object{} :
Object{
metadata: Object.metadata{
labels: {"lfx-mentorship": "kyverno"}
}
}
---
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: MutatingAdmissionPolicyBinding
metadata:
name: 'add-label-to-configmap-binding'
spec:
policyName: 'add-label-to-configmap'
matchResources:
namespaceSelector:
matchExpressions:
- key: environment
operator: In
values:
- staging
- production
리소스 매니페스트(configmaps.yaml):
이 파일은 서로 다른 Namespace에 있는 세 개의 ConfigMap 리소스를 포함합니다. staging과 production에 있는 것만 변경되어야 합니다.
apiVersion: v1
kind: ConfigMap
metadata:
name: matched-cm-1
namespace: staging
labels:
color: red
data:
player_initial_lives: '3'
---
apiVersion: v1
kind: ConfigMap
metadata:
name: matched-cm-2
namespace: production
labels:
color: red
data:
player_initial_lives: '3'
---
apiVersion: v1
kind: ConfigMap
metadata:
name: unmatched-cm
namespace: testing
labels:
color: blue
data:
player_initial_lives: '3'
Values 파일(values.yaml):
이 파일은 필요한 컨텍스트를 제공합니다. Kyverno CLI에 staging, production, testing Namespace와 연관된 레이블을 알려주어 바인딩의 namespaceSelector를 올바르게 평가할 수 있게 합니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Value
metadata:
name: values
namespaceSelector:
- labels:
environment: staging
name: staging
- labels:
environment: production
name: production
- labels:
environment: testing
name: testing
이제 MutatingAdmissionPolicy와 그 바인딩을 ConfigMap에 적용합니다:
kyverno apply /path/to/add-label-to-configmap.yaml --resource /path/to/configmaps.yaml -f /path/to/values.yaml
출력은 staging과 production Namespace의 변경된 ConfigMap을 보여주고, testing Namespace의 것은 변경되지 않습니다:
Applying 1 policy rule(s) to 3 resource(s)...
policy add-label-to-configmap applied to staging/ConfigMap/matched-cm-1:
apiVersion: v1
data:
player_initial_lives: "3"
kind: ConfigMap
metadata:
labels:
color: red
lfx-mentorship: kyverno
name: matched-cm-1
namespace: staging
---
Mutation has been applied successfully.
policy add-label-to-configmap applied to production/ConfigMap/matched-cm-2:
apiVersion: v1
data:
player_initial_lives: "3"
kind: ConfigMap
metadata:
labels:
color: red
lfx-mentorship: kyverno
name: matched-cm-2
namespace: production
---
Mutation has been applied successfully.
pass: 2, fail: 0, warn: 0, error: 0, skip: 0
ValidatingPolicies 적용하기 (Applying ValidatingPolicies)
이 예시에서는 정책을 준수하는 Deployment 매니페스트와 위반하는 매니페스트 두 개를 대상으로 ValidatingPolicy를 적용합니다.
먼저 어떤 Deployment도 레플리카를 2개 이상 가지지 못하게 하는 ValidatingPolicy를 정의합니다.
정책 매니페스트(check-deployment-replicas.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-deployment-replicas
spec:
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['deployments']
validations:
- expression: 'object.spec.replicas <= 2'
message: 'Deployment replicas must be less than or equal to 2'
리소스 매니페스트(deployments.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: good-deployment
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: bad-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
이제 kyverno apply 명령을 사용해 두 리소스에 대해 정책을 테스트합니다.
kyverno apply /path/to/check-deployment-replicas.yaml --resource /path/to/deployments.yaml --policy-report
다음 출력이 생성됩니다:
apiVersion: openreports.io/v1alpha1
kind: ClusterReport
metadata:
creationTimestamp: null
name: merged
results:
- message: Deployment replicas must be less than or equal 2
policy: check-deployment-replicas
properties:
process: background scan
resources:
- apiVersion: apps/v1
kind: Deployment
name: bad-deployment
namespace: default
result: fail
scored: true
source: KyvernoValidatingPolicy
timestamp:
nanos: 0
seconds: 1752755472
- message: success
policy: check-deployment-replicas
properties:
process: background scan
resources:
- apiVersion: apps/v1
kind: Deployment
name: good-deployment
namespace: default
result: pass
scored: true
source: KyvernoValidatingPolicy
timestamp:
nanos: 0
seconds: 1752755472
source: ""
summary:
error: 0
fail: 1
pass: 1
skip: 0
warn: 0
로컬 YAML 파일을 테스트하는 것 외에도 kyverno apply 명령을 사용해 Kubernetes 클러스터에서 이미 실행 중인 리소스에 대해 정책을 검증할 수 있습니다. --resource 플래그로 리소스 파일을 지정하는 대신 --cluster 플래그를 사용할 수 있습니다.
예를 들어 현재 활성 클러스터의 모든 Deployment 리소스에 대해 check-deployment-replicas 정책을 테스트하려면 다음을 실행합니다:
kyverno apply /path/to/check-deployment-replicas.yaml --cluster --policy-report
많은 고급 정책은 resource.Get()과 같은 Kyverno의 커스텀 CEL 함수를 사용해 클러스터의 다른 리소스 상태를 조회해야 합니다. kyverno apply 명령으로 이러한 정책을 로컬에서 테스트할 때 CLI는 클러스터에 연결해 필요한 리소스를 가져올 수 없으므로 --context-path 플래그를 통해 이러한 리소스를 입력으로 제공해야 합니다.
이 플래그를 사용하면 정책이 참조할 리소스를 지정할 수 있습니다. 그러면 CLI는 이 리소스들을 사용해 정책을 평가합니다.
이 예시는 들어오는 Pod의 이름을 ConfigMap에 저장된 값과 비교해 검증하는 정책을 테스트하는 방법을 보여줍니다.
먼저 resource.Get()을 사용해 policy-cm이라는 ConfigMap을 가져오는 ValidatingPolicy를 정의합니다. 그런 다음 정책은 들어오는 Pod의 이름이 ConfigMap의 data에 있는 name 키와 일치하는지 검증합니다.
정책 매니페스트(check-pod-name-from-configmap.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-pod-name-from-configmap
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['pods']
variables:
# This variable uses a Kyverno CEL function to get a ConfigMap from the cluster.
- name: cm
expression: >-
resource.Get("v1", "configmaps", object.metadata.namespace, "policy-cm")
validations:
# This rule validates that the Pod's name matches the 'name' key in the ConfigMap's data.
- expression: >-
object.metadata.name == variables.cm.data.name
리소스 매니페스트(pods.yaml):
apiVersion: v1
kind: Pod
metadata:
name: good-pod
spec:
containers:
- name: nginx
image: nginx
---
apiVersion: v1
kind: Pod
metadata:
name: bad-pod
spec:
containers:
- name: nginx
image: nginx
CLI는 클러스터에 연결해 policy-cm ConfigMap을 가져올 수 없으므로 컨텍스트 파일에 제공해야 합니다. 이 파일에는 로컬 평가 중 resource.Get()이 사용할 mock ConfigMap이 포함됩니다.
컨텍스트 파일(context.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Context
metadata:
name: context
spec:
# The resources defined here will be available to functions like resource.Get()
resources:
- apiVersion: v1
kind: ConfigMap
metadata:
namespace: default
name: policy-cm
data:
# According to this, the valid pod name is 'good-pod'.
name: good-pod
이제 정책, 리소스, 컨텍스트 파일을 제공하면서 kyverno apply 명령을 실행할 수 있습니다. 결과를 나타내는 ClusterReport를 생성하기 위해 -p(또는 --policy-report) 플래그도 사용합니다.
kyverno apply /path/to/policy.yaml --resource /path/to/pods.yaml --context-file /path/to/context.yaml -p
다음 출력이 생성됩니다:
apiVersion: openreports.io/v1alpha1
kind: ClusterReport
metadata:
creationTimestamp: null
name: merged
results:
- message: success
policy: check-pod-name-from-configmap
properties:
process: background scan
resources:
- apiVersion: v1
kind: Pod
name: good-pod
namespace: default
result: pass
scored: true
source: KyvernoValidatingPolicy
timestamp:
nanos: 0
seconds: 1752756617
- policy: check-pod-name-from-configmap
properties:
process: background scan
resources:
- apiVersion: v1
kind: Pod
name: bad-pod
namespace: default
result: fail
scored: true
source: KyvernoValidatingPolicy
timestamp:
nanos: 0
seconds: 1752756617
source: ''
summary:
error: 0
fail: 1
pass: 1
skip: 0
warn: 0
good-pod 리소스는 이름이 컨텍스트 파일에서 제공한 ConfigMap의 값과 일치하므로 pass 결과가 나왔습니다.
bad-pod리소스는 이름이 일치하지 않으므로 fail 결과가 나왔고, 리포트에는 정책의 검증 오류 메시지가 포함됩니다.
--cluster 플래그를 사용하면 CLI는 활성 Kubernetes 클러스터에 연결하므로 로컬 컨텍스트 파일이 필요 없습니다. resource.Get() 함수는 라이브 ConfigMap을 클러스터에서 직접 가져오므로 명령을 실행하기 전에 ConfigMap과 Pod 리소스가 클러스터에 존재하는지 확인해야 합니다.
kyverno apply /path/to/check-pod-name-from-configmap.yaml --cluster --policy-report
PolicyException을 사용해 ValidatingPolicy를 적용하는 경우 --exception 플래그로 예외 매니페스트를 지정할 수 있습니다. 그러면 CLI가 정책과 예외를 함께 적용합니다.
이 예시에서는 hostPath 볼륨을 금지하는 정책을 테스트하지만, PolicyException을 사용해 특정 Pod에 대한 예외를 만듭니다.
정책 매니페스트(disallow-host-path.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: disallow-host-path
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['pods']
validations:
- expression: '!has(object.spec.volumes) || object.spec.volumes.all(volume, !has(volume.hostPath))'
message: 'HostPath volumes are forbidden. The field spec.volumes[*].hostPath must be unset.'
리소스 매니페스트(pod-with-hostpath.yaml):
apiVersion: v1
kind: Pod
metadata:
name: pod-with-hostpath
spec:
containers:
- name: nginx
image: nginx
volumes:
- name: udev
hostPath:
path: /etc/udev
이제 특정 Pod을 이 정책에서 제외하는 PolicyException을 만듭니다. 예외는 이름으로 Pod을 일치시키고 disallow-host-path 정책을 참조합니다.
Policy Exception 매니페스트(exception.yaml):
apiVersion: policies.kyverno.io/v1
kind: PolicyException
metadata:
name: exempt-hostpath-pod
spec:
policyRefs:
- name: disallow-host-path
kind: ValidatingPolicy
matchConditions:
- name: 'skip-pod-by-name'
expression: "object.metadata.name == 'pod-with-hostpath'"
이제 --exception 플래그를 사용해 정책, 리소스, 예외를 제공하면서 kyverno apply 명령을 사용합니다. 자세한 리포트를 생성하기 위해 -p도 사용합니다.
kyverno apply policy.yaml --resource resource.yaml --exception exception.yaml -p
다음 출력이 생성됩니다:
apiVersion: openreports.io/v1alpha1
kind: ClusterReport
metadata:
creationTimestamp: null
name: merged
results:
- message: 'rule is skipped due to policy exception: exempt-hostpath-pod'
policy: disallow-host-path
properties:
exceptions: exempt-hostpath-pod
process: background scan
resources:
- apiVersion: v1
kind: Pod
name: pod-with-hostpath
namespace: default
result: skip
rule: exception
scored: true
source: KyvernoValidatingPolicy
timestamp:
nanos: 0
seconds: 1752759828
source: ''
summary:
error: 0
fail: 0
pass: 0
skip: 1
warn: 0
출력은 PolicyException이 의도대로 작동했음을 확인합니다:
result: skip: 정책 규칙이 리소스에 시행되지 않았습니다.properties.exceptions: exempt-hostpath-pod: 리포트는 skip의 원인이 된 PolicyException을 명시적으로 지목합니다.summary.skip: 1: 최종 개수는 하나의 규칙이 skip되었음을 반영합니다.
교차 리소스 정책 평가 (오프라인) (Cross-Resource Policy Evaluation (Offline))
context.apiCall을 사용해 형제 Kubernetes 객체를 조회하는 정책(예: "이 Deployment에 대한 PodDisruptionBudget이 존재하는가?")은 이전에는 라이브 API 서버에 도달하기 위해 --cluster 플래그가 필요했습니다. --cluster 없이 실행하면 CLI는 "disabled loading of APICall context entry"를 기록하고 해당 규칙을 완전히 건너뛰어 CI에서 잘못된 pass/fail 개수를 초래했습니다.
Kyverno CLI v1.14부터 --resource로 리소스를 전달하고 --cluster를 사용하지 않으면 CLI가 제공된 매니페스트에서 자동으로 인메모리 dynamic client를 구성하고 해당 스냅샷에 대해 apiCall을 활성화합니다. 이로써 예를 들어 CI에서 클러스터 접근 없이 helm template의 출력 같은 완전한 멀티-도큐먼트 매니페스트를 린트(lint)할 수 있습니다.
동일한 메커니즘은 context.globalReference 항목도 해결합니다. 리소스 스트림에 GlobalContextEntry 객체가 나타나면 CLI는 인메모리 client에서 관련 리소스를 스냅샷하고 이를 context loader factory에 연결하므로, globalReference를 사용하는 정책도 완전히 오프라인으로 검증할 수 있습니다.
참고 (Note):
spec.kubernetesResource소스를 가진 GlobalContextEntry 항목만 이렇게 해결됩니다. 외부 HTTP 서비스를 가리키는 항목은 오프라인 평가 범위를 벗어납니다.
오프라인 apiCall GET
아래 예시는 apiCall 컨텍스트 항목을 사용해 ServiceAccount를 가져와 모든 Deployment에 같은 Namespace의 관련 ServiceAccount가 있는지 확인합니다.
정책 매니페스트(policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: check-serviceaccount
spec:
rules:
- name: sa-must-exist
match:
any:
- resources:
kinds:
- Deployment
context:
- name: sa
apiCall:
urlPath: /api/v1/namespaces/{{request.object.metadata.namespace}}/serviceaccounts/{{request.object.spec.template.spec.serviceAccountName}}
jmesPath: metadata.name
validate:
failureAction: Enforce
message: 'ServiceAccount {{ sa }} referenced by Deployment must exist in the same namespace'
deny:
conditions:
any:
- key: '{{ sa }}'
operator: Equals
value: ''
리소스 매니페스트(resources.yaml) — Deployment와 그 ServiceAccount가 한 파일에 함께 있습니다:
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-sa
namespace: default
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
serviceAccountName: my-sa
containers:
- name: app
image: nginx:stable
오프라인 적용 — 클러스터가 필요 없습니다:
kyverno apply policy.yaml --resource resources.yaml
CLI는 resources.yaml에서 fake client를 만들고 이에 대해 apiCall을 해결하여 다음을 생성합니다:
Applying 1 policy rule(s) to 1 resource(s)...
pass: 1, fail: 0, warn: 0, error: 0, skip: 0
오프라인 apiCall LIST
아래 예시는 issue #8615의 PodDisruptionBudget 패턴을 재현합니다. 모든 Deployment에는 일치하는 PDB가 있어야 합니다.
kyverno apply policy.yaml --resource resources.yaml
PDB가 resources.yaml에 없으면 규칙은 조용히 skip되는 대신 fail로 평가됩니다. "disabled loading of APICall context entry" 경고는 나타나지 않습니다.
오프라인 GlobalContextEntry
GlobalContextEntry를 참조하는 정책은 해당 GlobalContextEntry 객체(그리고 그것이 가리키는 리소스)를 같은 매니페스트에 포함시켜 오프라인으로 평가할 수도 있습니다.
kyverno apply policy.yaml --resource resources.yaml
CLI는 리소스 스트림에서 GlobalContextEntry 객체를 감지하고, 인메모리 client에서 일치하는 리소스를 나열하며 결과를 context loader factory에 연결합니다 — 클러스터나 컨트롤러가 필요 없습니다.
Test 명령 (Test Command)
test 명령은 하나 이상의 정책에 대해 주어진 리소스 집합을 테스트하여, 별도의 테스트 매니페스트 파일에 미리 선언된 기대 결과를 실제 결과와 비교하는 데 사용됩니다. test는 기대 결과가 무엇인지 의도를 정의해 선언하고 싶을 때 유용하며, 이는 결과가 변경될 때 차이를 찾는 데 도움이 됩니다.
test는 Git 저장소나 로컬 폴더일 수 있는 주어진 위치를 스캔하고 그 안에 정의된 테스트를 실행하는 방식으로 동작합니다. 현재 validate, mutate, generate 규칙 유형이 지원됩니다. 명령은 지정된 파일 이름을 가진, 정책 테스트 선언(아래 설명)이 포함된 YAML 파일을 재귀적으로 찾아 해당 테스트를 실행합니다. 같은 테스트에 적용되는 모든 파일은 같은 위치에 있어야 합니다. 디렉터리 재귀가 지원됩니다. test는 auto-gen 기능을 지원하므로 예를 들어 Deployment 리소스를 Pod 정책에 대해 테스트할 수 있습니다.
test는 kyverno-test.yaml이라는 이름의 파일을 검색하고, 찾으면 그 안의 테스트를 실행합니다.
각 테스트에는 네 가지 기대 결과가 있으며 테스트할 수 있습니다. 테스트가 실행된 후의 실제 결과가 테스트 매니페스트에 정의된 기대 결과와 일치하면 명령 출력에서 pass로 채점됩니다. 예를 들어, 정책에 대한 리소스 테스트의 지정된 결과가 pass로 선언되었고 실제 결과도 pass라면 명령 출력은 pass로 표시됩니다. 만약 실제 결과가 skip이었다면 두 결과가 일치하지 않으므로 명령 출력은 fail로 표시됩니다. 다음은 테스트 매니페스트에 지정할 수 있는 기대 결과입니다.
- pass: 리소스가 정책 정의를 통과합니다. deny 문으로 작성된 validate 규칙의 경우 이것은 가능한 결과가 아닙니다. mutate 및 generate 규칙은 pass를 선언할 수 있습니다.
- skip: 리소스가 match 또는 exclude 블록을 충족하지 않거나 precondition 문을 통과하지 못합니다. deny 문으로 작성된 validate 규칙의 경우 이것은 가능한 결과입니다. 규칙에 충족되지 않는 특정 조건부 앵커가 포함되어 있으면 결과가 skip으로 채점될 수도 있습니다.
- fail: 리소스가 정책 정의를 통과하지 못합니다. 일반적으로 pattern 스타일 정책 정의를 가진 validate 규칙에 사용됩니다.
- warn: 리소스나 정책에
policies.kyverno.io/scored주석을"false"로 설정한 경우, 그렇지 않으면 실패했을 항목이 warn으로 간주됩니다.
포괄적인 출력을 보려면 --detailed-results를 사용하세요(기본값 false). test 명령에 대한 도움말은 -h 플래그를 전달하면 사용법, 플래그, 샘플 매니페스트를 포함한 광범위한 출력을 얻을 수 있습니다.
참고 (Note): test 명령을 통한 Kyverno CLI는 Kubernetes control plane 구성 요소를 내장하지 않으므로, in-cluster 생성 흐름의 일부로 리소스에 가해지는 초기 변경 유형을 수행할 수 없습니다. 테스트하는 매니페스트가 이러한 수정 사항을 고려하도록 주의하세요.
테스트 파일 구조 (Test File Structures)
kyverno-test.yaml의 테스트 선언 파일 형식은 다음 형식이어야 합니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test
policies:
- <path/to/policy.yaml>
- <path/to/policy.yaml>
resources:
- <path/to/resource.yaml>
- <path/to/resource.yaml>
targetResources: # optional key for specifying target resources when testing for mutate existing rules
- <path/to/target-resource.yaml>
- <path/to/target-resource.yaml>
exceptions: # optional files for specifying exceptions. See below for an example.
- <path/to/exception.yaml>
- <path/to/exception.yaml>
variables: variables.yaml # optional file for declaring variables. see below for example.
userinfo: user_info.yaml # optional file for declaring admission request information (roles, cluster roles and subjects). see below for example.
context: context.yaml # optional file for declaring context variables. It is used in the new policy types; validatingpolicies, imagevalidationpolicies, mutatingpolicies and generatingpolicies.
apiCallResponses: # optional; inline mock responses for context.apiCall and CEL http.Get()/http.Post() calls (offline testing)
- url: https://example.com/api # URL to match
method: GET # optional HTTP method filter
response:
statusCode: 200
body: {} # arbitrary JSON value (object/array/string/number/bool/null)
globalContextEntries: # optional; inline mock data for GlobalContextEntry references (offline testing)
- name: <globalcontextentry-name>
# Choose exactly ONE of the three mutually exclusive data sources below.
# Option 1: arbitrary JSON root value
# data: {}
# Option 2: inline Kubernetes resource manifests
# resources:
# - apiVersion: apps/v1
# kind: Deployment
# metadata:
# name: <resource-name>
# namespace: <namespace>
# Option 3: YAML file paths relative to the test directory
# resourceFiles:
# - <path/to/resources.yaml>
fieldPath: '' # optional JMESPath to narrow the root (applies to data; not used with resources/resourceFiles)
projections: # optional named JMESPath extractions from the root
- name: <key>
path: <jmespath>
results:
- policy: <name>
테스트 선언은 다음 부분으로 구성됩니다:
- policies 요소: 적용할 하나 이상의 정책을 나열합니다.
- resources 요소: 정책이 적용되는 하나 이상의 리소스를 나열합니다.
- exceptions 요소: 하나 이상의 정책 예외를 나열합니다. ValidatingAdmissionPolicy와 함께 사용할 수 없습니다. 선택적입니다.
- variables 요소: 정책 테스트에 사용하기 위해 변수와 그 값이 저장된 파일을 정의합니다. 정책 내용에 따라 선택적입니다.
- userinfo 요소: subjects와 roles에 대한 admission 요청 데이터를 선언합니다. 정책 내용에 따라 선택적입니다.
- results 요소: 기대 결과를 선언합니다. 테스트되는 규칙 유형에 따라 이 섹션은 달라질 수 있습니다.
- checks 요소: 결과에 대해 평가할 assertion을 선언합니다 (Assertion Trees 사용 참고).
- apiCallResponses 요소:
context.apiCall및 CELhttp.Get()/http.Post()호출에 대한 정적 mock 응답을 선언하여 실제 HTTP 서버 없이 오프라인 테스트를 가능하게 합니다. 선택적입니다. - globalContextEntries 요소: GlobalContextEntry 참조에 대한 mock 데이터를 선언하여
context.globalReference(v1 ClusterPolicy)와globalContext.Get()(CEL ValidatingPolicy) 호출을 모두 오프라인으로 충족시킵니다. 각 항목은 세 가지 상호 배타적 데이터 소스인data(임의의 JSON 값),resources(인라인 Kubernetes 리소스 매니페스트),resourceFiles(테스트 디렉터리 기준 YAML 파일 경로) 중 하나를 지원합니다.resources와resourceFiles옵션은 매니페스트를 실제 Kubernetes 리소스 캐시와 동일한[]interface{}형태로 디코딩하므로, kubernetesResource 기반 GlobalContextEntries를 완전히 오프라인으로 테스트할 수 있습니다. 선택적입니다.
API 호출이나 다른 요소로 만들어진 컨텍스트 변수 같은 외부 데이터 소스의 변수를 전달해야 한다면, apply 명령에서 허용되는 형식과 같은 variables.yaml 파일을 정의할 수 있습니다. 변수가 문자열 배열을 포함해야 한다면 JSON으로 인코딩된 형식이어야 합니다. apply 명령과 마찬가지로 request.object로 시작하는 변수는 리소스에서 가져오므로 보통 variables 파일에 지정할 필요가 없습니다. request.operation이 CREATE와 일치할 때 트리거되는 정책은 variables 파일이 필요 없습니다. request.operation 변수가 정의되지 않은 경우 CLI는 CREATE 값을 가정합니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: exclude-namespaces-example
rules:
- name: exclude-namespaces-dynamically
values:
namespacefilters.data.exclude: asdf
resources:
- name: nonroot-pod
values:
namespacefilters.data.exclude: foo
- name: root-pod
values:
namespacefilters.data.exclude: '["cluster-admin", "cluster-operator", "tenant-admin"]'
variables 파일은 특정 규칙이나 리소스를 이름으로 지정하지 않고도 전역 변수 값을 선택적으로 지정할 수 있어, 같은 변수와 같은 값에 대한 반복을 피할 수 있습니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
globalValues:
request.operation: UPDATE
정책이 namespaceSelector를 사용한다면 변수 파일에 지정할 수도 있습니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
namespaceSelector:
- name: test1
labels:
foo.com/managed-state: managed
roles, cluster roles, subjects 같은 admission 요청 정보를 전달하는 데 사용할 수 있는 user_info.yaml 파일을 선언할 수도 있습니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: UserInfo
metadata:
name: user-info
clusterRoles:
- admin
userInfo:
username: someone@somecorp.com
Kind/Subresource 일치 형식으로 하위 리소스를 테스트하려면 values 파일에 subresources{} 섹션도 필요합니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
subresources:
- subresource:
name: <name of subresource>
kind: <kind of subresource>
group: <group of subresource>
version: <version of subresource>
parentResource:
name: <name of parent resource>
kind: <kind of parent resource>
group: <group of parent resource>
version: <version of parent resource>
하위 리소스를 테스트할 때의 예시입니다:
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
subresources:
- subresource:
name: 'deployments/scale'
kind: 'Scale'
group: 'autoscaling'
version: 'v1'
parentResource:
name: 'deployments'
kind: 'Deployment'
group: 'apps'
version: 'v1'
로컬 파일에 대한 테스트 (Test Against Local Files)
작업 디렉터리의 로컬 파일 집합을 테스트합니다.
kyverno test .
디렉터리를 지정하여 로컬 파일 집합을 테스트합니다.
kyverno test /path/to/folderContainingTestYamls
Git 저장소에 대한 테스트 (Test Against Git Repositories)
repo URL 안에 브랜치 이름을 지정하여 전체 Git 저장소를 테스트합니다. 브랜치가 지정되지 않으면 기본값으로 main이 사용됩니다.
kyverno test https://github.com/kyverno/policies/release-1.6
repo URL 안의 디렉터리와 함께 --git-branch 또는 -b 플래그로 브랜치를 지정하여 저장소의 특정 디렉터리를 테스트합니다. main을 테스트하더라도 repo URL에 디렉터리를 사용할 때는 --git-branch 또는 -b 플래그를 전달해야 합니다.
kyverno test https://github.com/kyverno/policies/pod-security/restricted -b release-1.6
테스트 케이스를 포함하는 커스텀 파일 이름을 설정하려면 -f 플래그를 사용하세요. 기본적으로 test는 kyverno-test.yaml이라는 파일을 검색합니다.
이미지 레지스트리 접근으로 정책 테스트하기 (Testing Policies with Image Registry Access)
컨텍스트 변수를 설정하기 위해 이미지 레지스트리 접근이 필요한 정책의 경우, 해당 변수는 (아래 정의된) variables 파일에서 가져오거나 --registry 플래그를 전달해 "live" 레지스트리에서 가져올 수 있습니다.
리소스 하위 집합 테스트 (Test Subset of Resources)
어떤 경우에는 테스트 매니페스트에 정의된 모든 정책, 규칙, 리소스 조합이 아니라 일부만 테스트하고 싶을 수 있습니다. 실행할 정확한 테스트를 지정하려면 --test-case-selector 플래그를 사용하세요.
kyverno test . --test-case-selector "policy=add-default-resources, rule=add-default-requests, resource=nginx-demo2"
예시 (Examples)
test 명령은 정책을 리소스에 적용하고 실제 결과를 기대/예상 결과와 비교하여 테스트 선언을 실행합니다. 실제 결과가 기대 결과와 일치하면 테스트는 통과합니다.
아래는 두 개의 validate 규칙을 포함하는 정책을 같은 리소스에 대해 테스트하는 예시로, 각각 정책을 통과해야 합니다.
정책 매니페스트(disallow_latest_tag.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: disallow-latest-tag
spec:
rules:
- name: require-image-tag
match:
any:
- resources:
kinds:
- Pod
validate:
failureAction: Audit
message: 'An image tag is required.'
pattern:
spec:
containers:
- image: '*:*'
- name: validate-image-tag
match:
any:
- resources:
kinds:
- Pod
validate:
failureAction: Audit
message: "Using a mutable image tag e.g. 'latest' is not allowed."
pattern:
spec:
containers:
- image: '!*:latest'
리소스 매니페스트(resource.yaml):
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: nginx
image: nginx:1.12
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: disallow_latest_tag
policies:
- disallow_latest_tag.yaml
resources:
- resource.yaml
results:
- policy: disallow-latest-tag
rule: require-image-tag
resources:
- myapp-pod
kind: Pod
result: pass
- policy: disallow-latest-tag
rule: validate-image-tag
resources:
- myapp-pod
kind: Pod
result: pass
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 1 resource ...
Checking results ...
│────│─────────────────────│────────────────────│───────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│─────────────────────│────────────────────│───────────────│────────│────────│
│ 1 │ disallow-latest-tag │ require-image-tag │ Pod/myapp-pod │ Pass │ Ok │
│ 2 │ disallow-latest-tag │ validate-image-tag │ Pod/myapp-pod │ Pass │ Ok │
│────│─────────────────────│────────────────────│───────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
아래 사례에서는 Pod에 기본 리소스를 추가하는 mutate 정책이 두 리소스에 대해 테스트됩니다. mutate 규칙을 테스트할 때 요구되는 결과 배열의 patchedResources 필드가 추가된 것에 주목하세요.
정책 매니페스트(add-default-resources.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-resources
spec:
background: false
rules:
- name: add-default-requests
match:
any:
- resources:
kinds:
- Pod
preconditions:
any:
- key: '{{request.operation}}'
operator: AnyIn
value:
- CREATE
- UPDATE
mutate:
patchStrategicMerge:
spec:
containers:
- (name): '*'
resources:
requests:
+(memory): '100Mi'
+(cpu): '100m'
리소스 매니페스트(resource.yaml):
apiVersion: v1
kind: Pod
metadata:
name: nginx-demo1
spec:
containers:
- name: nginx
image: nginx:1.14.2
---
apiVersion: v1
kind: Pod
metadata:
name: nginx-demo2
spec:
containers:
- name: nginx
image: nginx:latest
resources:
requests:
memory: '200Mi'
cpu: '200m'
Variables 매니페스트(values.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
policies:
- name: add-default-resources
resources:
- name: nginx-demo1
values:
request.operation: CREATE
- name: nginx-demo2
values:
request.operation: UPDATE
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: add-default-resources
policies:
- add-default-resources.yaml
resources:
- resource.yaml
variables: values.yaml
results:
- policy: add-default-resources
rule: add-default-requests
resources:
- nginx-demo1
patchedResources: patchedResource1.yaml
kind: Pod
result: pass
- policy: add-default-resources
rule: add-default-requests
resources:
- nginx-demo2
patchedResources: patchedResource2.yaml
kind: Pod
result: skip
$ kyverno test .
Executing add-default-resources...
applying 1 policy to 2 resources...
skipped mutate policy add-default-resources -> resource default/Pod/nginx-demo2
│───│───────────────────────│──────────────────────│─────────────────────────│────────│
│ # │ POLICY │ RULE │ RESOURCE │ RESULT │
│───│───────────────────────│──────────────────────│─────────────────────────│────────│
│ 1 │ add-default-resources │ add-default-requests │ default/Pod/nginx-demo1 │ Pass │
│ 2 │ add-default-resources │ add-default-requests │ default/Pod/nginx-demo2 │ Pass │
│───│───────────────────────│──────────────────────│─────────────────────────│────────│
Test Summary: 2 tests passed and 0 tests failed
이 시나리오에서는 특정 ConfigMap에 대한 요청에 따라 Secrets에 레이블을 추가하는 mutate 정책을 테스트하며, targetResources 필드의 사용에 주목하세요.
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test.yaml
policies:
- policy.yaml
resources:
- trigger-cm.yaml
targetResources:
- raw-secret.yaml
results:
- patchedResources: mutated-secret.yaml
policy: mutate-existing-secret
resources:
- secret-1
result: pass
rule: mutate-secret-on-configmap-create
정책(policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: mutate-existing-secret
spec:
rules:
- match:
any:
- resources:
kinds:
- ConfigMap
names:
- dictionary-1
namespaces:
- staging
mutate:
mutateExistingOnPolicyUpdate: false
patchStrategicMerge:
metadata:
labels:
foo: bar
targets:
- apiVersion: v1
kind: Secret
name: '*'
namespace: staging
name: mutate-secret-on-configmap-create
트리거(trigger-cm.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: dictionary-1
namespace: staging
대상(raw-secret.yaml):
apiVersion: v1
kind: Secret
metadata:
name: secret-1
namespace: staging
변경된 대상(mutated-secret.yaml):
apiVersion: v1
kind: Secret
metadata:
labels:
foo: bar
name: secret-1
namespace: staging
$ kyverno test .
Loading test ( 3-test/kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 1 resource ...
Checking results ...
│────│────────────────────────│───────────────────────────────────│────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────────│───────────────────────────────────│────────────────────────────│────────│────────│
│ 1 │ mutate-existing-secret │ mutate-secret-on-configmap-create │ v1/Secret/staging/secret-1 │ Pass │ Ok │
│────│────────────────────────│───────────────────────────────────│────────────────────────────│────────│────────│
Test Summary: 1 tests passed and 0 tests failed
results의 resources 필드에 항목을 지정하지 않으면 CLI는 테스트에 관련된 모든 트리거 및 대상 리소스의 결과를 확인하고 patchedResources 파일에 지정된 리소스와 일치시킵니다:
변경된 리소스(mutated-resources.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: dictionary-1
namespace: staging
---
apiVersion: v1
kind: Secret
metadata:
labels:
foo: bar
name: secret-1
namespace: staging
---
Loading test ( 5-test-with-selection/kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 1 resource ...
Checking results ...
│────│────────────────────────│───────────────────────────────────│───────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────────│───────────────────────────────────│───────────────────────────────────│────────│────────│
│ 1 │ mutate-existing-secret │ mutate-secret-on-configmap-create │ v1/Secret/staging/secret-1 │ Pass │ Ok │
│ 2 │ mutate-existing-secret │ mutate-secret-on-configmap-create │ v1/ConfigMap/staging/dictionary-1 │ Pass │ Ok │
│────│────────────────────────│───────────────────────────────────│───────────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
다음 정책 테스트에서는 resource.yaml에 존재하는 기존 리소스에서 새 리소스를 생성하는 generate 정책 규칙이 적용됩니다. generate 정책을 테스트하려면 정책이 생성한 리소스에 대해 테스트하는 데 사용되는 results 배열의 generatedResource 필드 추가가 필요합니다.
정책 매니페스트(add_network_policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-networkpolicy
spec:
rules:
- name: default-deny
match:
any:
- resources:
kinds:
- Namespace
generate:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
name: default-deny
namespace: '{{request.object.metadata.name}}'
synchronize: true
data:
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
리소스 매니페스트(resource.yaml):
apiVersion: v1
kind: Namespace
metadata:
name: hello-world-namespace
생성된 리소스(generatedResource.yaml):
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: hello-world-namespace
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: deny-all-traffic
policies:
- add_network_policy.yaml
resources:
- resource.yaml
results:
- policy: add-networkpolicy
rule: default-deny
resources:
- hello-world-namespace
generatedResource: generatedResource.yaml
kind: Namespace
result: pass
$ kyverno test .
Executing deny-all-traffic...
applying 1 policy to 1 resource...
│───│───────────────────│──────────────│────────────────────────────────│────────│
│ # │ POLICY │ RULE │ RESOURCE │ RESULT │
│───│───────────────────│──────────────│────────────────────────────────│────────│
│ 1 │ add-networkpolicy │ default-deny │ /Namespace/hello-world-namespace │ Pass │
│───│───────────────────│──────────────│────────────────────────────────│────────│
Test Summary: 1 tests passed and 0 tests failed
다음 정책 테스트에서는 validate 규칙이 Pod이 host namespace에 접근하지 못하도록 보장합니다. Policy Exception을 사용해 delta namespace에서 important-tool이라는 이름으로 시작하는 Pod과 Deployment를 이 규칙에서 제외합니다. exceptions 필드는 테스트 매니페스트에서 Policy Exception 매니페스트를 선언하는 데 사용됩니다. 규칙을 위반하지만 정책 예외와 일치하는 리소스는 skip될 것으로 예상됩니다. 그렇지 않으면 fail됩니다.
정책 매니페스트(disallow-host-namespaces.yaml):
apiVersion: kyverno.io/v2beta1
kind: ClusterPolicy
metadata:
name: disallow-host-namespaces
spec:
background: false
rules:
- name: host-namespaces
match:
any:
- resources:
kinds:
- Pod
validate:
failureAction: Enforce
message: >-
Sharing the host namespaces is disallowed. The fields spec.hostNetwork,
spec.hostIPC, and spec.hostPID must be unset or set to `false`.
pattern:
spec:
=(hostPID): 'false'
=(hostIPC): 'false'
=(hostNetwork): 'false'
Policy Exception 매니페스트(delta-exception.yaml):
apiVersion: kyverno.io/v2
kind: PolicyException
metadata:
name: delta-exception
namespace: delta
spec:
exceptions:
- policyName: disallow-host-namespaces
ruleNames:
- host-namespaces
- autogen-host-namespaces
match:
any:
- resources:
kinds:
- Pod
- Deployment
namespaces:
- delta
names:
- important-tool*
리소스 매니페스트(resource.yaml):
두 Deployment 모두 정책을 위반하지만 하나만 예외와 일치합니다. 예외가 없는 Deployment는 fail되고 예외가 있는 Deployment는 skip됩니다.
apiVersion: apps/v1
kind: Deployment
metadata:
name: important-tool
namespace: delta
labels:
app: busybox
spec:
replicas: 1
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
hostIPC: true
containers:
- image: busybox:1.35
name: busybox
command: ['sleep', '1d']
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: not-important
namespace: gamma
labels:
app: busybox
spec:
replicas: 1
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
hostIPC: true
containers:
- image: busybox:1.35
name: busybox
command: ['sleep', '1d']
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: disallow-host-namespaces-test-exception
policies:
- disallow-host-namespace.yaml
resources:
- resource.yaml
exceptions:
- delta-exception.yaml
results:
- kind: Deployment
policy: disallow-host-namespaces
resources:
- important-tool
rule: host-namespaces
result: skip
- kind: Deployment
policy: disallow-host-namespaces
resources:
- not-important
rule: host-namespaces
result: fail
kyverno test .
Loading test ( .kyverno-test/kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 2 resources with 1 exception ...
Checking results ...
│────│──────────────────────────│─────────────────│───────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│──────────────────────────│─────────────────│───────────────────────────│────────│────────│
│ 1 │ disallow-host-namespaces │ host-namespaces │ Deployment/important-tool │ Pass │ Ok │
│ 2 │ disallow-host-namespaces │ host-namespaces │ Deployment/not-important │ Pass │ Ok │
│────│──────────────────────────│─────────────────│───────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
더 많은 테스트 케이스 예시는 웹사이트에 나타나는 모든 샘플 정책에 대한 테스트 케이스를 갖추기 위해 노력하는 kyverno/policies 저장소를 참고하세요.
Kubernetes 네이티브 정책 (Kubernetes Native Policies)
kyverno test 명령을 사용해 네이티브 Kubernetes 정책을 테스트할 수 있습니다.
ValidatingAdmissionPolicy
ValidatingAdmissionPolicy를 테스트하려면 테스트 매니페스트의 각 result 항목에 isValidatingAdmissionPolicy: true 필드가 포함되어야 합니다.
아래는 두 개의 리소스 중 하나가 정책을 위반하는 경우에 대해 ValidatingAdmissionPolicy를 테스트하는 예시입니다.
정책 매니페스트(disallow-host-path.yaml):
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: disallow-host-path
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['deployments']
validations:
- expression: '!has(object.spec.template.spec.volumes) || object.spec.template.spec.volumes.all(volume, !has(volume.hostPath))'
message: 'HostPath volumes are forbidden. The field spec.template.spec.volumes[*].hostPath must be unset.'
리소스 매니페스트(deployments.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-pass
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx-server
image: nginx
volumeMounts:
- name: temp
mountPath: /scratch
volumes:
- name: temp
emptyDir: {}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-fail
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx-server
image: nginx
volumeMounts:
- name: udev
mountPath: /data
volumes:
- name: udev
hostPath:
path: /etc/udev
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: disallow-host-path-test
policies:
- disallow-host-path.yaml
resources:
- deployments.yaml
results:
- policy: disallow-host-path
resources:
- deployment-pass
isValidatingAdmissionPolicy: true
kind: Deployment
result: pass
- policy: disallow-host-path
resources:
- deployment-fail
isValidatingAdmissionPolicy: true
kind: Deployment
result: fail
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Applying 1 policy to 2 resources ...
Checking results ...
│────│────────────────────│──────│────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────│──────│────────────────────────────│────────│────────│
│ 1 │ disallow-host-path │ │ Deployment/deployment-pass │ Pass │ Ok │
│ 2 │ disallow-host-path │ │ Deployment/deployment-fail │ Pass │ Ok │
│────│────────────────────│──────│────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
아래 예시에서는 ValidatingAdmissionPolicy와 해당 ValidatingAdmissionPolicyBinding이 여섯 개의 리소스에 대해 테스트됩니다. 이 중 두 개는 바인딩과 일치하지 않고, 두 개는 바인딩과 일치하지만 정책을 위반하며, 나머지 두 개는 바인딩과 일치하고 정책을 위반하지 않습니다.
정책 매니페스트(check-deployment-replicas.yaml):
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: 'check-deployment-replicas'
spec:
matchConstraints:
resourceRules:
- apiGroups:
- apps
apiVersions:
- v1
operations:
- CREATE
- UPDATE
resources:
- deployments
validations:
- expression: object.spec.replicas <= 2
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: 'check-deployment-replicas-binding'
spec:
policyName: 'check-deployment-replicas'
validationActions: [Deny]
matchResources:
namespaceSelector:
matchExpressions:
- key: environment
operator: In
values:
- staging
- production
리소스 매니페스트(resource.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: testing-deployment-1
namespace: testing
labels:
app: busybox
spec:
replicas: 4
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: testing-deployment-2
namespace: testing
labels:
app: busybox
spec:
replicas: 2
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: staging-deployment-1
namespace: staging
labels:
app: nginx
spec:
replicas: 4
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: staging-deployment-2
namespace: staging
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: production-deployment-1
namespace: production
labels:
app: nginx
spec:
replicas: 4
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: production-deployment-2
namespace: production
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
위 리소스 매니페스트에는 다음이 포함됩니다:
- testing namespace에
testing-deployment-1과testing-deployment-2라는 두 개의 Deployment. 첫 번째 Deployment에는 4개의 레플리카가 있고, 두 번째에는 2개가 있습니다. - staging namespace에
staging-deployment-1과staging-deployment-2라는 두 개의 Deployment. 첫 번째 Deployment에는 4개의 레플리카가 있고, 두 번째에는 2개가 있습니다. - production namespace에
production-deployment-1과production-deployment-2라는 두 개의 Deployment. 첫 번째 Deployment에는 4개의 레플리카가 있고, 두 번째에는 2개가 있습니다.
Variables 매니페스트(values.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Values
metadata:
name: values
namespaceSelector:
- name: staging
labels:
environment: staging
- name: production
labels:
environment: production
- name: testing
labels:
environment: testing
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test.yaml
policies:
- policy.yaml
resources:
- resource.yaml
variables: values.yaml
results:
- kind: Deployment
policy: check-deployment-replicas
isValidatingAdmissionPolicy: true
resources:
- testing-deployment-1
- testing-deployment-2
result: skip
- kind: Deployment
policy: check-deployment-replicas
isValidatingAdmissionPolicy: true
resources:
- staging-deployment-1
- production-deployment-1
result: fail
- kind: Deployment
policy: check-deployment-replicas
isValidatingAdmissionPolicy: true
resources:
- staging-deployment-2
- production-deployment-2
result: pass
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 6 resources ...
Checking results ...
│────│───────────────────────────│──────│────────────────────────────────────│────────│──────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│───────────────────────────│──────│────────────────────────────────────│────────│──────────│
│ 1 │ check-deployment-replicas │ │ Deployment/testing-deployment-1 │ Pass │ Excluded │
│ 2 │ check-deployment-replicas │ │ Deployment/testing-deployment-2 │ Pass │ Excluded │
│ 3 │ check-deployment-replicas │ │ Deployment/staging-deployment-1 │ Pass │ Ok │
│ 4 │ check-deployment-replicas │ │ Deployment/production-deployment-1 │ Pass │ Ok │
│ 5 │ check-deployment-replicas │ │ Deployment/staging-deployment-2 │ Pass │ Ok │
│ 6 │ check-deployment-replicas │ │ Deployment/production-deployment-2 │ Pass │ Ok │
│────│───────────────────────────│──────│────────────────────────────────────│────────│──────────│
Test Summary: 6 tests passed and 0 tests failed
MutatingAdmissionPolicy
MutatingAdmissionPolicy를 테스트하려면 테스트 매니페스트의 테스트 결과 배열에 isMutatingAdmissionPolicy 필드를 true로 설정해야 합니다. 또한 정책이 패치할 것으로 예상되는 리소스를 지정하려면 patchedResources 필드를 포함해야 합니다.
예시 1: 단순 변경 (Simple Mutation)
이 예시는 ConfigMap에 레이블을 추가하는 정책을 테스트합니다.
정책 매니페스트(policy.yaml):
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: MutatingAdmissionPolicy
metadata:
name: 'add-label-to-configmap'
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE']
resources: ['configmaps']
failurePolicy: Fail
reinvocationPolicy: Never
mutations:
- patchType: 'ApplyConfiguration'
applyConfiguration:
expression: >
object.metadata.?labels["lfx-mentorship"].hasValue() ? Object{} :
Object{
metadata: Object.metadata{
labels: {"lfx-mentorship": "kyverno"}
}
}
리소스 매니페스트(resource.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: game-demo
labels:
app: game
data:
player_initial_lives: '3'
패치된 리소스 매니페스트(patched-resource.yaml):
이 파일은 정책이 적용된 후 ConfigMap이 어떻게 보여야 하는지 정의합니다.
apiVersion: v1
kind: ConfigMap
metadata:
name: game-demo
labels:
app: game
lfx-mentorship: kyverno
data:
player_initial_lives: '3'
테스트 매니페스트(kyverno-test.yaml):
apiVersion: kyverno.io/v1
kind: Test
metadata:
name: test
policies:
- policy.yaml
resources:
- resource.yaml
results:
- isMutatingAdmissionPolicy: true
kind: ConfigMap
patchedResources: patched-resource.yaml
policy: add-label-to-configmap
resources:
- game-demo
result: pass
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 1 resource with 0 exceptions ...
Checking results ...
│────│────────────────────────│──────│────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────────│──────│────────────────────────────────│────────│────────│
│ 1 │ add-label-to-configmap │ │ v1/ConfigMap/default/game-demo │ Pass │ Ok │
│────│────────────────────────│──────│────────────────────────────────│────────│────────│
Test Summary: 1 tests passed and 0 tests failed
예시 2: 바인딩과 Namespace 선택기를 사용한 변경 (Mutation with a Binding and Namespace Selector)
이 예시는 특정 Namespace의 ConfigMap에 레이블을 추가하는 정책을 테스트합니다.
정책 매니페스트(policy.yaml):
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: MutatingAdmissionPolicy
metadata:
name: 'add-label-to-configmap'
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE']
resources: ['configmaps']
failurePolicy: Fail
reinvocationPolicy: Never
mutations:
- patchType: 'ApplyConfiguration'
applyConfiguration:
expression: >
object.metadata.?labels["lfx-mentorship"].hasValue() ? Object{} :
Object{
metadata: Object.metadata{
labels: {"lfx-mentorship": "kyverno"}
}
}
---
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: MutatingAdmissionPolicyBinding
metadata:
name: 'add-label-to-configmap-binding'
spec:
policyName: 'add-label-to-configmap'
matchResources:
namespaceSelector:
matchExpressions:
- key: environment
operator: In
values:
- staging
- production
리소스 매니페스트(resource.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: matched-cm-1
namespace: staging
labels:
color: red
data:
player_initial_lives: '3'
---
apiVersion: v1
kind: ConfigMap
metadata:
name: matched-cm-2
namespace: production
labels:
color: red
data:
player_initial_lives: '3'
---
apiVersion: v1
kind: ConfigMap
metadata:
name: unmatched-cm
namespace: testing
labels:
color: blue
data:
player_initial_lives: '3'
패치된 리소스 매니페스트(patched-resource.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: matched-cm-1
namespace: staging
labels:
color: red
lfx-mentorship: kyverno
data:
player_initial_lives: '3'
---
apiVersion: v1
kind: ConfigMap
metadata:
name: matched-cm-2
namespace: production
labels:
color: red
lfx-mentorship: kyverno
data:
player_initial_lives: '3'
Variables 매니페스트(values.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Value
metadata:
name: values
namespaceSelector:
- labels:
environment: staging
name: staging
- labels:
environment: production
name: production
- labels:
environment: testing
name: testing
테스트 매니페스트(kyverno-test.yaml):
apiVersion: kyverno.io/v1
kind: Test
metadata:
name: test
policies:
- policy.yaml
resources:
- resource.yaml
results:
- isMutatingAdmissionPolicy: true
kind: ConfigMap
patchedResources: patched-resource.yaml
policy: add-label-to-configmap
resources:
- matched-cm-1
- matched-cm-2
result: pass
variables: values.yaml
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 3 resources with 0 exceptions ...
Checking results ...
│────│────────────────────────│──────│──────────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────────│──────│──────────────────────────────────────│────────│────────│
│ 1 │ add-label-to-configmap │ │ v1/ConfigMap/staging/matched-cm-1 │ Pass │ Ok │
│ 2 │ add-label-to-configmap │ │ v1/ConfigMap/production/matched-cm-2 │ Pass │ Ok │
│────│────────────────────────│──────│──────────────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
ValidatingPolicies 테스트하기 (Testing ValidatingPolicies)
ValidatingPolicy를 테스트하려면 테스트 매니페스트의 results 배열에 isValidatingPolicy 필드를 true로 설정해야 합니다.
아래는 두 개의 리소스 중 하나가 정책을 위반하는 경우에 대해 ValidatingPolicy를 테스트하는 예시입니다.
정책 매니페스트(check-deployment-replicas.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-deployment-replicas
spec:
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['deployments']
validations:
- expression: 'object.spec.replicas <= 2'
message: 'Deployment replicas must be less than or equal to 2'
리소스 매니페스트(deployments.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: good-deployment
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: bad-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test
policies:
- policy.yaml
resources:
- deployments.yaml
results:
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-replicas
resources:
- bad-deployment
result: fail
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-replicas
resources:
- good-deployment
result: pass
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 2 resources with 0 exceptions ...
Checking results ...
│────│───────────────────────────│──────│────────────────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│───────────────────────────│──────│────────────────────────────────────────────│────────│────────│
│ 1 │ check-deployment-replicas │ │ apps/v1/Deployment/default/bad-deployment │ Pass │ Ok │
│ 2 │ check-deployment-replicas │ │ apps/v1/Deployment/default/good-deployment │ Pass │ Ok │
│────│───────────────────────────│──────│────────────────────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
일부 정책은 리소스가 생성되는 Namespace의 속성(예: 레이블이나 이름)을 기반으로 결정을 내려야 합니다. CEL의 namespaceObject 변수는 이를 위해 전체 namespace 객체에 대한 접근을 제공합니다.
kyverno test를 실행할 때 명령은 오프라인 모드로 동작하며 라이브 클러스터의 namespaces에 접근할 수 없습니다. namespaceObject를 사용하는 정책을 테스트하려면 mock namespace 정의를 제공해야 합니다. 이는 "values file"을 만들고 이를 kyverno-test.yaml에서 참조하여 수행합니다.
default namespace에서 특정 Deployment 생성을 금지하는 정책부터 시작해 보겠습니다. Namespace의 이름을 확인하기 위해 namespaceObject.metadata.name을 사용합니다.
정책 매니페스트(disallow-default-deployment.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-deployment-namespace
spec:
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['deployments']
# This policy only applies to Deployments with the label `app: nginx`
objectSelector:
matchLabels:
app: nginx
validations:
# The validation logic checks the name of the Namespace object.
- expression: "namespaceObject.metadata.name != 'default'"
message: "Using 'default' namespace is not allowed for this application."
모든 테스트 케이스를 다루도록 여러 Deployment를 정의합니다:
- default namespace의 Deployment (fail되어야 함).
- 다른 namespace인 staging의 Deployment (pass되어야 함).
app: nginx레이블이 없는 두 개의 Deployment (skip되어야 함).
리소스 매니페스트(deployments.yaml):
# This deployment should FAIL because it's in the 'default' namespace.
apiVersion: apps/v1
kind: Deployment
metadata:
name: bad-deployment
namespace: default
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
# This deployment should PASS because it's in the 'staging' namespace.
apiVersion: apps/v1
kind: Deployment
metadata:
name: good-deployment
namespace: staging
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
---
# This deployment should be SKIPPED because it lacks the 'app: nginx' label.
apiVersion: apps/v1
kind: Deployment
metadata:
name: skipped-deployment-1
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox:latest
---
# This deployment should also be SKIPPED for the same reason.
apiVersion: apps/v1
kind: Deployment
metadata:
name: skipped-deployment-2
namespace: staging
spec:
replicas: 1
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox:latest
이것이 핵심 단계입니다. mock Namespace 객체를 제공하기 위해 values 파일(예: values.yaml)을 만듭니다. kyverno test 명령은 테스트 실행 중 이 객체들을 사용해 namespaceObject 변수를 채웁니다.
Values 매니페스트(values.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Value
metadata:
name: values
namespaces:
- apiVersion: v1
kind: namespace
metadata:
labels:
environment: staging
name: staging
- apiVersion: v1
kind: namespace
metadata:
labels:
environment: default
name: default
마지막으로 모든 것을 묶는 테스트 매니페스트를 만듭니다.
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test.yaml
policies:
- policy.yaml
resources:
- resources.yaml
results:
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-namespace
resources:
- bad-deployment
result: fail
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-namespace
resources:
- good-deployment
result: pass
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-namespace
resources:
- skipped-deployment-1
- skipped-deployment-2
result: skip
variables: values.yaml
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 4 resources with 0 exceptions ...
Checking results ...
│────│────────────────────────────│──────│────────────────────────────────────────────│────────│──────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────────────│──────│────────────────────────────────────────────│────────│──────────│
│ 1 │ check-deployment-namespace │ │ apps/v1/Deployment/default/bad-deployment │ Pass │ Ok │
│ 2 │ check-deployment-namespace │ │ apps/v1/Deployment/staging/good-deployment │ Pass │ Ok │
│ 3 │ check-deployment-namespace │ │ apps/Deployment/v1 │ Pass │ Excluded │
│ 4 │ check-deployment-namespace │ │ apps/Deployment/v1 │ Pass │ Excluded │
│────│────────────────────────────│──────│────────────────────────────────────────────│────────│──────────│
Test Summary: 4 tests passed and 0 tests failed
정책은 종종 ConfigMap에 저장된 값 같은 외부 데이터를 기반으로 리소스를 검증해야 합니다. Kyverno의 커스텀 CEL 함수 resource.Get()은 정책이 클러스터에서 이러한 외부 리소스를 가져올 수 있게 해 줍니다.
오프라인 테스트를 위해 kyverno test를 사용할 때, resource.Get() 함수가 성공적으로 해결할 수 있도록 이 외부 리소스를 "context"로 제공해야 합니다. 이는 kyverno-test.yaml에서 직접 컨텍스트 파일을 참조하여 수행할 수 있습니다.
이 예시에서는 Pod의 이름을 ConfigMap에 저장된 값과 비교해 검증하는 정책을 테스트합니다.
먼저 check-pod-name-from-configmap이라는 정책을 정의합니다. 이 정책은 resource.Get()을 사용해 policy-cm이라는 ConfigMap을 가져온 다음, 들어오는 Pod의 이름이 ConfigMap의 data에 있는 name 키와 일치하는지 확인합니다.
정책 매니페스트(check-pod-name-from-configmap.yaml):
policy.yaml
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-pod-name-from-configmap
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: ['CREATE', 'UPDATE']
resources: ['pods']
variables:
# Get the ConfigMap 'policy-cm' from the Pod's namespace.
- name: cm
expression: >-
resource.Get("v1", "configmaps", object.metadata.namespace, "policy-cm")
validations:
# The Pod is valid only if its name matches the value from the ConfigMap.
- expression: >-
object.metadata.name == variables.cm.data.name
컨텍스트 매니페스트(context.yaml):
context.yaml
apiVersion: cli.kyverno.io/v1alpha1
kind: Context
metadata:
name: test-context
spec:
resources:
- apiVersion: v1
kind: ConfigMap
metadata:
namespace: default
name: policy-cm
data:
# The 'name' key specifies that the only valid pod name is 'good-pod'.
name: good-pod
good-pod(이름이 컨텍스트의 값과 일치)와 bad-pod(일치하지 않음)라는 두 개의 Pod 매니페스트를 정의합니다.
리소스 매니페스트(pods.yaml):
# This Pod should PASS validation.
apiVersion: v1
kind: Pod
metadata:
name: good-pod
spec:
containers:
- name: nginx
image: nginx
---
# This Pod should FAIL validation.
apiVersion: v1
kind: Pod
metadata:
name: bad-pod
spec:
containers:
- name: nginx
image: nginx
마지막으로 kyverno-test.yaml 파일을 만듭니다. 핵심은 mock ConfigMap을 테스트에 연결하는 context: context.yaml 필드입니다.
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test.yaml
policies:
- policy.yaml
resources:
- pod1.yaml
- pod2.yaml
results:
- isValidatingPolicy: true
kind: Pod
policy: disallow-host-path
resources:
- bad-pod
result: fail
- isValidatingPolicy: true
kind: Pod
policy: disallow-host-path
resources:
- good-pod
result: pass
context: context.yaml
$ kyverno test .
Loading test ( kyverno-test.yaml ) ...
Loading values/variables ...
Loading policies ...
Loading resources ...
Loading exceptions ...
Applying 1 policy to 2 resources with 0 exceptions ...
Checking results ...
│────│────────────────────│──────│─────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│────────────────────│──────│─────────────────────────│────────│────────│
│ 1 │ disallow-host-path │ │ v1/Pod/default/bad-pod │ Pass │ Ok │
│ 2 │ disallow-host-path │ │ v1/Pod/default/good-pod │ Pass │ Ok │
│────│────────────────────│──────│─────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
오프라인 HTTP Mock과 Global Context로 정책 테스트하기 (Testing Policies with Offline HTTP Mocks and Global Context)
context.apiCall, CEL http.Get() 또는 http.Post()를 통해 외부 HTTP 서비스를 호출하거나 GlobalContextEntry 참조를 조회하는 정책은 CLI에 라이브 클러스터나 외부 서버가 없으므로 기본적으로 kyverno test로 테스트할 수 없습니다. Kyverno CLI v1.14부터 kyverno-test.yaml은 apiCallResponses와 globalContextEntries라는 두 개의 새로운 선택적 필드를 허용하므로 기대하는 외부 데이터를 인라인으로 선언할 수 있으며, 로컬 개발과 CI/CD 파이프라인에서 완전한 오프라인 정책 검증이 가능합니다.
스키마 개요 (Schema overview)
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: my-test
policies:
- policy.yaml
resources:
- resources.yaml
# Inline mock responses for context.apiCall and CEL http.Get() / http.Post() calls.
apiCallResponses:
- url: https://external-service.example.com/api/check # URL to match (required)
method: GET # HTTP method (optional; matches any method if omitted)
response:
statusCode: 200 # Must be a valid HTTP status code (100–599)
body: # Arbitrary JSON object
allowed: true
# Inline mock data for GlobalContextEntry references.
# Each entry requires exactly ONE of: data, resources, or resourceFiles (mutually exclusive).
globalContextEntries:
- name: gctxentry-deployments # Must match the GlobalContextEntry name used in the policy
# Option 1: arbitrary JSON root value
data:
deployments:
- name: existing-deployment-1
- name: existing-deployment-2
# Option 2: inline Kubernetes resource manifests (mimics kubernetesResource cache shape)
# resources:
# - apiVersion: apps/v1
# kind: Deployment
# metadata:
# name: existing-deployment-1
# namespace: default
# Option 3: YAML file paths relative to the test directory
# resourceFiles:
# - gce-deployments.yaml
fieldPath: deployments # Optional JMESPath applied to the root before projections
projections: # Optional list of named values extracted from the narrowed root
- name: items
path: '@'
results:
- kind: Pod
policy: my-policy
resources:
- default/my-pod
result: pass
rule: my-rule
참고 (Note): 각 apiCallResponses 항목의 body 필드는 유효한 JSON 값(객체, 배열, 문자열, 숫자, 불리언, null)을 허용합니다. 상태 코드는 표준 HTTP 코드(100–599)인지 검증되고 body는 유효한 JSON이어야 합니다. CLI는 어떤 테스트가 실행되기 전에 형식이 잘못된 mock에 대해 오류를 보고합니다.
상호 배타성 (Mutual Exclusivity): 각 globalContextEntries 항목에 대해 data, resources, resourceFiles는 상호 배타적이며 정확히 하나만 제공해야 합니다. resources와 resourceFiles 옵션은 kubernetesResource 기반 GlobalContextEntries를 위해 설계되었습니다. CLI는 매니페스트를 실제 Kubernetes informer cache가 반환하는 것과 동일한 []interface{} 목록 형태로 디코딩하므로 JMESPath와 CEL projections가 프로덕션과 동일하게 동작합니다. data 옵션은 임의의 JSON을 위한 것으로, Kubernetes 객체보다 구조화된 데이터를 보유하는 GlobalContextEntry를 mock할 때 유용합니다.
중복 키 검증 (Duplicate Key Validation): 각 apiCallResponses 항목은 method + URL 조합으로 고유하게 식별됩니다. 같은 method와 url로 두 항목을 구성하는 것은 오류입니다. CLI는 평가가 시작되기 전에 테스트 매니페스트를 거부합니다. 이는 중복 mock으로 인한 조용한 비결정적 동작을 방지합니다.
같은 URL에 대한 서로 다른 HTTP 메서드는 유효한 별개 항목입니다. 예를 들어 둘 다 https://authz.example.com/validate를 가리키는 GET 항목과 POST 항목은 충돌 없이 공존할 수 있습니다.
CEL http.Get() 호출 mock하기 (Mocking CEL http.Get() calls)
다음 예시는 Kyverno의 CEL http.Get() 라이브러리 함수를 사용해 외부 구성 엔드포인트를 호출하는 ValidatingPolicy를 테스트합니다.
정책 매니페스트(policy.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-external-config
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: [CREATE, UPDATE]
resources: [pods]
variables:
- name: config
expression: http.Get("https://example.com/config")
validations:
- expression: variables.config.allowed == true
message: 'External config check failed'
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: cel-http-get-mock-test
policies:
- policy.yaml
resources:
- resources.yaml
apiCallResponses:
- method: GET
url: https://example.com/config
response:
statusCode: 200
body:
allowed: true
results:
- isValidatingPolicy: true
kind: Pod
policy: check-external-config
resources:
- default/test-pod
result: pass
테스트 실행:
kyverno test .
예상 출력:
Loading test ( kyverno-test.yaml ) ...
Applying 1 policy to 1 resource with 0 exceptions ...
Checking results ...
│────│───────────────────────│──────│─────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│───────────────────────│──────│─────────────────────────────│────────│────────│
│ 1 │ check-external-config │ │ v1/Pod/default/test-pod │ Pass │ Ok │
│────│───────────────────────│──────│─────────────────────────────│────────│────────│
Test Summary: 1 tests passed and 0 tests failed
CEL http.Post() 호출 mock하기 (Mocking CEL http.Post() calls)
다음 예시는 Kyverno의 CEL http.Post() 라이브러리 함수를 사용해 외부 인가 서비스를 호출하는 ValidatingPolicy를 테스트합니다. 서비스가 요청을 허용하는 pass 시나리오와 요청을 거부하는 deny 시나리오가 모두 표시됩니다.
정책 매니페스트(policy.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-pod-admission
spec:
matchConstraints:
resourceRules:
- apiGroups: ['']
apiVersions: ['v1']
operations: [CREATE, UPDATE]
resources: [pods]
validations:
- expression: >-
http.Post("https://authz.example.com/validate",
{"namespace": object.metadata.namespace, "name": object.metadata.name}).body.allowed == true
message: 'External authorization service rejected this pod'
테스트 매니페스트 — pass 시나리오(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: cel-http-post-mock
policies:
- policy.yaml
resources:
- resources.yaml
apiCallResponses:
- method: POST
url: https://authz.example.com/validate
response:
statusCode: 200
body:
allowed: true
results:
- isValidatingPolicy: true
kind: Pod
policy: check-pod-admission
resources:
- default/test-pod
result: pass
테스트 매니페스트 — deny 시나리오(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: cel-http-post-mock-deny
policies:
- policy.yaml
resources:
- resources.yaml
apiCallResponses:
- method: POST
url: https://authz.example.com/validate
response:
statusCode: 200
body:
allowed: false
results:
- isValidatingPolicy: true
kind: Pod
policy: check-pod-admission
resources:
- default/test-pod
result: fail
테스트 실행:
kyverno test .
예상 출력(pass 시나리오):
Loading test ( kyverno-test.yaml ) ...
Applying 1 policy to 1 resource with 0 exceptions ...
Checking results ...
│────│───────────────────────│──────│─────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│───────────────────────│──────│─────────────────────────────│────────│────────│
│ 1 │ check-pod-admission │ │ v1/Pod/default/test-pod │ Pass │ Ok │
│────│───────────────────────│──────│─────────────────────────────│────────│────────│
Test Summary: 1 tests passed and 0 tests failed
context.apiCall (v1 ClusterPolicy) mock하기 (Mocking context.apiCall (v1 ClusterPolicy))
동일한 apiCallResponses 필드는 v1 Kyverno 정책의 context.apiCall 서비스 URL 항목도 mock합니다. URL은 일치시키기 전에 변수 치환이 적용되므로 https://service/check/{{request.object.metadata.name}} 같은 템플릿이 올바르게 해석됩니다.
정책 매니페스트(policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: check-external-service
spec:
rules:
- name: check-allowed
match:
any:
- resources:
kinds:
- Pod
context:
- name: response
apiCall:
method: GET
urlPath: ''
service:
url: https://external-service.example.com/api/check
jmesPath: body
validate:
failureAction: Enforce
message: 'External service denied this Pod'
deny:
conditions:
any:
- key: '{{ response.allowed }}'
operator: Equals
value: false
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: mock-apicall-responses
policies:
- policy.yaml
resources:
- resources.yaml
variables: values.yaml
apiCallResponses:
- url: https://external-service.example.com/api/check
response:
statusCode: 200
body:
allowed: true
results:
- kind: Pod
policy: check-external-service
rule: check-allowed
resources:
- test-ns/test-pod-pass
result: pass
GlobalContextEntry 참조 mock하기 (Mocking GlobalContextEntry references)
globalContextEntries 필드는 context.globalReference(v1 ClusterPolicy) 또는 globalContext.Get()(CEL ValidatingPolicy)을 사용하는 정책에 정적 데이터를 제공합니다.
projections 목록은 data 루트에서 평가되는 JMESPath 표현식에 이름을 매핑하며, 실제 GlobalContextEntry projection 동작과 일치합니다. 선택적 fieldPath는 projections이 적용되기 전에 루트를 좁힐 수 있습니다.
정책 매니페스트 — v1 ClusterPolicy(policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: check-global-context
spec:
rules:
- name: check-deployment-count
context:
- name: deploymentCount
globalReference:
name: gctxentry-deployments
jmesPath: 'items | length(@)'
match:
any:
- resources:
kinds:
- Deployment
validate:
failureAction: Enforce
deny:
conditions:
any:
- key: '{{ deploymentCount }}'
operator: Equals
value: 0
정책 매니페스트 — CEL ValidatingPolicy(policy-vpol.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-global-context-cel
spec:
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: [CREATE, UPDATE]
resources: [deployments]
variables:
- name: deploymentData
expression: globalContext.Get("gctxentry-deployments", "")
validations:
- expression: >-
variables.deploymentData != null && size(variables.deploymentData.items) >= 2
message: 'Deployment count from global context must be at least 2'
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: mock-global-context
policies:
- policy.yaml
- policy-vpol.yaml
resources:
- resources.yaml
variables: values.yaml
globalContextEntries:
- name: gctxentry-deployments
data:
deployments:
- name: existing-deployment-1
- name: existing-deployment-2
projections:
- name: items
path: deployments
results:
- kind: Deployment
policy: check-global-context
rule: check-deployment-count
resources:
- test-ns/test-deployment
result: pass
- isValidatingPolicy: true
kind: Deployment
policy: check-global-context-cel
resources:
- test-ns/test-deployment
result: pass
테스트 실행:
kyverno test .
예상 출력:
Loading test ( kyverno-test.yaml ) ...
Applying 2 policies to 1 resource with 0 exceptions ...
Checking results ...
│────│──────────────────────────│────────────────────────│────────────────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│──────────────────────────│────────────────────────│────────────────────────────────────────────│────────│────────│
│ 1 │ check-global-context │ check-deployment-count │ apps/v1/Deployment/test-ns/test-deployment │ Pass │ Ok │
│ 2 │ check-global-context-cel │ │ apps/v1/Deployment/test-ns/test-deployment │ Pass │ Ok │
│────│──────────────────────────│────────────────────────│────────────────────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
인라인 리소스로 kubernetesResource 기반 GlobalContextEntries mock하기 (Mocking kubernetesResource-backed GlobalContextEntries with Inline Resources)
spec.kubernetesResource 소스가 있는 GlobalContextEntry를 참조하는 정책은 보통 해결하려면 라이브 클러스터가 필요합니다. globalContextEntries의 resources 필드를 사용하면 네이티브 Kubernetes 매니페스트를 kyverno-test.yaml 안에 직접 정의할 수 있습니다. CLI는 이를 Kubernetes informer cache가 사용하는 정확한 []interface{} 형태로 디코딩하므로 JMESPath 표현식과 CEL projections이 프로덕션과 동일하게 동작합니다 — 클러스터가 필요 없습니다.
다음 예시는 kubernetesResource 기반 GlobalContextEntry를 사용해 기존 Deployment 수를 세는 정책을 테스트합니다. 정책의 두 가지 변형인 v1 ClusterPolicy(JMESPath)와 CEL ValidatingPolicy가 표시됩니다.
정책 매니페스트 — v1 ClusterPolicy(policy.yaml):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: check-deployment-replicas
spec:
failurePolicy: Fail
rules:
- name: check-min-replicas
context:
- name: existingDeployments
globalReference:
name: gctxentry-inline-deployments
jmesPath: 'length(@)'
match:
all:
- resources:
kinds:
- Deployment
preconditions:
all:
- key: '{{ request.operation }}'
operator: AnyIn
value:
- CREATE
- UPDATE
validate:
failureAction: Enforce
deny:
conditions:
any:
- key: '{{ existingDeployments }}'
operator: Equals
value: 0
정책 매니페스트 — CEL ValidatingPolicy(policy-vpol.yaml):
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: check-deployment-replicas-cel
spec:
matchConstraints:
resourceRules:
- apiGroups: ['apps']
apiVersions: ['v1']
operations: [CREATE, UPDATE]
resources: [deployments]
variables:
- name: deploymentData
expression: >-
globalContext.Get("gctxentry-inline-deployments", "")
validations:
- expression: >-
variables.deploymentData != null && size(variables.deploymentData) >= 2
message: 'At least 2 existing deployments required in global context'
리소스 매니페스트(resources.yaml) — 검증 중인 리소스:
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
namespace: test-ns
labels:
app: test-deployment
spec:
replicas: 1
selector:
matchLabels:
app: test-deployment
template:
metadata:
labels:
app: test-deployment
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
테스트 매니페스트(kyverno-test.yaml):
resources 아래에 나열된 두 Deployment는 mock kubernetesResource cache 역할을 합니다. 실제 informer가 반환하는 것과 동일한 []interface{} 슬라이스로 디코딩되므로 JMESPath의 length(@)와 CEL의 size(...)가 모두 2를 반환합니다.
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: mock-gce-inline-resource
policies:
- policy.yaml
- policy-vpol.yaml
resources:
- resources.yaml
variables: values.yaml
globalContextEntries:
- name: gctxentry-inline-deployments
resources:
- apiVersion: apps/v1
kind: Deployment
metadata:
name: existing-deployment-1
namespace: default
labels:
app: web
spec:
replicas: 2
- apiVersion: apps/v1
kind: Deployment
metadata:
name: existing-deployment-2
namespace: default
labels:
app: api
spec:
replicas: 3
results:
- kind: Deployment
policy: check-deployment-replicas
rule: check-min-replicas
resources:
- test-ns/test-deployment
result: pass
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-replicas-cel
resources:
- test-ns/test-deployment
result: pass
테스트 실행:
kyverno test .
예상 출력:
Loading test ( kyverno-test.yaml ) ...
Applying 2 policies to 1 resource with 0 exceptions ...
Checking results ...
│────│──────────────────────────────│──────────────────────│────────────────────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│──────────────────────────────│──────────────────────│────────────────────────────────────────────────│────────│────────│
│ 1 │ check-deployment-replicas │ check-min-replicas │ apps/v1/Deployment/test-ns/test-deployment │ Pass │ Ok │
│ 2 │ check-deployment-replicas-cel│ │ apps/v1/Deployment/test-ns/test-deployment │ Pass │ Ok │
│────│──────────────────────────────│──────────────────────│────────────────────────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
외부 파일로 kubernetesResource 기반 GlobalContextEntries mock하기 (Mocking kubernetesResource-backed GlobalContextEntries with External Files)
더 크거나 재사용 가능한 mock 리소스 집합의 경우 resourceFiles를 사용해 테스트 디렉터리 기준의 외부 YAML 파일에서 Kubernetes 매니페스트를 로드하세요. 멀티-도큐먼트 YAML 파일(---로 구분)은 완전히 지원됩니다. CLI는 모든 문서를 분할, 파싱, 병합한 후 정책 컨텍스트에 공급합니다.
이 접근 방식은 위의 인라인 resources 방식과 동일하지만 kyverno-test.yaml을 간결하게 유지하고 동일한 리소스 픽스처 파일을 여러 테스트에서 공유할 수 있게 합니다.
외부 리소스 파일(gce-deployments.yaml):
apiVersion: apps/v1
kind: Deployment
metadata:
name: existing-deployment-1
namespace: default
labels:
app: web
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.21
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: existing-deployment-2
namespace: default
labels:
app: api
spec:
replicas: 3
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: node
image: node:18
테스트 매니페스트(kyverno-test.yaml):
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: mock-gce-resource-files
policies:
- policy.yaml
- policy-vpol.yaml
resources:
- resources.yaml
variables: values.yaml
globalContextEntries:
- name: gctxentry-inline-deployments
resourceFiles:
- gce-deployments.yaml
results:
- kind: Deployment
policy: check-deployment-replicas
rule: check-min-replicas
resources:
- test-ns/test-deployment
result: pass
- isValidatingPolicy: true
kind: Deployment
policy: check-deployment-replicas-cel
resources:
- test-ns/test-deployment
result: pass
테스트 실행:
kyverno test .
예상 출력:
Loading test ( kyverno-test.yaml ) ...
Applying 2 policies to 1 resource with 0 exceptions ...
Checking results ...
│────│──────────────────────────────│──────────────────────│────────────────────────────────────────────────│────────│────────│
│ ID │ POLICY │ RULE │ RESOURCE │ RESULT │ REASON │
│────│──────────────────────────────│──────────────────────│────────────────────────────────────────────────│────────│────────│
│ 1 │ check-deployment-replicas │ check-min-replicas │ apps/v1/Deployment/test-ns/test-deployment │ Pass │ Ok │
│ 2 │ check-deployment-replicas-cel│ │ apps/v1/Deployment/test-ns/test-deployment │ Pass │ Ok │
│────│──────────────────────────────│──────────────────────│────────────────────────────────────────────────│────────│────────│
Test Summary: 2 tests passed and 0 tests failed
팁 (Tip): 같은 mock Kubernetes 리소스 집합을 여러 테스트에서 참조할 때는
resourceFiles를 사용하세요. 파일을 한 번 정의하고 각각의 kyverno-test.yaml에 나열하면 됩니다. 테스트 매니페스트에서 모든 것을 한눈에 보기 원하는 자체 포함 테스트에는resources를 사용하세요.
jp 명령 (jp Command)
Kyverno CLI에는 Kyverno 고유의 커스텀 필터뿐 아니라 jp 도구 자체에 포함된 JMESPath의 전체 기능을 테스트할 수 있는 jp 하위 명령이 있습니다. 입력 JSON 또는 YAML 문서와 표현식을 stdin 또는 파일로 전달하면 jp 하위 명령이 모든 JMESPath 표현식을 평가하고 출력을 제공합니다.
예시:
사용 가능한 Kyverno 커스텀 JMESPath 필터를 나열합니다. 각 커스텀 필터에 대한 자세한 내용은 JMESPath 문서 페이지를 참고하세요. 이는 상위(upstream)에서 제공되는 내장 JMESPath 필터는 표시하지 않고 Kyverno 커스텀 필터만 표시합니다.
$ kyverno jp
functionName: add
Signature: add(any, any) any
Note: does arithmetic addition of two specified values of numbers, quantities, and durations
Name: base64_decode
Signature: base64_decode(string) string
Note: decodes a base 64 string
Name: base64_encode
Signature: base64_encode(string) string
Note: encodes a regular, plaintext and unencoded string to base64
Name: compare
Signature: compare(string, string) number
Note: compares two strings lexicographically
<snip>
stdin 입력을 사용해 커스텀 JMESPath 필터를 테스트합니다.
$ echo '{"foo": "BAR"}' | kyverno jp query 'to_lower(foo)'
Reading from terminal input.
Enter input object and hit Ctrl+D.
# to_lower(foo)
"bar"
입력 JSON 파일을 사용해 커스텀 JMESPath 필터를 테스트합니다. YAML 파일도 지원됩니다.
$ cat foo.json
{"bar": "this-is-a-dashed-string"}
$ kyverno jp query -i foo.json "split(bar, '-')"
# split(bar, '-')
[
"this",
"is",
"a",
"dashed",
"string"
]
커스텀 JMESPath 필터와 상위(upstream) JMESPath 필터를 함께 테스트합니다.
$ kyverno jp query -i foo.json "split(bar, '-') | length(@)"
# split(bar, '-') | length(@)
5
파일의 표현식을 사용해 커스텀 JMESPath 필터를 테스트합니다.
$ cat add
add(`1`,`2`)
$ echo {} | kyverno jp query -q add
Reading from terminal input.
Enter input object and hit Ctrl+D.
# add(`1`,`2`)
3
입력 JSON 파일을 사용해 상위 JMESPath 기능을 테스트하고 정리된 출력을 표시합니다.
$ cat pod.json
{ "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "mypod", "namespace": "foo" }, "spec": { "containers": [ { "name": "busybox", "image": "busybox" } ] } }
$ kyverno jp query -i pod.json 'spec.containers[0].name' -u
# spec.containers[0].name
busybox
JMESPath 표현식을 파싱하고 어떻게 해석되었는지 확인하기 위해 해당 AST를 표시합니다.
$ kyverno jp parse 'request.object.metadata.name | truncate(@, `9`)'
# request.object.metadata.name | truncate(@, `9`)
ASTPipe {
children: {
ASTSubexpression {
children: {
ASTSubexpression {
children: {
ASTSubexpression {
children: {
ASTField { value: "request" }
ASTField { value: "object" }
}
ASTField { value: "metadata" }
}
ASTField { value: "name" }
}
}
ASTFunctionExpression {
value: "truncate"
children: {
ASTCurrentNode { }
ASTLiteral { value: 9 }
}
}
}
}
}
}
Kyverno에서 사용하기 위한 JMESPath 작성에 대한 더 구체적인 정보는 JMESPath 페이지를 참고하세요.
assertion 트리 사용하기 (Working with assertion trees)
Kyverno 1.12는 test 명령에 assertion trees(단언 트리) 지원을 도입했습니다.
assertion trees의 목적은 traditional results 구문보다 더 많은 유연성을 제공하는 것입니다.
Assertion trees는 아래 예시와 같이 checks 스탠자 아래에 위치합니다:
checks:
- match:
resource:
kind: Namespace
metadata:
name: hello-world-namespace
policy:
kind: ClusterPolicy
metadata:
name: sync-secret
rule:
name: sync-my-secret
assert:
status: pass
error:
(status != 'pass'): true
check 항목의 구성 (Composition of a check item)
check는 다음 부분으로 구성됩니다:
- match 문: check가 고려하는 요소를 선택합니다. 이 match는 resource, policy, 그리고/또는 rule에 대해 동작할 수 있습니다. kind나 name으로 일치시키는 것에 국한되지 않고 페이로드의 어떤 것(레이블, 주석 등)과도 일치할 수 있습니다.
- assert 문: 일치한 요소에 대해 검증할 조건을 정의합니다.
- error 문: (assert의 반대) 일치한 요소에 대해 true로 평가되면 안 되는 조건을 정의합니다.
위 예시에서 check는 sync-secret이라는 클러스터 정책과 sync-my-secret 규칙에 대해 hello-world-namespace라는 이름의 Namespace 요소를 일치시킵니다. 해당 요소에 대해 status가 pass와 같을 것으로 예상되고, (status != 'pass') 표현식은 true가 아닐 것으로 예상됩니다.
예시 (Examples)
구현은 Kyverno JSON의 assertion trees를 기반으로 합니다. 구문에 대한 자세한 내용은 해당 문서를 참고하세요.
모든 결과 선택하기 (Select all results)
모든 결과를 선택하려면 빈 match 문을 제공하기만 하면 됩니다:
- match: {} # this will match everything
assert: # ...
error: # ...
레이블 기반 선택 (Select based on labels)
레이블에 기반해 결과를 선택하려면 해당하는 스탠자에 그 레이블을 지정하세요:
- match:
resource:
metadata:
labels:
foo: bar
policy:
metadata:
labels:
bar: baz
assert: # ...
error: # ...
더 알아보기 (Learn more)
Kyverno CLI의 다른 명령과 자세한 내용은 Kyverno 공식 문서의 Kyverno CLI Reference를 참고하세요.