Kyverno Policy Management Quiz
This quiz tests your understanding of policy management using Kyverno in Kubernetes.
Quiz Questions
1. What is Kyverno?
A. A Kubernetes-native policy engine B. A container image scanner C. A cluster monitoring tool D. A service mesh implementation
Show Answer
Answer: A. A Kubernetes-native policy engine
Explanation: Kyverno is a Kubernetes-native policy engine that can validate, mutate, and generate Kubernetes resources using policies written in YAML or JSON. Since Kyverno uses the Kubernetes API and YAML syntax, you can define and manage policies without learning a new language or tools.
Key Features:
- Native Kubernetes Integration: Works directly with the Kubernetes API.
- Declarative Policy Definition: Uses YAML-based declarative policies.
- Various Policy Types Supported: Supports Validate, Mutate, Generate, and Cleanup policies.
- Image Verification: Provides container image security verification capabilities.
- Auditing and Reporting: Provides auditing and reporting capabilities for policy compliance.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-labels
spec:
validationFailureAction: enforce
rules:
- name: check-team-label
match:
resources:
kinds:
- Pod
validate:
message: "label 'team' is required"
pattern:
metadata:
labels:
team: "?*"This policy requires all Pods to have a 'team' label.
Issues with Other Options:
- B. Container image scanner: While Kyverno provides image verification capabilities, its primary purpose is policy management. Dedicated image scanners include Trivy, Clair, etc.
- C. Cluster monitoring tool: Kyverno is not a monitoring tool. Prometheus, Grafana, etc. are monitoring tools.
- D. Service mesh implementation: Kyverno is not a service mesh. Istio, Linkerd, etc. are service mesh implementations.
2. Which of the following is NOT a policy type supported by Kyverno?
A. Validate B. Mutate C. Generate D. Authenticate
Show Answer
Answer: D. Authenticate
Explanation: Kyverno supports the following policy types:
- Validate: Validates that resources meet certain conditions.
- Mutate: Automatically modifies resources.
- Generate: Automatically creates additional resources when other resources are created.
- Verify Images: Verifies container image signatures.
- Cleanup: Automatically deletes resources based on certain conditions.
Kyverno does not directly support an Authentication policy type. Authentication in Kubernetes is typically handled at the API server level and managed through mechanisms such as RBAC (Role-Based Access Control), OIDC (OpenID Connect), and service accounts.
Examples of Each Policy Type:
- Validate Policy Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-resource-limits
spec:
validationFailureAction: enforce
rules:
- name: check-resource-limits
match:
resources:
kinds:
- Pod
validate:
message: "Resource limits are required"
pattern:
spec:
containers:
- resources:
limits:
memory: "?*"
cpu: "?*"- Mutate Policy Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-labels
spec:
rules:
- name: add-environment-label
match:
resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
metadata:
labels:
environment: "{{request.object.metadata.namespace}}"- Generate Policy Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: generate-networkpolicy
spec:
rules:
- name: generate-default-networkpolicy
match:
resources:
kinds:
- Namespace
generate:
kind: NetworkPolicy
name: default-deny-all
namespace: "{{request.object.metadata.name}}"
data:
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress- Verify Images Policy Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: verify-image-signatures
spec:
validationFailureAction: enforce
rules:
- name: check-image-signatures
match:
resources:
kinds:
- Pod
verifyImages:
- image: "docker.io/library/*"
repository: "docker.io/library/*"
key: |-
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8xOUetsCa8AKa9F1hx3gUw1RcyZg
rjMqwNZcDzDv3PpFtpSdwGzA1GRk7XBqDJJQa9Jekky0yvEUDjtwLFp7aw==
-----END PUBLIC KEY------ Cleanup Policy Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: cleanup-old-pods
spec:
rules:
- name: cleanup-completed-pods
match:
resources:
kinds:
- Pod
preconditions:
all:
- key: "{{request.object.status.phase}}"
operator: In
value: ["Succeeded", "Failed"]
cleanup:
ttl: "24h"Explanation of Other Options:
- A. Validate: A policy type supported by Kyverno that validates whether resources meet certain conditions.
- B. Mutate: A policy type supported by Kyverno that automatically modifies resources.
- C. Generate: A policy type supported by Kyverno that automatically creates additional resources when other resources are created.
A. Generate a warning only on policy violation B. Block resource creation or update on policy violation C. Automatically modify the resource on policy violation D. Delete the resource on policy violation
Show Answer
Answer: B. Block resource creation or update on policy violation
Explanation: In a Kyverno policy, validationFailureAction: enforce is a setting that blocks resource creation or update when a policy is violated. When this setting is applied, the policy rejects the creation or modification of resources that do not meet policy conditions and returns a policy violation message to the user.
There are two possible values for validationFailureAction:
- enforce: Blocks resource creation or update on policy violation.
- audit: Allows resource creation or update on policy violation but logs the violation. This is useful for testing policies or auditing the current state.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-probes
spec:
validationFailureAction: enforce # Block resource creation/update on policy violation
rules:
- name: check-readiness-probe
match:
resources:
kinds:
- Pod
validate:
message: "Readiness probe is required"
pattern:
spec:
containers:
- readinessProbe:
{}This policy checks that all Pod containers have a readinessProbe configured, and if not, blocks Pod creation.
How to Apply the Policy:
# Apply the policy
kubectl apply -f require-probes.yaml
# Attempt to create a Pod without a readinessProbe
kubectl apply -f pod-without-probe.yaml
# Result: Error from server: error when creating "pod-without-probe.yaml": admission webhook "validate.kyverno.svc" denied the request:
# resource Pod/default/nginx was blocked due to the following policies: require-probes: check-readiness-probe: Readiness probe is requiredIssues with Other Options:
- A. Generate a warning only on policy violation: This is the behavior of
validationFailureAction: audit. - C. Automatically modify the resource on policy violation: This is the behavior of mutate policies and is unrelated to validationFailureAction.
- D. Delete the resource on policy violation: Kyverno does not automatically delete existing resources on policy violation. Cleanup policies can delete resources based on certain conditions, but this is a different mechanism from validationFailureAction.
4. What field is used in Kyverno to select which resources a policy applies to?
A. selector B. match C. target D. apply
Show Answer
Answer: B. match
Explanation: The field used in Kyverno to select which resources a policy applies to is match. This field is used to specify the kind, name, namespace, labels, etc. of resources to which policy rules apply.
The match field can include the following subfields:
- resources: Specifies resource kind, name, namespace, etc.
- subjects: Specifies users, groups, service accounts to which the policy applies.
- roles: Specifies roles to which the policy applies.
- clusterRoles: Specifies cluster roles to which the policy applies.
Additionally, the exclude field can be used to exclude specific resources from policy application.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-labels-for-deployments
spec:
validationFailureAction: enforce
rules:
- name: check-required-labels
match:
resources:
kinds:
- Deployment
namespaces:
- "production"
- "staging"
selector:
matchLabels:
app.kubernetes.io/managed-by: kustomize
validate:
message: "Required labels are missing"
pattern:
metadata:
labels:
app.kubernetes.io/name: "?*"
app.kubernetes.io/version: "?*"
app.kubernetes.io/component: "?*"This policy applies only to Deployments in the 'production' and 'staging' namespaces that have the 'app.kubernetes.io/managed-by: kustomize' label.
Complex Matching Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: complex-matching-policy
spec:
validationFailureAction: enforce
rules:
- name: complex-match-rule
match:
resources:
kinds:
- Deployment
- StatefulSet
namespaces:
- "production"
- "staging"
selector:
matchLabels:
tier: "frontend"
subjects:
- kind: User
name: "admin@example.com"
- kind: Group
name: "system:masters"
exclude:
resources:
namespaces:
- "kube-system"
names:
- "critical-deployment"
validate:
message: "Policy validation failed"
pattern:
spec:
template:
spec:
containers:
- securityContext:
runAsNonRoot: trueThis policy applies to Deployments and StatefulSets in the 'production' and 'staging' namespaces with the 'tier: frontend' label, and only when created or modified by the 'admin@example.com' user or 'system:masters' group. Resources in the 'kube-system' namespace and resources named 'critical-deployment' are excluded.
Issues with Other Options:
- A. selector: In Kyverno, it is used as a subfield like
match.resources.selector, but is not a top-level field. - C. target: A field not used in Kyverno policies.
- D. apply: A field not used in Kyverno policies.
5. Which policy type in Kyverno automatically modifies resources on policy violation?
A. Validate B. Mutate C. Generate D. Verify
Show Answer
Answer: B. Mutate
Explanation: The policy type in Kyverno that automatically modifies resources on policy violation is Mutate. Mutate policies automatically modify resources when they are created or updated to meet policy requirements.
Mutate policies can modify resources using the following methods:
- patchStrategicMerge: Uses strategic merge patch to modify resources.
- patchesJson6902: Uses JSON patch (RFC 6902) to modify resources.
- overlay: (Legacy) A legacy field that provides the same functionality as patchStrategicMerge.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-resources
spec:
rules:
- name: add-default-cpu-memory
match:
resources:
kinds:
- Deployment
mutate:
patchStrategicMerge:
spec:
template:
spec:
containers:
- (name): "*"
resources:
limits:
memory: "{{ if hasKey .object.spec.template.spec.containers[0].resources.limits \"memory\" }}{{ .object.spec.template.spec.containers[0].resources.limits.memory }}{{ else }}512Mi{{ end }}"
cpu: "{{ if hasKey .object.spec.template.spec.containers[0].resources.limits \"cpu\" }}{{ .object.spec.template.spec.containers[0].resources.limits.cpu }}{{ else }}500m{{ end }}"
requests:
memory: "{{ if hasKey .object.spec.template.spec.containers[0].resources.requests \"memory\" }}{{ .object.spec.template.spec.containers[0].resources.requests.memory }}{{ else }}256Mi{{ end }}"
cpu: "{{ if hasKey .object.spec.template.spec.containers[0].resources.requests \"cpu\" }}{{ .object.spec.template.spec.containers[0].resources.requests.cpu }}{{ else }}250m{{ end }}"This policy adds default values if resource limits and requests are not set for containers when Deployment resources are created or updated.
Example Using JSON Patch:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-labels-json-patch
spec:
rules:
- name: add-labels
match:
resources:
kinds:
- Pod
mutate:
patchesJson6902: |-
- op: add
path: /metadata/labels/app.kubernetes.io~1managed-by
value: kyverno
- op: add
path: /metadata/labels/environment
value: "{{ request.object.metadata.namespace }}"This policy uses JSON patch to add labels to Pods.
How to Apply Mutate Policy:
# Apply the policy
kubectl apply -f add-default-resources.yaml
# Create a Deployment without resource limits
kubectl apply -f deployment-without-resources.yaml
# Check the created Deployment
kubectl get deployment my-deployment -o yaml
# Result: Resource limits and requests are automatically addedIssues with Other Options:
- A. Validate: Only validates whether resources meet policy conditions, does not modify them.
- C. Generate: Creates additional resources when other resources are created, but does not modify existing resources.
- D. Verify: A policy type that verifies container image signatures, does not modify resources.
A. Automatically create related resources when a resource is created B. Automatically generate error messages during resource validation C. Automatically create backups when a resource is deleted D. Automatically create previous versions when a resource is updated
Show Answer
Answer: A. Automatically create related resources when a resource is created
Explanation: Kyverno's Generate policy is useful for automatically creating related resources when a specific resource is created. This policy type helps manage dependencies between resources, automate standard configurations, and maintain consistent environments.
Main use cases for Generate policies:
- Create default resources when a namespace is created: Automatically create resources like NetworkPolicy, ResourceQuota, LimitRange when a namespace is created.
- Create related resources when an application is deployed: Automatically create related Service, ConfigMap, Secret when a Deployment is created.
- Automate standard configurations: Create additional resources with standard configurations when specific types of resources are created.
- Multi-tenancy environment management: Automatically create all necessary resources when a namespace is created for a new tenant.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: generate-default-networkpolicy
spec:
rules:
- name: generate-default-networkpolicy
match:
resources:
kinds:
- Namespace
exclude:
resources:
namespaces:
- "kube-system"
- "kube-public"
- "kube-node-lease"
generate:
kind: NetworkPolicy
name: default-deny-all
namespace: "{{request.object.metadata.name}}"
synchronize: true
data:
spec:
podSelector: {}
policyTypes:
- Ingress
- EgressThis policy automatically creates a default NetworkPolicy in the namespace when a new namespace is created (excluding kube-system, kube-public, kube-node-lease). This NetworkPolicy blocks all ingress and egress traffic.
synchronize field:
synchronize: true: Synchronizes the generated resource with the source resource. When the source resource is changed or deleted, the generated resource is also updated or deleted accordingly.synchronize: false: The generated resource exists independently of the source resource.
Clone Policy Example:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: clone-secrets-across-namespaces
spec:
rules:
- name: clone-docker-registry-secret
match:
resources:
kinds:
- Namespace
generate:
kind: Secret
name: docker-registry
namespace: "{{request.object.metadata.name}}"
synchronize: true
clone:
namespace: default
name: docker-registryThis policy clones the 'docker-registry' Secret from the 'default' namespace to the new namespace when a new namespace is created.
Issues with Other Options:
- B. Automatically generate error messages during resource validation: This is a feature of Validate policies.
- C. Automatically create backups when a resource is deleted: Kyverno does not provide automatic backup functionality when resources are deleted by default.
- D. Automatically create previous versions when a resource is updated: This is related to Kubernetes' resource version management mechanism and is not related to Kyverno's Generate policy.
7. What policy type is used in Kyverno to verify container image signatures?
A. ImagePolicy B. VerifyImages C. SignaturePolicy D. ImageVerification
Show Answer
Answer: B. VerifyImages
Explanation: The policy type used in Kyverno to verify container image signatures is VerifyImages. This policy type is used to confirm that container images come from trusted sources and to verify that images have not been tampered with.
VerifyImages policies provide the following features:
- Image signature verification: Verifies the integrity and origin of images using digital signatures.
- Image registry restriction: Restricts pulling images only from specific registries.
- Image tag restriction: Restricts specific tags (e.g., prohibiting latest tag usage).
- Image digest verification: Verifies image digests to ensure exact image versions are used.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: verify-image-signatures
spec:
validationFailureAction: enforce
rules:
- name: verify-signatures
match:
resources:
kinds:
- Pod
verifyImages:
- image: "docker.io/library/*"
repository: "docker.io/library/*"
key: |-
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8xOUetsCa8AKa9F1hx3gUw1RcyZg
rjMqwNZcDzDv3PpFtpSdwGzA1GRk7XBqDJJQa9Jekky0yvEUDjtwLFp7aw==
-----END PUBLIC KEY-----
- image: "ghcr.io/my-org/*"
repository: "ghcr.io/my-org/*"
roots: |-
-----BEGIN CERTIFICATE-----
MIICmTCCAj+gAwIBAgIUYzA4YTU5YjQ2OTk1MjNmMDI2OTVkMGYwDQYJKoZIhvcN
AQELBQAwXDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1TYW4g
RnJhbmNpc2NvMQ8wDQYDVQQKDAZNeU9yZzEXMBUGA1UEAwwOY2EubXlvcmcubG9j
YWwwHhcNMjMwNzIwMDAwMDAwWhcNMjQwNzE5MDAwMDAwWjBcMQswCQYDVQQGEwJV
UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xDzANBgNVBAoM
Bk15T3JnMRcwFQYDVQQDDA5jYS5teW9yZy5sb2NhbDCBnzANBgkqhkiG9w0BAQEF
AAOBjQAwgYkCgYEA1Jcpv/Gj0M3vaJQY4dLQJA9ZEMVCfOUzAFAgxm0DKJQSiQ+6
HuQFTJjHnOJwYwKSAEGYe4JUg/fMUJMKl9BM7A9gjXKe0v8JMSyYGHVqTiPZ2RuW
x7tO5Nh5jLz3GQYmZl0m7CRReY2zt9OUdRz2LR5xMPHitpy7aLGvGSsIZVECAwEA
AaN7MHkwHQYDVR0OBBYEFPgVXUQGbNrGkFmXQkCXYvs8HzIIMB8GA1UdIwQYMBaA
FPgVXUQGbNrGkFmXQkCXYvs8HzIIMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQD
AgEGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjANBgkqhkiG9w0BAQsF
AAOBgQBB3TVGvZXKpZSzqPOzQzUNnCMzMEf1I7Qx9mKIqTKSZLqHYBDxHpQRQQNy
aBBtMBgUn3KkZY8QdRUKj8Sw0PN+GV4bCXGwCJeRNZWO1FdaIVoUYKKWMPLYUUrJ
UpZXfNQO8XUjIEqBK8RGn3MwYYwRF+OjDHGvpOf6hk0XPHGjlQ==
-----END CERTIFICATE-----This policy verifies signatures for two image sources:
- docker.io/library/* images are verified using the specified public key.
- ghcr.io/my-org/* images are verified using the specified certificate.
Image Signing Tools: Kyverno integrates with various image signing tools:
- Cosign: Part of the Sigstore project, a tool for signing and verifying container images.
- Notary: Docker's content trust framework.
- GnuPG (GPG): Open-source encryption tool.
Example of Image Signing and Verification Using Cosign:
# Generate key pair
cosign generate-key-pair
# Sign the image
cosign sign --key cosign.key my-registry.io/my-image:tag
# Extract public key to use in Kyverno policy
cat cosign.pubIssues with Other Options:
- A. ImagePolicy: A policy type not used in Kyverno.
- C. SignaturePolicy: A policy type not used in Kyverno.
- D. ImageVerification: A policy type not used in Kyverno.
8. What does the background: false setting mean in a Kyverno policy?
A. The policy does not run in the background B. The policy does not apply to existing resources C. The policy does not affect cluster background jobs D. The policy does not apply to resources created by background processes
Show Answer
Answer: B. The policy does not apply to existing resources
Explanation: The background: false setting in a Kyverno policy means that the policy does not apply to existing resources and only applies to newly created or updated resources. The default value is background: true, in which case the policy applies to all resources including existing ones.
Key characteristics of the background setting:
- Existing resource scanning: When
background: true, Kyverno periodically scans existing resources in the cluster to check policy compliance. - Resource load: Scanning many resources in large clusters can cause significant load, so it's better to use
background: trueonly when necessary. - Audit reports: Background scan results are recorded in PolicyReport and ClusterPolicyReport CRDs.
- Scope: Even when
background: false, the policy still acts as an Admission Controller and applies to newly created or updated resources.
Example Policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-labels
spec:
validationFailureAction: enforce
background: false # Does not apply to existing resources
rules:
- name: check-team-label
match:
resources:
kinds:
- Pod
validate:
message: "label 'team' is required"
pattern:
metadata:
labels:
team: "?*"This policy applies only to newly created or updated Pods and does not scan existing Pods.
When background scanning is needed:
- Compliance auditing: When you need to regularly check that all resources in the cluster comply with policies
- Security policy enforcement: When you need to continuously monitor and report security vulnerabilities
- Configuration drift detection: When you need to detect whether resource configurations deviate from policies over time
When background scanning is not needed:
- Performance optimization: When you need to minimize resource usage in large clusters
- Managing only new resources: When you want to leave existing resources as-is and only have new resources comply with policies
- Gradual policy introduction: When you want to apply policies only to new workloads without affecting existing workloads
Issues with Other Options:
- A. The policy does not run in the background: This is a misinterpretation of the
backgroundsetting. All Kyverno policies act as Admission Controllers. - C. The policy does not affect cluster background jobs: This is unrelated to the
backgroundsetting. - D. The policy does not apply to resources created by background processes: This is unrelated to the
backgroundsetting. Policies apply regardless of what process created the resource.
A. PolicyViolation B. PolicyReport C. ComplianceReport D. AuditReport
Show Answer
Answer: B. PolicyReport
Explanation: The resources used in Kyverno to generate policy violation reports are PolicyReport and ClusterPolicyReport. These resources are used to store and report policy check results.
Key characteristics of PolicyReport and ClusterPolicyReport:
Scope:
PolicyReport: Reports policy check results for resources within a specific namespace.ClusterPolicyReport: Reports policy check results for cluster-level resources.
Generation method:
- Background scan: Policies with
background: trueperiodically scan resources and record results in reports. - Admission checks: Policy check results performed during resource creation or update are also recorded in reports.
- Background scan: Policies with
Report contents:
- Policy name
- Scanned resource
- Result (pass, fail, warn, error, skip)
- Message
- Severity
- Category
- Timestamp
Example PolicyReport:
apiVersion: wgpolicyk8s.io/v1alpha2
kind: PolicyReport
metadata:
name: polr-ns-default
namespace: default
summary:
pass: 7
fail: 3
warn: 0
error: 0
skip: 0
results:
- policy: require-labels
rule: check-team-label
resource:
kind: Pod
name: nginx
namespace: default
status: fail
message: "label 'team' is required"
severity: medium
category: Best Practices
timestamp:
created: "2023-07-20T10:15:30Z"
- policy: require-probes
rule: check-readiness-probe
resource:
kind: Pod
name: nginx
namespace: default
status: pass
timestamp:
created: "2023-07-20T10:15:30Z"How to Query Reports:
# Query namespace policy reports
kubectl get policyreport -n default
# Query cluster policy reports
kubectl get clusterpolicyreport
# Query specific report details
kubectl describe policyreport polr-ns-default -n defaultPolicy Report Integration: Kyverno's policy reports follow the PolicyReport CRD specification defined by the Kubernetes Policy Working Group. This allows results from various policy engines (Kyverno, OPA Gatekeeper, etc.) to be reported in a consistent format.
How to Use Reports:
- Compliance monitoring: Continuously monitor the policy compliance status of the cluster.
- Audit evidence: Provide evidence needed for compliance audits.
- Troubleshooting: Help identify and resolve policy violations.
- Trend analysis: Analyze policy compliance trends over time.
Issues with Other Options:
- A. PolicyViolation: A resource type not used in Kyverno.
- C. ComplianceReport: A resource type not used in Kyverno.
- D. AuditReport: A resource type not used in Kyverno.
10. What command-line tool can be used to test policies in Kyverno?
A. kyverno-cli B. kubectl-kyverno C. kyverno-test D. policy-test
Show Answer
Answer: B. kubectl-kyverno
Explanation: The command-line tool that can be used to test policies in Kyverno is kubectl-kyverno. This tool works as a kubectl plugin and helps test, validate, and manage Kyverno policies.
Key features of kubectl-kyverno:
- Policy testing: Simulates policy application results against resources.
- Policy validation: Validates policy syntax and structure.
- Policy generation: Generates policy templates for common use cases.
- Policy application: Applies policies to the cluster.
Installation Method:
# Installation using krew
kubectl krew install kyverno
# Direct download and installation
curl -L https://github.com/kyverno/kyverno/releases/download/v1.10.0/kubectl-kyverno_v1.10.0_linux_x86_64.tar.gz | tar -xvz
sudo mv kubectl-kyverno /usr/local/bin/Key Commands:
- Policy testing:
# Test policy application against a resource
kubectl kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml
# Test multiple policies
kubectl kyverno apply /path/to/policies/ --resource /path/to/resources/
# Check mutation results
kubectl kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml -o yaml- Policy validation:
# Validate policy syntax and structure
kubectl kyverno validate /path/to/policy.yaml- Policy generation:
# Generate a common policy template
kubectl kyverno create disallow-latest-tag
# Check available template list
kubectl kyverno create --help- Policy application:
# Apply policy to the cluster
kubectl kyverno apply /path/to/policy.yaml --clusterTest Example:
# Create policy file
cat > require-labels.yaml << EOF
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-labels
spec:
validationFailureAction: enforce
rules:
- name: check-team-label
match:
resources:
kinds:
- Pod
validate:
message: "label 'team' is required"
pattern:
metadata:
labels:
team: "?*"
EOF
# Create resource file
cat > pod.yaml << EOF
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- name: nginx
image: nginx:1.19.0
EOF
# Test the policy
kubectl kyverno apply require-labels.yaml --resource pod.yaml
# Result:
# applying 1 policy to 1 resource...
# resource Pod/default/nginx failed validation
# policy require-labels: rule check-team-label failed: label 'team' is requiredUsage in CI/CD Pipeline:
# GitHub Actions example
name: Kyverno Policy Test
on:
pull_request:
paths:
- 'policies/**'
- 'resources/**'
jobs:
test-policies:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Install kubectl-kyverno
run: |
curl -L https://github.com/kyverno/kyverno/releases/download/v1.10.0/kubectl-kyverno_v1.10.0_linux_x86_64.tar.gz | tar -xvz
sudo mv kubectl-kyverno /usr/local/bin/
- name: Validate policies
run: |
kubectl kyverno validate policies/
- name: Test policies against resources
run: |
kubectl kyverno apply policies/ --resource resources/Issues with Other Options:
- A. kyverno-cli: A tool name not used in Kyverno.
- C. kyverno-test: A tool name not used in Kyverno.
- D. policy-test: A tool name not used in Kyverno.