### Run Example Tests Source: https://github.com/hall/kubenix/blob/main/CONTRIBUTING.md Execute this command to run tests, which include checking the examples written in the documentation. This ensures examples are valid and up-to-date. ```bash nix flake check ``` -------------------------------- ### Deploy a Bare Pod Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/pod/_index.md This example shows the simplest way to define a pod using the `kubernetes.resources.pods` option. The `example` string is an arbitrary identifier for the pod. ```nix { example = kubernetes.resources.pods.example { containers = [ { image = "nginx"; name = "ex"; } ]; }; } ``` -------------------------------- ### Displaying Example Source: https://github.com/hall/kubenix/blob/main/docs/layouts/partials/details.html Renders an example associated with an option using the 'highlight' partial. This is useful for showcasing how to use the option. ```html {{ partial "highlight" . }} ``` -------------------------------- ### Module Usage Example Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/namespaces/_index.md Illustrates how to use the Kubenix namespaced submodule to define and deploy resources. ```nix { imports = [ ./namespaced.nix ]; kubenix.namespaced.name = "my-app-ns"; kubenix.namespaced.resources = [ { apiVersion = "v1"; kind = "Pod"; metadata = { name = "my-pod"; }; spec = { containers = [ { name = "nginx"; image = "nginx"; } ]; }; } ]; } ``` -------------------------------- ### Conditional Directory Listing Logic Source: https://github.com/hall/kubenix/blob/main/docs/layouts/partials/docs/inject/toc-after.html This Go template code checks if the current page is an example page and not the examples index page. If true, it proceeds to generate a directory listing. ```go-template {{/\* only show a directory listing on example pages \*/}} {{- if and (eq $.Section "examples") (ne $.Page.File.Path "examples/\_index.md") -}} {{/\* get base directory \*/}} {{- $dir := $.Page.File.Dir -}} {{- $loc := urls.JoinPath $.Site.Params.BookRepo "blob" "main" "docs" "content" $.Page.File.Dir -}} {{/\* create a list of nix files \*/}} {{- $files := slice -}} {{- range readDir (path.Join "content" $dir) -}} {{- if strings.HasSuffix .Name ".nix" -}} {{- $files = $files | append . -}} {{- end -}} {{- end -}} [{{- index (split $dir "/") 1 }}]({{ $loc }})/ {{- range $i, $file := $files }} {{- if ne (add $i 1) (len $files) }} ├── {{- else }} └── {{- end -}}  [{{ $file.Name }}]({{ urls.JoinPath $loc $file.Name }}) {{- end -}} {{- end -}} ``` -------------------------------- ### default.nix for Kubenix without flakes Source: https://github.com/hall/kubenix/blob/main/README.md Configure Kubenix using a default.nix file if you are not using Nix flakes. This example defines a simple Nginx pod. The output manifests are written to './result'. ```nix { kubenix ? import (builtins.fetchGit { url = "https://github.com/hall/kubenix.git"; ref = "main"; }) }: (kubenix.evalModules.x86_64-linux { module = { kubenix, ... }: { imports = [ kubenix.modules.k8s ]; kubernetes.resources.pods.example.spec.containers.nginx.image = "nginx"; }; }).config.kubernetes.result ``` -------------------------------- ### Default Nix Configuration for Testing Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/testing/_index.md This Nix file defines the default configuration, including testing setups. ```nix { testing = { success = "echo \"Test passed!\""; }; } ``` -------------------------------- ### Source Shortcode Example Source: https://github.com/hall/kubenix/blob/main/docs/layouts/shortcodes/source.html This is an example of how to use the source shortcode in a Hugo template. It takes a file path as input and displays the content of that file with syntax highlighting, along with a link to the file in the repository. ```html {{- $file := .Get 0 -}} [{{- $file -}}]({{ $.Site.Params.BookRepo}}/tree/main/docs/content/{{ .Page.File.Dir }}/{{ $file }}) {{- $file := path.Join .Page.File.Dir $file -}} {{- highlight ($file | readFile | safeHTML) (path.Ext $file) -}} ``` -------------------------------- ### Add New Kubernetes Version Source: https://github.com/hall/kubenix/blob/main/CONTRIBUTING.md Example of how to add a new Kubernetes version attribute to the versions.nix file. Ensure the attribute name is the version string and the value is the corresponding sha256 hash. ```nix { "1.23.0" = "sha256:0jivg8nlxka1y7gzqpcxkmbvhcbxynyrxmjn0blky30q5064wx2a"; } ``` -------------------------------- ### Instantiate Custom Resource Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/custom-resources/_index.md Instantiate custom resources under `kubernetes.resources.` after defining the custom type. The example shows instantiation for the `crontabs` attribute. ```nix { # ... kubernetes = { # ... resources = { crontabs = [ { metadata = { name = "my-new-cron-object"; }; spec = { cronSpec = "* * * * */5"; image = "my-awesome-cron-image"; replicas = 1; }; } ]; }; }; } ``` -------------------------------- ### Kubenix CLI diff output Source: https://github.com/hall/kubenix/blob/main/README.md Example of the diff output shown by the Kubenix CLI when applying changes. It prompts for confirmation before proceeding with the apply action. Note the diff ignores specific kubenix hash and generation metadata. ```diff diff -N -u -I ' kubenix/hash: ' -I ' generation: ' /tmp/LIVE-2503962153/apps.v1.Deployment.default.home-assistant /tmp/MERGED-231044561/apps.v1.Deployment.default.home-assistant --- /tmp/LIVE-2503962153/apps.v1.Deployment.default.home-assistant 2023-07-06 23:33:29.841771295 -0400 +++ /tmp/MERGED-231044561/apps.v1.Deployment.default.home-assistant 2023-07-06 23:33:29.842771296 -0400 @@ -43,7 +43,7 @@ spec: automountServiceAccountToken: true containers: - - image: homeassistant/home-assistant:2023.5 + - image: homeassistant/home-assistant:2023.6 imagePullPolicy: IfNotPresent livenessProbe: failureThreshold: 3 apply? [y/N]: ``` -------------------------------- ### Generated Custom Resource JSON Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/custom-resources/_index.md Example of the JSON output generated for a custom resource instance, based on the defined CRD and instantiation. ```json { "apiVersion": "stable.example.com/v1", "kind": "CronTab", "metadata": { "name": "my-new-cron-object", ... }, "spec": { "cronSpec": "* * * * */5", "image": "my-awesome-cron-image", "replicas": 1 } } ``` -------------------------------- ### Build and Serve Documentation Site Source: https://github.com/hall/kubenix/blob/main/CONTRIBUTING.md Use this command to build and serve the static documentation site locally. The site will be accessible at http://localhost:1313. ```bash nix run '.#docs' serve ``` -------------------------------- ### Deploy Custom Docker Image Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/image/_index.md Shows how to build the image and then references the generated manifest, which includes the custom image tag. ```sh nix build -f . --json config.docker.export ``` -------------------------------- ### Minimal default.nix for Kubenix Source: https://github.com/hall/kubenix/blob/main/docs/content/_index.md This snippet demonstrates a traditional Nix configuration (without flakes) for using Kubenix. It fetches Kubenix from a Git repository and defines a Kubernetes resource. ```nix { kubenix ? import (builtins.fetchGit { url = "https://github.com/hall/kubenix.git"; ref = "main"; }) }: (kubenix.evalModules.x86_64-linux { module = { kubenix, ... }: { imports = [ kubenix.modules.k8s ]; kubernetes.resources.pods.example.spec.containers.nginx.image = "nginx"; }; }).config.kubernetes.result ``` -------------------------------- ### Format Repository with Treefmt Source: https://github.com/hall/kubenix/blob/main/CONTRIBUTING.md Run this command to format the project according to the defined style guidelines before submitting changes. This ensures code consistency. ```bash nix fmt ``` -------------------------------- ### Deploy Kubenix Manifests to k3s Auto-Deploy Directory Source: https://github.com/hall/kubenix/blob/main/docs/content/tips-n-tricks/deploy.md This snippet demonstrates how to write Kubenix-generated YAML manifests to a file in the `/etc` directory and then create a symbolic link to it in k3s's auto-deployment directory. This allows k3s to automatically deploy the resources. Sensitive data should not be written to the Nix store. ```nix { # let's write `resultYAML` to an arbitrary file under `/etc` environment.etc."kubenix.yaml".source = (kubenix.evalModules.x86_64-linux { module = { kubenix, ... }: { imports = [ kubenix.modules.k8s ]; kubernetes.resources.pods.example.spec.containers.example.image = "nginx"; }; }).config.kubernetes.resultYAML; # now we can link our file into the appropriate directory # and k3s will handle the rest system.activationScripts.kubenix.text = '' ln -sf /etc/kubenix.yaml /var/lib/rancher/k3s/server/manifests/kubenix.yaml ''; } ``` -------------------------------- ### Create Deployment, ConfigMap, and Service Module Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/deployment/_index.md Create a Nix module to define related Kubernetes resources. This module creates a Deployment, mounts a ConfigMap into its pods, and defines a Service. ```nix { deploymentName ? "default-deployment", image ? "nginx:latest", servicePort ? 80, configMapName ? "my-config", configMapData ? { "app.conf" = '' # Configuration file content setting1 = value1 ''; }, }: { imports = [ ]; # Create a ConfigMap configMaps = { ${configMapName} = { data = configMapData; }; }; # Create a Deployment deployments = { ${deploymentName} = { replicas = 2; selector = { matchLabels = { app = deploymentName; }; }; template = { metadata = { labels = { app = deploymentName; }; }; spec = { containers = [ { name = deploymentName; image = image; ports = [ { containerPort = servicePort; } ]; volumeMounts = [ { name = "config-volume"; mountPath = "/etc/config"; } ]; } ]; volumes = [ { name = "config-volume"; configMap = { name = configMapName; }; } ]; }; }; }; }; # Define a Service services = { ${deploymentName}-service" = { ports = [ { port = servicePort; targetPort = servicePort; } ]; selector = { app = deploymentName; }; }; }; } ``` -------------------------------- ### Build Updated Specs for Kubernetes Versions Source: https://github.com/hall/kubenix/blob/main/CONTRIBUTING.md Execute this command to generate the updated specification files for the added Kubernetes versions. This command should be run after modifying versions.nix. ```bash nix run '.#generate' ``` -------------------------------- ### Create Development Environment with Nix Flakes Source: https://github.com/hall/kubenix/blob/main/CONTRIBUTING.md Use this command to enter the development shell provided by Nix flakes. This ensures a consistent environment for development. ```bash nix develop ``` -------------------------------- ### Evaluate Kubernetes Configuration Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/helm/_index.md Fetch and render the generated Kubernetes configuration for Helm releases. ```sh nix eval -f . --json config.kubernetes.generated ``` -------------------------------- ### Minimal flake.nix for Kubenix Source: https://github.com/hall/kubenix/blob/main/README.md Use this minimal flake.nix to build Kubernetes resources with Kubenix. The generated JSON manifests will be saved to the './result' directory. ```nix { inputs.kubenix.url = "github:hall/kubenix"; outputs = {self, kubenix, ... }@inputs: let system = "x86_64-linux"; in { packages.${system}.default = (kubenix.evalModules.${system} { module = { kubenix, ... }: { imports = [ kubenix.modules.k8s ]; kubernetes.resources.pods.example.spec.containers.nginx.image = "nginx"; }; }).config.kubernetes.result; }; } ``` -------------------------------- ### Apply Manifests with Vals and Kubectl Source: https://github.com/hall/kubenix/blob/main/docs/content/tips-n-tricks/secrets/_index.md Inject secrets during deploy time by piping manifests through `vals` for secret substitution before applying them with `kubectl`. Ensure `vals` and `kubectl` are available in the environment. ```nix pkgs.writeShellScript "apply" '' cat manifest.json | ${pkgs.vals}/bin/vals eval | ${pkgs.kubectl}/bin/kubectl -f - '' ``` -------------------------------- ### Import Docker Image Compatibility Module Source: https://github.com/hall/kubenix/blob/main/CHANGELOG.md Import this module to restore pre-v0.4.0 behavior for Docker image registry configurations and naming. ```nix imports = [ kubenix.modules.docker-image-from-package ]; ``` -------------------------------- ### Build Custom Docker Image with Nix Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/image/_index.md Defines a custom Docker image using Nix's `dockerTools.buildLayeredImage`. This is useful for creating self-contained application images. ```nix let pkgs = import ./nixpkgs {}; dockerTools = pkgs.dockerTools; myImage = dockerTools.buildLayeredImage { name = "my-image"; tag = "latest"; fromImage = { imageName = "alpine"; tag = "latest"; sha256 = "0000000000000000000000000000000000000000000000000000"; }; config = { Cmd = [ pkgs.writeShellApplication { name = "hello-world"; runtimePhase = '' echo "Hello World" ''; } ]; }; }; in { docker = { export = myImage; }; } ``` -------------------------------- ### Highlighting Nix Code Source: https://github.com/hall/kubenix/blob/main/docs/layouts/partials/highlight.html This snippet demonstrates how to use the highlight partial to render Nix code. It ensures that a blank character is added if the input text is empty to prevent formatting issues. ```html {{ $text := . }} {{ if not $text }} {{/\* add a blank character to prevent poor formatting \*/}} {{ $text = " " }} {{ end }} {{- transform.Highlight $text "nix" }} ``` -------------------------------- ### Nix Test Definition Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/testing/_index.md A sample Nix file defining a specific test case. ```nix { myTest = "echo \"This is my test.\""; } ``` -------------------------------- ### Default Kubenix Namespace Configuration Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/namespaces/_index.md Defines the main structure for Kubenix namespace management. ```nix { options = { kubenix.enable = lib.mkEnableOption "kubenix"; }; config = { kubenix.enable = lib.mkDefault true; }; } ``` -------------------------------- ### Define Default Nix Variables Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/deployment/_index.md Define high-level variables in the default.nix file for your project. This sets up the foundational configuration. ```nix let pkgs = import {}; in { # Define high-level variables here myDeploymentName = "my-app"; myImage = "nginx:latest"; myServicePort = 80; } ``` -------------------------------- ### Execute Nix Test Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/testing/_index.md Command to evaluate and execute a test defined in Nix. ```sh nix eval -f . config.testing.success ``` -------------------------------- ### Generate Kubernetes JSON Manifest Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/pod/_index.md This command evaluates the kubenix configuration and outputs the generated Kubernetes JSON manifest. The output includes details like apiVersion, kind, metadata, and spec for the deployed pod. ```sh nix eval -f . --json config.kubernetes.generated ``` ```json { "apiVersion": "v1", "items": [ { "apiVersion": "v1", "kind": "Pod", "metadata": { "annotations": { "kubenix/k8s-version": "1.24", "kubenix/project-name": "kubenix" }, "labels": { "kubenix/hash": "6e6ccbb6787f9b600737f8882d2487eeef84af9f" }, "name": "example" }, "spec": { "containers": [ { "image": "nginx", "name": "ex" } ] } } ], "kind": "List", "labels": { "kubenix/hash": "6e6ccbb6787f9b600737f8882d2487eeef84af9f", "kubenix/k8s-version": "1.24", "kubenix/project-name": "kubenix" } } ``` -------------------------------- ### Push Custom Docker Image to Registry Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/image/_index.md Executes a script to push the custom-built Docker image to a registry. This script is typically defined elsewhere and referenced by its output path. ```sh $(nix build -f . --print-out-paths config.docker.copyScript) ``` -------------------------------- ### Manage Details Elements and URL Fragments Source: https://github.com/hall/kubenix/blob/main/docs/layouts/partials/docs/inject/body.html This script enhances the behavior of HTML 'details' elements. It opens a 'details' element specified in the URL fragment on page load and manages click events on 'summary' elements to update the URL fragment and collapse other 'details' elements. Use this to create collapsible content sections that are bookmarkable via URL. ```javascript window.onload = function(){ // open details of option in URL fragment document.getElementById(decodeURI(window.location.hash.substring(1)))?.setAttribute("open", ""); var options = document.getElementsByTagName('details'); for(var i = 0; i < options.length; i++) { options[i].getElementsByTagName("summary")[0].onclick = function() { // set URL fragment to option id history.pushState({}, "", `#${this.parentElement.id}`); // is current panel open, return immediately as it's just being closed if (this.parentElement.hasAttribute("open")) return; // collapse all other options for(var j = 0; j < options.length; j++) { options[j].removeAttribute("open"); } }; } }; ``` -------------------------------- ### Generated Kubernetes Pod Manifest with Custom Image Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/image/_index.md A sample JSON output of a Kubernetes Pod manifest that uses the custom-built Docker image. Note the image tag reflects the built image. ```json { "apiVersion": "v1", "items": [ { "apiVersion": "v1", "kind": "Pod", "metadata": { "annotations": { "kubenix/k8s-version": "1.24", "kubenix/project-name": "kubenix" }, "labels": { "kubenix/hash": "ac7e4794c3d37f0884e4512a680a30d20e1d6454" }, "name": "example" }, "spec": { "containers": [ { "image": "docker.somewhere.io/nginx:w7c63alk7kynqh2mqnzxy9n1iqgdc93s", "name": "custom" } ] } } ], "kind": "List", "labels": { "kubenix/hash": "ac7e4794c3d37f0884e4512a680a30d20e1d6454", "kubenix/k8s-version": "1.24", "kubenix/project-name": "kubenix" } } ``` -------------------------------- ### Define Custom Resource Definition Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/custom-resources/_index.md Register a CRD by adding an entry to the `kubernetes.customTypes` list. Specify the Group, Version, Kind, and the Nix module describing the resource schema. ```nix { # ... kubernetes = { customTypes = [ { group = "stable.example.com"; version = "v1"; kind = "CronTab"; # The Nix module that describes the schema of the resource. # See kubernetes.schema module for details. module = { type = "object"; properties = { cronSpec = { type = "string"; description = "The cron schedule string."; }; image = { type = "string"; description = "The container image to run."; }; replicas = { type = "integer"; description = "Number of desired pods. This is a custom field and not commonly used."; minimum = 1; }; }; required = ["cronSpec" "image"]; }; } ]; # ... }; } ``` -------------------------------- ### Namespaced Resource Definition Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/namespaces/_index.md Defines a generic resource that can be deployed into a specific namespace. ```nix { options = { kubenix.namespaced = { name = lib.mkOption { type = lib.types.str; description = "The name of the namespace."; }; resources = lib.mkOption { type = lib.types.listOf lib.types.attrs; default = [ ]; description = "List of resources to deploy in this namespace."; }; }; }; config = { kubenix.namespaced = lib.mkIf config.kubenix.enable { # This is where the actual resource creation logic would go. # For example, using kubernetes.namespace or other modules. }; }; } ``` -------------------------------- ### Displaying Default Value Source: https://github.com/hall/kubenix/blob/main/docs/layouts/partials/details.html Renders the default value of an option using the 'highlight' partial. This is typically used for displaying code or configuration snippets. ```html {{ partial "highlight" $option.default.text }} ``` -------------------------------- ### Patching a Helm Release Deployment Source: https://github.com/hall/kubenix/blob/main/docs/content/examples/helm/_index.md Patch a deployment created by a Helm release by merging configuration during evaluation. This allows overriding `values.yaml` settings. ```nix { # define a resource with the same name kubernetes.resources.deployments.nginx = { # be sure to match the corresponding namespace as well metadata.namespace = "default"; # here we can configure anything and are no longer bound by `values.yaml` spec.template.spec.containers.nginx.env = [{ name = "MY_VARIABLE"; value = "100"; }]; }; } ``` -------------------------------- ### Override Kubenix package with custom module Source: https://github.com/hall/kubenix/blob/main/README.md Override the default Kubenix package to use a custom cluster module. This allows passing custom values to the kubenix module, such as the 'flake' argument for custom logic. ```nix { kubenix = inputs.kubenix.packages.${pkgs.system}.default.override { module = import ./cluster; # optional; pass custom values to the kubenix module specialArgs = { flake = self; }; }; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.