### Install Kclipper with Homebrew (Bash) Source: https://github.com/macropower/kclipper/blob/main/README.md Installs the Kclipper tool, which includes the 'kcl' and 'kcl-language-server' binaries, using the Homebrew package manager. This command taps the necessary repository and then installs the package. ```bash brew tap macropower/tap brew install macropower/tap/kclipper kcl version kcl-language-server version ``` -------------------------------- ### Install Minio Helm Chart Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/README.md Installs the Minio Helm chart in its default configuration on a Kubernetes cluster. This command utilizes the Helm package manager to deploy Minio. ```bash helm install stable/minio ``` -------------------------------- ### Install Redis with Helm and Values File Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/redis/README.md This command shows how to install a Redis release using Helm by providing a YAML file containing configuration values. This is an alternative to using the `--set` flag for multiple parameters. ```bash helm install --name my-release -f values.yaml stable/redis ``` -------------------------------- ### KCL Configuration Example Source: https://github.com/macropower/kclipper/blob/main/docs/helm_extensions.md This snippet demonstrates a basic KCL configuration for setting the number of replicas. It highlights the precedence of `values` over `valueFiles`. ```kcl replicas: 3 ``` -------------------------------- ### Install Redis using Helm Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/redis/README.md Installs the Redis chart on a Kubernetes cluster using Helm. Supports default and production configurations. Requires Kubernetes 1.8+ and PV provisioner support. ```bash # Testing configuration $ helm install stable/redis ``` ```bash # Production configuration $ helm install stable/redis --values values-production.yaml ``` ```bash # Install with a release name $ helm install --name my-release stable/redis ``` -------------------------------- ### Helm Install Minio with Persistence (Bash) Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/README.md Deploys a Minio server using Helm, specifying the persistent volume size. This command utilizes the `--set` argument to override default chart values. ```bash helm install --name my-release \ --set persistence.size=100Gi \ stable/minio ``` -------------------------------- ### Example Exported JSON Schema and Usage Source: https://context7.com/macropower/kclipper/llms.txt This section demonstrates an example of a JSON Schema exported from KCL and how it can be used for validation within a CI/CD workflow or with tools like yamllint. The schema defines the structure and types for a Kubernetes configuration. ```json # Example: exported JSON Schema cat podinfo-values.schema.json # Output: # { # "$schema": "http://json-schema.org/draft-07/schema#", # "type": "object", # "properties": { # "replicaCount": { # "type": "integer", # "description": "Number of replicas" # }, # "image": { # "type": "object", # "properties": { # "repository": {"type": "string"}, # "tag": {"type": "string"}, # "pullPolicy": {"type": "string"} # } # }, # "service": { # "type": "object", # "properties": { # "enabled": {"type": "boolean"}, # "type": {"type": "string"} # } # } # } # } # Use exported schema in CI/CD for validation cat > values-prod.yaml <:'. ```bash {{- else if contains "NodePort" .Values.service.type }} export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "simple-chart.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT {{- end }} ``` -------------------------------- ### Get Application URL with LoadBalancer Service Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/simple-chart/templates/NOTES.txt Fetches the application URL for a LoadBalancer service. It notes that the LoadBalancer IP may take time to become available and provides a command to monitor its status. Outputs the URL as 'http://:'. ```bash {{- else if contains "LoadBalancer" .Values.service.type }} NOTE: It may take a few minutes for the LoadBalancer IP to be available. You can watch its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "simple-chart.fullname" . }}' export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "simple-chart.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}) echo http://$SERVICE_IP:{{ .Values.service.port }} {{- end }} ``` -------------------------------- ### Render Helm Chart with `helm` Package and Patching (Python) Source: https://github.com/macropower/kclipper/blob/main/docs/helm_extensions.md Uses the `helm` package (after installation) to render a Helm chart. It defines chart details including values, value files, and a `postRenderer` lambda for patching resources. The output is then streamed as YAML. ```python import helm import regex import manifests _podinfo = helm.template(helm.Chart { chart = "podinfo" repoURL = "https://stefanprodan.github.io/podinfo" targetRevision = "6.7.0" valueFiles = [ "values.yaml", "values-prod.yaml" ] values = { replicaCount = 3 } postRenderer = lambda resource: {str:} -> {str:} { if regex.match(resource.metadata.name, "^podinfo-service-test-.*$"): resource.metadata.annotations |= {"example.com/added" = "by kcl patch"} resource } }) manifests.yaml_stream(_podinfo) ``` -------------------------------- ### Render Helm Chart to Kubernetes Resources (Python) Source: https://github.com/macropower/kclipper/blob/main/docs/helm_extensions.md Executes `helm template` to get Kubernetes resources from a chart. It uses Argo CD's Helm source on the backend for speed, especially after caching. Accepts chart name, revision, and repository URL as input, returning a list of Kubernetes resource objects. ```python import helm helm.template( chart="example", target_revision="0.1.0", repo_url="https://example.com/charts", ) # -> [{"group": "apps", "kind": "Deployment", ...}, ...] ``` -------------------------------- ### File Path Manipulation with kcl/filepath and file Source: https://github.com/macropower/kclipper/blob/main/modules/filepath/README.md Python example demonstrating how to use the filepath module to construct a path relative to the current file and read its content using the file module. It utilizes functions like `dir`, `join`, and `file.read`. ```python import file import filepath _current_dir = filepath.dir(file.current()) _example_path = filepath.join([_current_dir, "data", "example.json"]) example_data = file.read(_example_path) ``` -------------------------------- ### Patch Templated Helm Resources with KCL Lambda (Python) Source: https://github.com/macropower/kclipper/blob/main/docs/helm_extensions.md Demonstrates how to fetch Helm chart resources and then apply a KCL lambda function to patch specific resources. The example filters resources by name and adds an annotation. This requires the `regex` and `kcl_plugin.helm` modules. ```python import regex import kcl_plugin.helm import manifests _chart = helm.template( chart="example", target_revision="0.1.0", repo_url="https://example.com/charts", values={ replicas = 3 } ) patch = lambda resource: {str:} -> {str:} { if regex.match(resource.metadata.name, "^example-.*$"): resource.metadata.annotations |= {"example.com/added" = "by kcl patch"} resource } manifests.yaml_stream( [patch(r) for r in _chart] ) ``` -------------------------------- ### Declarative Helm Chart Configuration with KCL Source: https://context7.com/macropower/kclipper/llms.txt Defines Helm chart configurations declaratively using KCL. This includes settings for schema generation, CRD generation, validation, and repository configurations. Examples demonstrate various configurations like auto schema generation, value inference, and CRD generation from templates or chart files. ```kcl import helm # Complete chart configuration examples charts: helm.Charts = { # Simple chart with auto schema generation podinfo: { chart = "podinfo" repoURL = "https://stefanprodan.github.io/podinfo" targetRevision = "6.7.0" schemaGenerator = "AUTO" schemaValidator = "KCL" } # Chart with value inference from values.yaml files simple_chart: { chart = "simple-chart" repoURL = "@local" repositories = [repos.local] schemaGenerator = "VALUE-INFERENCE" valueInference = { keepFullComment = True dontRemoveHelmDocsPrefix = False } } # Chart with CRD generation from template output external_secrets: { chart = "external-secrets" repoURL = "https://charts.external-secrets.io/" targetRevision = "0.14.3" schemaGenerator = "AUTO" crdGenerator = "TEMPLATE" values = { installCRDs = True crds = { createClusterExternalSecret = False createClusterGenerator = False createClusterSecretStore = False createPushSecret = True } } } # Chart with CRD generation from chart files kube_prometheus_stack: { chart = "kube-prometheus-stack" repoURL = "https://prometheus-community.github.io/helm-charts" targetRevision = "69.8.2" schemaGenerator = "AUTO" crdGenerator = "CHART-PATH" crdPaths = ["**/crds/crds/*.yaml"] } # Chart from private repository with custom schema path app_template: { chart = "app-template" repoURL = "@bjw-s" targetRevision = "3.6.0" schemaGenerator = "CHART-PATH" schemaPath = "charts/common/values.schema.json" schemaValidator = "KCL" repositories = [repos.bjw_s] } } # Repository configuration repos: helm.ChartRepos = { local: { name = "local" url = "./local-charts/" } bjw_s: { name = "bjw-s" url = "https://bjw-s.github.io/helm-charts/" } chartmuseum: { name = "chartmuseum" url = "http://localhost:8080" usernameEnv = "CHARTMUSEUM_USER" passwordEnv = "CHARTMUSEUM_PASS" } private_oci: { name = "private-oci" url = "oci://registry.example.com/charts" usernameEnv = "REGISTRY_USER" passwordEnv = "REGISTRY_PASS" insecureSkipVerify = False } } ``` -------------------------------- ### Initialize KCL Project Source: https://github.com/macropower/kclipper/blob/main/README.md Initializes a new KCL project, creating essential configuration files like kcl.mod. This command sets up the basic structure for a KCL project. ```bash kcl mod init ``` -------------------------------- ### Initialize KCL Charts Package Source: https://github.com/macropower/kclipper/blob/main/README.md Initializes a new 'charts' package within the KCL project. This prepares the project to manage Helm charts. ```bash kcl chart init ``` -------------------------------- ### Initialize KCL Charts Package using kcl chart init Source: https://context7.com/macropower/kclipper/llms.txt Initializes a new Helm charts package within a KCL project. This command sets up the necessary directory structure and configuration files, including `charts.k` for chart declarations, `kcl.mod`, and `kcl.mod.lock`. ```bash # Initialize a new KCL project kcl mod init # Initialize the charts package kcl chart init # Result: Creates the following structure # . # ├── charts # │ ├── charts.k # Chart declarations # │ ├── kcl.mod # Package manifest # │ └── kcl.mod.lock # Locked dependencies # ├── main.k # ├── kcl.mod # └── kcl.mod.lock # The charts.k file contains: cat charts/charts.k # Output: # import helm # # charts: helm.Charts = {} ``` -------------------------------- ### Set Helm Chart Property via CLI Source: https://github.com/macropower/kclipper/blob/main/README.md Uses the KCL CLI to set a specific property of a Helm chart. This example updates the 'targetRevision' for the 'podinfo' chart to '6.7.1'. ```bash kcl chart set -c podinfo -O targetRevision=6.7.1 ``` -------------------------------- ### Connect to MinIO and Wait for Availability (Shell) Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/templates/_helper_create_bucket.txt This function, `connectToMinio`, establishes a connection to a MinIO server. It employs a loop with a defined limit to repeatedly attempt connection until successful or the limit is reached. It reads MinIO access and secret keys from files and configures the `mc` client. Dependencies include `mc` CLI and environment variables `MINIO_ENDPOINT` and `MINIO_PORT`. It returns 0 on success and exits with 1 on failure after exceeding attempts. ```shell #!/bin/sh set -e ; # Have script exit in the event of a failed command. # connectToMinio # Use a check-sleep-check loop to wait for Minio service to be available connectToMinio() { ATTEMPTS=0 ; LIMIT=29 ; # Allow 30 attempts set -e ; # fail if we can't read the keys. ACCESS=$(cat /config/accesskey) ; SECRET=$(cat /config/secretkey) ; set +e ; # The connections to minio are allowed to fail. echo "Connecting to Minio server: http://$MINIO_ENDPOINT:$MINIO_PORT" ; MC_COMMAND="mc config host add myminio http://$MINIO_ENDPOINT:$MINIO_PORT $ACCESS $SECRET" ; $MC_COMMAND ; STATUS=$? ; until [ $STATUS = 0 ] do ATTEMPTS=`expr $ATTEMPTS + 1` ; echo "Failed attempts: $ATTEMPTS" ; if [ $ATTEMPTS -gt $LIMIT ]; then exit 1 ; fi ; sleep 2 ; # 1 second intervals between attempts $MC_COMMAND ; STATUS=$? ; done ; set -e ; # reset `e` as active return 0 } ``` -------------------------------- ### Execute MinIO Operations using Helm Values (Shell) Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/templates/_helper_create_bucket.txt This snippet demonstrates the execution of MinIO operations within a shell script, likely used in a Kubernetes Helm chart context. It first calls `connectToMinio` to ensure the MinIO client is ready. Then, it calls `createBucket` with parameters dynamically populated from Helm template values, specifically `.Values.defaultBucket.name`, `.Values.defaultBucket.policy`, and `.Values.defaultBucket.purge`. This allows for configurable bucket creation and management during Helm deployments. ```shell # Try connecting to Minio instance connectToMinio # Create the bucket createBucket {{ .Values.defaultBucket.name }} {{ .Values.defaultBucket.policy }} {{ .Values.defaultBucket.purge }} ``` -------------------------------- ### Manage KCL Chart Packages Programmatically with Go API Source: https://context7.com/macropower/kclipper/llms.txt This Go API allows for the programmatic management of KCL chart packages. It supports creating packages with various configurations, subscribing to events, initializing the package, adding/updating charts and repositories, setting chart properties, and regenerating schemas. Dependencies include Kubernetes API machinery and the kclipper/kclipper packages. ```go package main import ( "log" "time" "k8s.io/apimachinery/pkg/api/resource" "github.com/macropower/kclipper/pkg/chartcmd" "github.com/macropower/kclipper/pkg/helm" "github.com/macropower/kclipper/pkg/kclmodule/kclhelm" ) func main() { // Create a Helm client client := helm.DefaultClient // Create a KCL package manager with options maxSize := resource.MustParse("50Mi") pkg, err := chartcmd.NewKCLPackage( ".", client, chartcmd.WithVendor(false), chartcmd.WithFastEval(true), chartcmd.WithTimeout(10*time.Minute), chartcmd.WithMaxExtractSize(&maxSize), ) if err != nil { log.Fatalf("Failed to create package: %v", err) } // Subscribe to events pkg.Subscribe(func(evt any) { switch e := evt.(type) { case chartcmd.EventChartAdded: log.Printf("Chart added: %s", e.Key) case chartcmd.EventChartUpdated: log.Printf("Chart updated: %s", e.Key) case chartcmd.EventRepoAdded: log.Printf("Repository added: %s", e.Name) } }) // Initialize if needed created, err := pkg.Init() if err != nil { log.Fatalf("Failed to init: %v", err) } if created { log.Println("Created new charts package") } // Add a chart chartConfig := kclhelm.ChartConfig{ ChartBase: kclhelm.ChartBase{ Chart: "podinfo", RepoURL: "https://stefanprodan.github.io/podinfo", TargetRevision: "6.7.0", }, SchemaGenerator: "AUTO", SchemaValidator: "KCL", } err = pkg.AddChart("podinfo", chartConfig) if err != nil { log.Fatalf("Failed to add chart: %v", err) } log.Println("Chart added successfully") // Add a repository repo := kclhelm.ChartRepo{ Name: "bitnami", URL: "https://charts.bitnami.com/bitnami", UsernameEnv: "", PasswordEnv: "", } err = pkg.AddRepo(repo) if err != nil { log.Fatalf("Failed to add repo: %v", err) } log.Println("Repository added successfully") // Update all charts err = pkg.Update() if err != nil { log.Fatalf("Failed to update: %v", err) } log.Println("All charts updated successfully") // Set a chart property overrides := []string{"targetRevision=6.7.1"} err = pkg.Set("podinfo", overrides) if err != nil { log.Fatalf("Failed to set: %v", err) } log.Println("Chart configuration updated") // Update after changing configuration err = pkg.Update("podinfo") if err != nil { log.Fatalf("Failed to update podinfo: %v", err) } log.Println("Podinfo schemas regenerated") } ``` -------------------------------- ### Add Helm Repository via CLI Source: https://github.com/macropower/kclipper/blob/main/README.md Command to add a Helm repository to the KCLIpper project. It takes the repository name, URL, and optional basic authentication credentials. The repository is stored in the repos.k file. ```bash kcl chart repo add -n chartmuseum -u http://localhost:8080 -U BASIC_AUTH_USER -P BASIC_AUTH_PASS ``` -------------------------------- ### Render Helm Charts with KCL and Post-Rendering Logic Source: https://github.com/macropower/kclipper/blob/main/README.md This snippet demonstrates how to use KCL to render Helm charts, including specifying value files, defining chart values, and applying post-rendering logic to modify resources. It imports necessary KCL modules for helm, manifests, regex, and specific chart APIs. ```kcl import helm import manifests import regex import charts.podinfo import charts.kube_prometheus_stack.api.v1 as prometheusv1 env = option("env") _podinfo = helm.template(podinfo.Chart { valueFiles = [ "values.yaml", "values-${env}.yaml", ] values = podinfo.Values { replicaCount = 3 } postRenderer = lambda resource: {str:} -> {str:} { if regex.match(resource.metadata.name, "^podinfo-service-test-.*$"): resource.metadata.annotations |= {"example.com/added" = "by kcl patch"} resource } }) _serviceMonitor = prometheusv1.ServiceMonitor { metadata.name = "podinfo" spec.selector.matchLabels = { app = "podinfo" } } manifests.yaml_stream([*_podinfo, _serviceMonitor]) ``` -------------------------------- ### Directly Invoke Helm Plugin for Chart Rendering with Python Source: https://context7.com/macropower/kclipper/llms.txt This Python code demonstrates the direct invocation of the KCL Helm plugin, bypassing the typical helm.template() wrapper. It allows for detailed configuration of Helm chart rendering, including chart name, repository URL, revision, release name, namespace, and various options like skipping CRDs/hooks and schema validation. It also shows how to pass credentials and specify repository details and values. The plugin respects Argo CD environment variables for execution context. ```python import kcl_plugin.helm # Direct plugin invocation with all parameters _chart = helm.template( chart = "wakatime-exporter", repo_url = "@jacobcolvin", target_revision = "0.1.0", release_name = "wakatime", namespace = "monitoring", skip_crds = False, skip_hooks = False, skip_schema_validation = True, pass_credentials = False, repositories = [{ name = "jacobcolvin" url = "https://jacobcolvin.com/helm-charts" }], values = { service.main.enabled = False ingress = { enabled = True hosts = [{ host = "wakatime.example.com" paths = [{path = "/", pathType = "Prefix"}] }] } resources = { limits = {cpu = "200m", memory = "256Mi"} requests = {cpu = "100m", memory = "128Mi"} } } ) {"result": _chart} # The plugin respects environment variables from Argo CD: # ARGOCD_APP_PROJECT_NAME - Project name # ARGOCD_APP_NAMESPACE - Target namespace # ARGOCD_APP_SOURCE_PATH - Source path in repository # KUBE_VERSION - Kubernetes version for chart rendering # KUBE_API_VERSIONS - Available Kubernetes API versions # ARGOCD_EXEC_TIMEOUT - Execution timeout (default: 60s) ``` -------------------------------- ### Create or Purge MinIO Bucket with Policy (Shell) Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/templates/_helper_create_bucket.txt The `createBucket` function ensures a MinIO bucket exists, optionally purging it if specified. It first checks if the bucket exists using `checkBucketExists`. If `purge` is true and the bucket exists, it's removed recursively and forcefully. Subsequently, if the bucket does not exist, it's created using `mc mb`. Finally, it sets the specified policy on the bucket using `mc policy`. Input parameters are bucket name, policy string, and a boolean purge flag. Dependencies include `mc` CLI and the `checkBucketExists` function. ```shell # createBucket ($bucket, $policy, $purge) # Ensure bucket exists, purging if asked to createBucket() { BUCKET=$1 POLICY=$2 PURGE=$3 # Purge the bucket, if set & exists # Since PURGE is user input, check explicitly for `true` if [ $PURGE = true ]; then if checkBucketExists $BUCKET ; then echo "Purging bucket '$BUCKET'." set +e ; # don't exit if this fails /usr/bin/mc rm -r --force myminio/$BUCKET set -e ; # reset `e` as active else echo "Bucket '$BUCKET' does not exist, skipping purge." fi fi # Create the bucket if it does not exist if ! checkBucketExists $BUCKET ; then echo "Creating bucket '$BUCKET'" /usr/bin/mc mb myminio/$BUCKET else echo "Bucket '$BUCKET' already exists." fi # At this point, the bucket should exist, skip checking for existence # Set policy on the bucket echo "Setting policy of bucket '$BUCKET' to '$POLICY'." /usr/bin/mc policy $POLICY myminio/$BUCKET } ``` -------------------------------- ### Configure Helm Repositories in KCL Source: https://github.com/macropower/kclipper/blob/main/README.md KCL code snippet defining Helm chart repositories. This configuration is typically stored in a repos.k file and includes repository name, URL, and environment variables for authentication. ```kcl import helm repos: helm.ChartRepos = { chartmuseum: { name = "chartmuseum" url = "http://localhost:8080" usernameEnv = "BASIC_AUTH_USER" passwordEnv = "BASIC_AUTH_PASS" } } ``` -------------------------------- ### Get Application URL with Kubernetes NodePort Service Source: https://github.com/macropower/kclipper/blob/main/pkg/chartcmd/testdata/charts/simple-chart/templates/NOTES.txt Determines the application URL for a NodePort service. It fetches the NodePort and a Node IP, then constructs the URL. This method relies on `kubectl` commands and assumes a NodePort service type. ```shell export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "simple-chart.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT ``` -------------------------------- ### Enable Network Policy for Minio with Helm Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/README.md Enables network policy for Minio installations using Helm. This requires a compatible networking plugin and restricts traffic to port 9000 by default. 'networkPolicy.allowExternal=true' can be set for more precise control. ```bash helm install --set networkPolicy.enabled=true stable/minio ``` -------------------------------- ### Helm Chart Schema Generation Configurations Source: https://context7.com/macropower/kclipper/llms.txt Demonstrates different strategies for generating schemas from Helm charts. These include automatic detection, value inference, chart path, URL, local path, and disabling schema generation. ```kcl charts: helm.Charts = { # AUTO: Automatically detect best schema source # Tries values.schema.json in chart, falls back to value inference auto_example: { chart = "podinfo" repoURL = "https://stefanprodan.github.io/podinfo" targetRevision = "6.7.0" schemaGenerator = "AUTO" } # VALUE-INFERENCE: Generate schema from values.yaml files # Uses helm-schema to infer types from example values inferred_example: { chart = "my-chart" repoURL = "./local-charts/" schemaGenerator = "VALUE-INFERENCE" valueInference = { keepFullComment = True dontRemoveHelmDocsPrefix = False skipAutoGeneratedMessages = True } } # CHART-PATH: Use schema from within chart files chart_path_example: { chart = "app-template" repoURL = "https://bjw-s.github.io/helm-charts/" targetRevision = "3.7.1" schemaGenerator = "CHART-PATH" schemaPath = "charts/common/values.schema.json" } # URL: Download schema from URL url_example: { chart = "custom-chart" repoURL = "https://charts.example.com/" targetRevision = "1.0.0" schemaGenerator = "URL" schemaPath = "https://example.com/schemas/custom-chart-values.json" } # LOCAL-PATH: Use schema from project directory local_path_example: { chart = "internal-chart" repoURL = "@internal" targetRevision = "2.0.0" schemaGenerator = "LOCAL-PATH" schemaPath = "./schemas/internal-chart-values.schema.json" repositories = [repos.internal] } # NONE: No schema generation, values are [..str]: any no_schema_example: { chart = "legacy-chart" repoURL = "https://charts.legacy.com/" targetRevision = "0.1.0" schemaGenerator = "NONE" } } ``` -------------------------------- ### Integrate Helm Charts with Konfig for Application Management Source: https://github.com/macropower/kclipper/blob/main/README.md This KCL snippet showcases the integration of Helm charts with konfig for managing application configurations. It defines an `App` configuration that includes Helm chart deployments, secret store references, external secrets, and extra Kubernetes resources, demonstrating a unified approach to application definition. ```kcl import tenant import konfig.models.frontend import konfig.models.templates.networkpolicy import konfig.models.utils import charts.grafana_operator import charts.grafana_operator.crds as grafana appConfiguration: frontend.App { name = "grafana" charts.grafanaOperator = grafana_operator.Chart { values = grafana_operator.Values { resources.requests = { cpu = "10m" memory = "50Mi" } } } secretStore = tenant.secretStores.default.name externalSecrets.grafana = frontend.ExternalSecret { name = "grafana-credentials" data.GRAFANA_ADMIN_USER = { ref: "grafana-admin-username" } data.GRAFANA_ADMIN_PASS = { ref: "grafana-admin-password" } } extraResources.grafanaFoo = grafana.Grafana { metadata.name = "grafana-foo" spec.config = utils.GrafanaConfigBuilder(domainName, "foo") } } ``` -------------------------------- ### Get Application URL with Kubernetes LoadBalancer Service Source: https://github.com/macropower/kclipper/blob/main/pkg/chartcmd/testdata/charts/simple-chart/templates/NOTES.txt Fetches the application URL for a LoadBalancer service. It retrieves the LoadBalancer IP and combines it with the service port. Note that the LoadBalancer IP may take time to become available. Requires `kubectl`. ```shell NOTE: It may take a few minutes for the LoadBalancer IP to be available. You can watch its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "simple-chart.fullname" . }}' export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "simple-chart.fullname" . }} --template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}") echo http://$SERVICE_IP:{{ .Values.service.port }} ``` -------------------------------- ### Kubernetes Redis Client Pod Deployment Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/redis/templates/NOTES.txt This command deploys a temporary Redis client pod within a Kubernetes cluster. It allows interactive access to the Redis service using the redis-cli. Environment variables for password and labels for network policy can be configured. ```bash kubectl run --namespace {{ .Release.Namespace }} {{ template "redis.fullname" . }}-client --rm --tty -i \ {{ if .Values.usePassword }} --env REDIS_PASSWORD=$REDIS_PASSWORD \{{ end }} {{- if and (.Values.networkPolicy.enabled) (not .Values.networkPolicy.allowExternal) }}--labels="{{ template "redis.name" . }}-client=true" \{{- end }} --image {{ template "redis.image" . }} -- bash ``` -------------------------------- ### Get Application URL with LoadBalancer Service Source: https://github.com/macropower/kclipper/blob/main/docs/examples/src/my-local-charts/simple-chart/templates/NOTES.txt This snippet fetches the application URL for a Kubernetes service of type LoadBalancer. It retrieves the LoadBalancer IP and prints the URL. It also includes a note about potential delays in IP availability and a command to monitor the service status. Dependencies: kubectl, a Kubernetes cluster with a LoadBalancer service. ```shell {{- else if contains "LoadBalancer" .Values.service.type }} NOTE: It may take a few minutes for the LoadBalancer IP to be available. You can watch its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "simple-chart.fullname" . }}' export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "simple-chart.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}) echo http://$SERVICE_IP:{{ .Values.service.port }} {{- end }} ``` -------------------------------- ### Utilize Schema Generators for Type-Safe KCL Configurations Source: https://context7.com/macropower/kclipper/llms.txt This section briefly mentions KClipper's support for multiple schema generators. These generators are used to create type-safe KCL schemas from various sources. This functionality enables features like validation, auto-completion, and documentation generation for configurations. ```python import helm ``` -------------------------------- ### Render Helm Chart using Defined Configuration (Python) Source: https://github.com/macropower/kclipper/blob/main/docs/helm_extensions.md Renders a Helm chart defined in `charts.k` using the `helm.template` function. It utilizes the `podinfo.Chart` and `podinfo.Values` schemas generated from the `charts.k` configuration to specify chart values. ```python import helm import charts.podinfo helm.template(podinfo.Chart { values = podinfo.Values { replicas = 3 } }) ``` -------------------------------- ### Upgrade Minio Release with Custom Configuration Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/README.md This command upgrades an existing Minio Helm release with custom configurations defined in a YAML file. The `-f` flag specifies the configuration file to use. ```bash helm upgrade -f config.yaml stable/minio ``` -------------------------------- ### Access Application with Kubernetes ClusterIP Service via Port Forwarding Source: https://github.com/macropower/kclipper/blob/main/pkg/chartcmd/testdata/charts/simple-chart/templates/NOTES.txt Sets up port forwarding for a ClusterIP service to access the application locally. It identifies the pod name and container port, then forwards local port 8080 to the container port. Requires `kubectl`. ```shell export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "simple-chart.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") echo "Visit http://127.0.0.1:8080 to use your application" kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT ``` -------------------------------- ### Configure Minio Client (mc) for Local Access Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/templates/NOTES.txt Configuration command for the Minio client (mc) to connect to a locally exposed Minio instance. This command sets up a new host alias using provided access and secret keys. It assumes Minio is accessible via localhost on port 9000. ```shell mc config host add {{ template "minio.fullname" . }}-local http://localhost:9000 {{ .Values.accessKey }} {{ .Values.secretKey }} S3v4 ``` -------------------------------- ### Configure kclipper CMP in Argo CD Source: https://github.com/macropower/kclipper/blob/main/docs/argo_cd_cmp.md This snippet shows the Argo CD configuration to enable kclipper as a Config Management Plugin. It defines the command and arguments for KCL generation and specifies the discovery file pattern. It also configures an extra container in the repoServer to host the kcl-plugin. ```yaml configs: cmp: create: true plugins: kcl: generate: command: [kcl] args: - run - --no_style - --quiet - --log_level=info - --log_format=json discover: fileName: "*.k" repoServer: extraContainers: - name: kcl-plugin image: ghcr.io/macropower/kclipper:latest command: [/var/run/argocd/argocd-cmp-server] securityContext: runAsNonRoot: true runAsUser: 999 runAsGroup: 999 volumeMounts: - name: var-files mountPath: /var/run/argocd - name: plugins mountPath: /home/argocd/cmp-server/plugins - name: kcl-plugin-config mountPath: /home/argocd/cmp-server/config/plugin.yaml subPath: kcl.yaml - name: cmp-tmp mountPath: /tmp env: - name: KPM_FEATURE_GATES value: SupportMVS=true - name: KCL_FAST_EVAL value: "1" volumes: - name: kcl-plugin-config configMap: name: argocd-cmp-cm - name: cmp-tmp emptyDir: {} ``` -------------------------------- ### Declaratively Manage Helm Charts and Schemas with KCL Source: https://github.com/macropower/kclipper/blob/main/README.md This code defines a KCL configuration for managing Helm charts. It supports various repository types (private, OCI, local) and specifies schema generation/validation strategies. The `kcl chart` command is mentioned for command-line editing. ```kcl import helm charts: helm.Charts = { # kcl chart add -c podinfo -r https://stefanprodan.github.io/podinfo -t "6.7.0" podinfo: { chart = "podinfo" repoURL = "https://stefanprodan.github.io/podinfo" targetRevision = "6.7.0" schemaGenerator = "AUTO" } # kcl chart repo add -n bjw-s -u https://bjw-s.github.io/helm-charts/ # kcl chart add -c app-template -r @bjw-s -t "3.6.0" app_template_v3: { chart = "app-template" repoURL = "@bjw-s" targetRevision = "3.6.0" schemaValidator = "KCL" schemaGenerator = "CHART-PATH" schemaPath = "charts/common/values.schema.json" repositories = [repos.bjw_s] } # kcl chart add -c my-chart -r ./my-charts/ my_chart: { chart = "my-chart" repoURL = "./my-charts/" crdGenerator = "TEMPLATE" } } ``` -------------------------------- ### ChartConfig Schema Source: https://github.com/macropower/kclipper/blob/main/modules/helm/README.md Describes the configuration that can be defined in `charts.k`, extending `helm.ChartBase`. ```APIDOC ## ChartConfig Schema Configuration that can be defined in `charts.k`, in addition to those specified in `helm.ChartBase`. ``` -------------------------------- ### Inspect Minio Helm Chart Values Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/minio/README.md This command allows you to view all configurable parameters and their default values for the Minio Helm chart. It's essential for understanding what can be customized before applying changes. ```bash helm inspect values stable/minio ``` -------------------------------- ### Kubernetes Redis Cluster Client Connection Source: https://github.com/macropower/kclipper/blob/main/pkg/helm/testdata/redis/templates/NOTES.txt These commands demonstrate how to connect to Redis master and slave instances within a Kubernetes cluster using redis-cli. It includes connection strings for both read/write (master) and read-only (slave) endpoints, with optional password authentication. ```bash redis-cli -h {{ template "redis.fullname" . }}-master{{ if .Values.usePassword }} -a $REDIS_PASSWORD{{ end }} redis-cli -h {{ template "redis.fullname" . }}-slave{{ if .Values.usePassword }} -a $REDIS_PASSWORD{{ end }} ```