### Run KCL Operator Unit Tests Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Provides common commands for running unit tests for the KCL Operator using Go and Make. It includes examples for running all tests with coverage and for targeting specific packages, along with expected output formats. ```bash # Run all tests with coverage make test # Expected output: # KUBEBUILDER_ASSETS=".../bin" go test ./... -coverprofile cover.out # ? kcl-lang.io/kcl-operator/api/kclrun/v1alpha1 [no test files] # ok kcl-lang.io/kcl-operator/pkg/webhook/handler 2.145s coverage: 78.9% of statements # ? kcl-lang.io/kcl-operator/cmd/webhook-server [no test files] # Run tests for specific package go test -v ./pkg/webhook/handler/... # Expected output: # === RUN TestMutationHandler_Mutate # === RUN TestMutationHandler_Mutate/successful_mutation # === RUN TestMutationHandler_Mutate/no_KCLRun_found # --- PASS: TestMutationHandler_Mutate (0.05s) # --- PASS: TestMutationHandler_Mutate/successful_mutation (0.03s) # --- PASS: TestMutationHandler_Mutate/no_KCLRun_found (0.01s) # PASS # ok kcl-lang.io/kcl-operator/pkg/webhook/handler 2.145s ``` -------------------------------- ### Create KCLRun from OCI Registry (Bash) Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Applies a KCLRun custom resource definition from a YAML snippet that sources a KCL module from an OCI registry. This example demonstrates deploying annotation injection from a remote module. ```bash # Deploy annotation injection from OCI registry kubectl apply -f- << EOF apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: set-annotation namespace: default spec: params: annotations: managed-by: kcl-operator environment: production source: oci://ghcr.io/kcl-lang/set-annotation EOF # Verify KCLRun is created kubectl get kclruns # Expected output: # NAME AGE # set-annotation 5s ``` -------------------------------- ### Inline KCL for Conditional Mutations (YAML) Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Defines a KCLRun custom resource with inline KCL source code for complex conditional mutations. This example demonstrates adding labels based on resource names and annotations based on replica counts. ```yaml apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: conditional-mutation namespace: default spec: source: | items = [ item | { metadata.labels: { "tier" = "backend" if item.metadata.name.startswith("api-") "tier" = "frontend" if item.metadata.name.startswith("web-") } metadata.annotations: { "auto-scaled" = "true" if item.spec.replicas > 3 } } for item in option("items") ] ``` -------------------------------- ### Define KCLRun Custom Resource for Annotations (YAML) Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Defines a KCLRun custom resource to add a 'managed-by' annotation to Kubernetes resources. This example uses inline KCL source to specify the mutation logic. ```yaml apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: set-annotation namespace: default spec: source: | items = [item | { metadata.annotations: {"managed-by" = "kcl-operator"} } for item in option("items")] ``` -------------------------------- ### Build and Deploy Webhook Server with Make and Docker Source: https://context7.com/kcl-lang/kcl-operator/llms.txt This section details the commands for building the webhook server binary using `make webhook`, creating a Docker image with `docker build`, and deploying the server to Kubernetes using `make deploy`. It also includes instructions for checking server logs. Proper TLS configuration is required for deployment. ```bash # Build webhook server binary make webhook # Output: Builds cmd/webhook-server/main.go and cmd/webhook-init/main.go # Build Docker image docker build -t kcllang/webhook-server:latest -f docker/Dockerfile . # Deploy to Kubernetes with custom image export IMG=kcllang/webhook-server:v0.2.0 make deploy # Check webhook server logs kubectl logs -l app=webhook-server --follow # Expected output: # INFO[0000] Setup a manager # INFO[0001] Webhook server Listening on :8081 # INFO[0002] Get the KCL source list.. # INFO[0003] Mutating using KCL.. # INFO[0004] Mutate using KCL finished. ``` -------------------------------- ### Register Webhook Configuration with Go Source: https://context7.com/kcl-lang/kcl-operator/llms.txt The `webhook-init` container programmatically registers a `MutatingWebhookConfiguration` with the Kubernetes API. This Go code defines the webhook's behavior, including its name, client configuration (with CA bundle and service reference), rules for resource matching, and failure policy. It requires a Kubernetes client and CA bundle data as input. ```go // Example of what webhook-init does programmatically package main import ( "context" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) func registerWebhook(kubeClient *kubernetes.Clientset, caBundle []byte) error { path := "/mutate" fail := admissionregistrationv1.Fail sideEffectClassNone := admissionregistrationv1.SideEffectClassNone mutateConfig := &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ Name: "kcl-mutating-webhook", }, Webhooks: []admissionregistrationv1.MutatingWebhook{{ Name: "kcl-webhook-server.krm.kcl.dev", ClientConfig: admissionregistrationv1.WebhookClientConfig{ CABundle: caBundle, Service: &admissionregistrationv1.ServiceReference{ Name: "webhook-service", Namespace: "default", Path: &path, }, }, Rules: []admissionregistrationv1.RuleWithOperations{{ Operations: []admissionregistrationv1.OperationType{ admissionregistrationv1.Create, }, Rule: admissionregistrationv1.Rule{ APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "pods"}, }, }}, SideEffects: &sideEffectClassNone, AdmissionReviewVersions: []string{"v1", "v1beta1"}, FailurePolicy: &fail, }}, } _, err := kubeClient.AdmissionregistrationV1(). MutatingWebhookConfigurations(). Create(context.Background(), mutateConfig, metav1.CreateOptions{}) return err } ``` -------------------------------- ### Deploy KCL Operator and Verify (Bash) Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Commands to deploy the KCL Operator to a Kubernetes cluster using `make deploy` and verify its components are running. It also shows how to check the created `mutatingwebhookconfigurations`. ```bash # Deploy the operator components make deploy # Verify the webhook server is running kubectl get pods # Expected output: # NAME READY STATUS RESTARTS AGE # webhook-server-xxxx 1/1 Running 0 30s # Check webhook configuration kubectl get mutatingwebhookconfigurations # Expected output: # NAME WEBHOOKS AGE # kcl-mutating-webhook 1 30s ``` -------------------------------- ### Read KCL Options and Parameters Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Demonstrates how to access input resources and parameters from the KCL execution context within a KCLRun resource. It shows how to retrieve parameters like 'team' and 'cost-center' and apply them to resource labels. ```kcl apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: parameterized-mutation namespace: default spec: params: team: "platform-engineering" cost-center: "engineering-123" environment: "staging" source: | # Access parameters params = option("params") # Access input resources items = [item | { metadata.labels: { "team" = params.team "cost-center" = params["cost-center"] "env" = params.environment } } for item in option("items")] ``` -------------------------------- ### Apply Resource and Observe Annotations (Bash) Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Applies a Kubernetes Pod resource and then uses `kubectl` commands to retrieve and display the mutated annotations, including those added by the KCL operator. ```bash # Create a pod that will be mutated kubectl apply -f- << EOF apiVersion: v1 kind: Pod metadata: name: nginx namespace: default annotations: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 EOF # Check the mutated annotations kubectl get pod nginx -o yaml | grep -A 5 "annotations:" # Expected output: # annotations: # app: nginx # environment: production # managed-by: kcl-operator # View full pod specification kubectl get pod nginx -o jsonpath='{.metadata.annotations}' | jq # Expected output: # { # "app": "nginx", # "environment": "production", # "managed-by": "kcl-operator" # } ``` -------------------------------- ### Validate Resources using KCL Assertions Source: https://context7.com/kcl-lang/kcl-operator/llms.txt This KCL script demonstrates how to use assertions to validate Kubernetes resources. It defines rules for `Deployment` and `Pod` resources, ensuring that replica counts are within a specified range and that the number of containers in a pod does not exceed a limit. The `items` variable is expected to be provided as an option, containing the resources to be validated. ```yaml apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: validate-resources namespace: default spec: source: | items = option("items") # Validate each resource [assert item.spec.replicas >= 2 and item.spec.replicas <= 10, "Replicas must be between 2 and 10" for item in items if item.kind == "Deployment"] [assert len(item.spec.containers) <= 5, "Maximum 5 containers allowed per pod" for item in items if item.kind == "Pod"] items ``` -------------------------------- ### Deploy KCL Source as KCLRun Source: https://github.com/kcl-lang/kcl-operator/blob/main/README.md Applies a KCLRun resource to the cluster, specifying a KCL source from an OCI registry. This allows for custom resource mutations or validations defined in the KCL script. ```yaml apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: set-annotation spec: params: annotations: managed-by: kcl-operator source: oci://ghcr.io/kcl-lang/set-annotation ``` -------------------------------- ### Deploy KCL Operator Source: https://github.com/kcl-lang/kcl-operator/blob/main/README.md Deploys the KCL Operator to the Kubernetes cluster using a make command. It is recommended to verify the pod status is 'Running' after deployment. ```shell make deploy kubectl get po ``` -------------------------------- ### Process KCL Resources with Go MutationHandler Source: https://context7.com/kcl-lang/kcl-operator/llms.txt The MutationHandler in Go processes admission requests by executing KCL scripts. It lists KCLRun resources and iterates through them to apply mutations based on the provided KCL source. This functionality is essential for dynamic resource modification within the Kubernetes cluster. ```go package main import ( "context" "fmt" "k8s.io/apimachinery/pkg/runtime" krmkcldevv1alpha1 "kcl-lang.io/kcl-operator/api/kclrun/v1alpha1" "sigs.k8s.io/controller-runtime/pkg/client" ) // Example usage of MutationHandler func mutateResource(ctx context.Context, client client.Client) error { // Fetch all KCLRun resources in namespace kclRunList := &krmkcldevv1alpha1.KCLRunList{} err := client.List(ctx, kclRunList, client.InNamespace("default")) if err != nil { return fmt.Errorf("failed to list KCLRun resources: %w", err) } // Process each KCLRun configuration for _, kclRun := range kclRunList.Items { fmt.Printf("Processing KCLRun: %s\n", kclRun.Name) fmt.Printf("Source: %s\n", kclRun.Spec.Source) // The webhook handler executes the KCL source against incoming resources // Output: Resource mutations based on KCL logic } return nil } ``` -------------------------------- ### Validate Mutation Result with Pod Creation Source: https://github.com/kcl-lang/kcl-operator/blob/main/README.md Creates a Kubernetes Pod and then validates if the mutation performed by the KCL Operator (e.g., adding an annotation) has been applied by inspecting the Pod's YAML output. ```shell kubectl apply -f- << EOF apiVersion: v1 kind: Pod metadata: name: nginx annotations: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 EOF kubectl get po nginx -o yaml | grep kcl-operator ``` -------------------------------- ### Generate Multiple Kubernetes Resources Source: https://context7.com/kcl-lang/kcl-operator/llms.txt Illustrates how to generate multiple distinct Kubernetes resources, such as ConfigMaps and Secrets, from a single KCL configuration within a KCLRun resource. This is useful for defining related resources declaratively. ```kcl apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: generate-resources namespace: default spec: source: | items = [ { apiVersion: "v1" kind: "ConfigMap" metadata.name = "app-config" data = { "database.url" = "postgres://db:5432" "cache.enabled" = "true" } }, { apiVersion: "v1" kind: "Secret" metadata.name = "app-secret" type = "Opaque" stringData = { "api-key" = "placeholder" } } ] ``` -------------------------------- ### KCLRun with Items Output Source: https://github.com/kcl-lang/kcl-operator/blob/main/README.md Defines a KCLRun resource where the KCL script generates a list of Kubernetes resources (KRM objects) under the 'items' field. This is a common way to generate multiple resources. ```yaml apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: basic spec: source: | items = [{ apiVersion: "v1" kind: "Foo" metadata.name = "foo" }, { apiVersion: "v1" kind: "Bar" metadata.name = "bar" }] ``` -------------------------------- ### KCLRun with Single YAML Output Source: https://github.com/kcl-lang/kcl-operator/blob/main/README.md Defines a KCLRun resource where the KCL script generates a single Kubernetes resource directly. This is used when only one resource needs to be produced by the KCL script. ```yaml apiVersion: krm.kcl.dev/v1alpha1 kind: KCLRun metadata: name: basic spec: source: | { apiVersion: "v1" kind: "Foo" metadata.name = "foo" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.