### Initialize easykubenix Instance Source: https://context7.com/lillecarl/easykubenix/llms.txt Import the easykubenix library and pass your modules to generate manifest outputs and deployment scripts. ```nix # default.nix { pkgs ? import { } }: let easykubenix = import ( builtins.fetchTree { type = "github"; owner = "lillecarl"; repo = "easykubenix"; } ); result = easykubenix { inherit pkgs; modules = [ ./my-resources.nix ./helm-releases.nix ]; # Optional: pass additional arguments to modules specialArgs = { environment = "production"; clusterName = "my-cluster"; }; }; in { # Access different output formats inherit (result) manifestAttrs # Nix attribute set of the Kubernetes List manifestJSON # JSON string manifestJSONFile # Path to JSON file manifestYAML # YAML string (requires IFD) manifestYAMLFile # Path to YAML file ; # Scripts for deployment and validation inherit (result) deploymentScript validationScript; # Access the full eval for advanced use cases inherit (result) eval; } # Build and inspect outputs: # nix build --file . manifestYAMLFile && cat result # nix build --file . manifestJSONFile && cat result ``` -------------------------------- ### Run easykubenix Demo Source: https://github.com/lillecarl/easykubenix/blob/main/README.md Evaluate the demo YAML and apply it to an ephemeral apiserver. Use 'cat' to check the generated YAML. ```bash nix run --file . validationScript ``` ```bash cat $(nix build --print-out-paths --file . manifestYAMLFile) ``` -------------------------------- ### Create an easykubenix Instance Source: https://github.com/lillecarl/easykubenix/blob/main/README.md Import easykubenix from GitHub and configure it with custom modules. This sets up the environment for generating Kubernetes manifests. ```nix { pkgs ? import {}}: let easykubenix = import ( builtins.fetchTree { type = "github"; owner = "lillecarl"; repo = "easykubenix"; } ); in easykubenix { inherit pkgs; modules = [ ./my-modules.nix ]; } ``` -------------------------------- ### Configure Kluctl Deployment Project Source: https://context7.com/lillecarl/easykubenix/llms.txt Sets up kluctl project files for GitOps workflows, including discriminator, resource priorities, and pre/post-deploy scripts. The 'discriminator' is crucial for automatic resource pruning. ```nix # kluctl-config.nix { pkgs, ... }: { config.kluctl = { # Unique discriminator for this deployment (used for pruning) discriminator = "my-production-cluster"; # Resource apply order priorities resourcePriority = { Namespace = 10; CustomResourceDefinition = 10; ClusterRole = 20; ClusterRoleBinding = 20; }; # Pre-deploy script (e.g., push to cache) preDeployScript = '' echo "Pushing manifests to binary cache..." # nix copy --to s3://my-cache $1 ''; # Post-deploy script postDeployScript = '' echo "Deployment complete!" # notify-slack "Deployment successful" ''; # Kluctl project configuration project = { targets = [ { name = "production"; context = "prod-cluster"; } { name = "staging"; context = "staging-cluster"; } ]; }; # Additional files to include in kluctl project files = { "secrets/encrypted.yaml" = '' apiVersion: v1 kind: Secret metadata: name: encrypted-secret # SOPS encrypted data... ''; }; }; } ``` -------------------------------- ### Define Kubernetes Resources with easykubenix Source: https://context7.com/lillecarl/easykubenix/llms.txt Define resources using the hierarchical path kubernetes.objects.... Use _namedlist = true to convert attribute sets into lists where required by the Kubernetes API. ```nix # my-resources.nix { pkgs, ... }: { config.kubernetes.objects = { # Cluster-scoped resource (no namespace) none.Namespace.my-app = { }; # Namespaced resources - namespace is auto-injected my-app.ConfigMap.app-config = { data = { "database.host" = "postgres.my-app.svc.cluster.local"; "log.level" = "info"; }; }; my-app.Secret.app-secrets = { metadata.labels.app = "my-app"; stringData = { "api-key" = "your-secret-key"; "config.yaml" = builtins.toJSON { feature_flags = { enable_beta = true; }; }; }; }; my-app.Deployment.web-server = { spec = { replicas = 3; selector.matchLabels.app = "web-server"; template = { metadata.labels.app = "web-server"; spec.containers = { _namedlist = true; # Convert attrset to list by name main = { name = "main"; image = "nginx:1.25"; ports = { _namedlist = true; http = { name = "http"; containerPort = 80; }; }; env = { _namedlist = true; LOG_LEVEL.value = "info"; DATABASE_HOST = { valueFrom.configMapKeyRef = { name = "app-config"; key = "database.host"; }; }; }; }; }; }; }; }; my-app.Service.web-server = { spec = { selector.app = "web-server"; ports = { _namedlist = true; http = { name = "http"; port = 80; targetPort = 80; }; }; }; }; }; } ``` -------------------------------- ### Run Kluctl Deployment Script Source: https://context7.com/lillecarl/easykubenix/llms.txt Executes the kluctl deployment script for GitOps workflows. Use flags like --yes for automatic confirmation, --prune for resource pruning, and --dry-run for a simulation. ```bash # Run the deployment script nix run --file . deploymentScript -- --yes --prune # Dry-run deployment nix run --file . deploymentScript -- --dry-run # Deploy to specific target nix run --file . deploymentScript -- --target staging --yes ``` -------------------------------- ### Trigger rollouts with ConfigMap hashing Source: https://context7.com/lillecarl/easykubenix/llms.txt Use lib.hashAttrs to generate a hash of configuration data, which can be used in deployment annotations to trigger rollouts when the configuration changes. ```nix # utilities.nix { config, lib, ... }: let appConfig = { database.host = "postgres.default.svc"; cache.enabled = true; log.level = "info"; }; configHash = lib.hashAttrs appConfig; in { config.kubernetes.objects.default = { ConfigMap.app-config.data."config.json" = builtins.toJSON appConfig; Deployment.myapp = { spec.template = { # Trigger rollout when ConfigMap changes metadata.annotations."config-hash" = configHash; spec.containers = { _namedlist = true; main = { name = "main"; image = "myapp:latest"; volumeMounts = { _namedlist = true; config = { name = "config"; mountPath = "/etc/app/config.json"; subPath = "config.json"; }; }; }; }; spec.volumes = { _namedlist = true; config = { name = "config"; configMap.name = "app-config"; }; }; }; spec.selector.matchLabels.app = "myapp"; }; }; } ``` -------------------------------- ### Validate Kubernetes Manifests Source: https://github.com/lillecarl/easykubenix/blob/main/README.md Run the validation script to build manifests, spin up a temporary API server, and apply configurations to it for validation against the Kubernetes API. ```bash nix run --file . validationScript ``` -------------------------------- ### Configure Custom Validation Settings Source: https://context7.com/lillecarl/easykubenix/llms.txt Sets custom network configurations and kubeadm overrides for the validation script. Debug output can be enabled by setting 'debug' to true. ```nix { ... }: { config.validation = { # Enable debug output debug = false; # Custom network configuration podSubnet = "10.244.0.0/16"; serviceSubnet = "10.96.0.0/16"; # Custom kubeadm configuration overrides kubeadmConfig = { apiVersion = "kubeadm.k8s.io/v1beta4"; kind = "ClusterConfiguration"; # Additional kubeadm options... }; }; } ``` -------------------------------- ### Define Kubernetes Resources with NixOS Modules Source: https://github.com/lillecarl/easykubenix/blob/main/README.md Define Kubernetes resources like ConfigMaps and Deployments using the NixOS module system. Resources are nested under 'kubernetes.namespace' or 'kubernetes.resources'. ```nix { kubernetes.namespace.ConfigMap.my-awesome-configmap = { stringData."config.json" = builtins.toJSON { key = "value"; }; }; kubernetes.namespace.Deployment.my-app = { spec.replicas = 3; }; } ``` -------------------------------- ### Generate Final YAML Manifests Source: https://github.com/lillecarl/easykubenix/blob/main/README.md Import your custom modules into the provided 'eval' function to generate the final YAML manifests. This is typically done in a default.nix file. ```nix # default.nix { pkgs ? import {} }: (import { inherit pkgs; modules = [ ./my-modules.nix ]; }).eval ``` -------------------------------- ### Resource Filters in Nix Source: https://context7.com/lillecarl/easykubenix/llms.txt Defines filters to conditionally exclude Kubernetes resources from the output. Filters return true to keep a resource or false to exclude it. ```nix # filters.nix { lib, ... }: { config.kubernetes.filters = [ # Exclude resources marked for deletion (object: (object.metadata.annotations."easykubenix/exclude" or "false") != "true") # Only include resources for specific environment (object: let envLabel = object.metadata.labels."environment" or "all"; in envLabel == "all" || envLabel == "production" ) # Exclude test resources in production (object: !(lib.hasPrefix "test-" (object.metadata.name or "")) ) # Filter out empty ConfigMaps (object: if object.kind == "ConfigMap" then (object.data or {}) != {} || (object.binaryData or {}) != {} else true ) ]; } ``` -------------------------------- ### Run Kubernetes Validation Script Source: https://context7.com/lillecarl/easykubenix/llms.txt Executes a script to validate Kubernetes manifests against an ephemeral API server. Use the --debug flag for verbose output. ```bash # Run validation script from the demo nix run --file . validationScript # With debugging enabled nix run --file . validationScript -- --debug # Build and inspect the validation script nix build --file . validationScript cat result/bin/kubeval ``` -------------------------------- ### Apply Global Resource Transformers Source: https://context7.com/lillecarl/easykubenix/llms.txt Implement cross-cutting concerns like labels, annotations, resource limits, and security contexts by defining a list of transformer functions. ```nix # transformers.nix { lib, ... }: { config.kubernetes.transformers = [ # Add common labels to all resources (object: lib.recursiveUpdate object { metadata.labels = (object.metadata.labels or {}) // { "app.kubernetes.io/managed-by" = "easykubenix"; "environment" = "production"; }; } ) # Configure LoadBalancer services (object: if object.kind == "Service" && (object.spec.type or null) == "LoadBalancer" then lib.recursiveUpdate object { metadata.annotations = (object.metadata.annotations or {}) // { "metallb.io/allow-shared-ip" = "true"; "external-dns.alpha.kubernetes.io/ttl" = "60"; }; } else object ) # Enforce resource limits on all containers (object: if lib.elem object.kind [ "Deployment" "StatefulSet" "DaemonSet" ] then let defaultResources = { requests = { cpu = "10m"; memory = "32Mi"; }; limits = { cpu = "1000m"; memory = "1Gi"; }; }; addResources = container: container // { resources = container.resources or defaultResources; }; in lib.recursiveUpdate object { spec.template.spec.containers = map addResources (object.spec.template.spec.containers or []); } else object ) # Set security context for all pods (object: if lib.elem object.kind [ "Deployment" "StatefulSet" "DaemonSet" "Job" ] then lib.recursiveUpdate object { spec.template.spec.securityContext = { runAsNonRoot = true; seccompProfile.type = "RuntimeDefault"; }; } else object ) ]; } ``` -------------------------------- ### Define Helm Releases in Nix Source: https://context7.com/lillecarl/easykubenix/llms.txt Configure Helm charts by specifying the repository, version, and values. Use overrides to modify rendered objects and control CRD or hook behavior. ```nix # helm-releases.nix { pkgs, lib, ... }: { config.helm.releases = { ingress-nginx = { namespace = "ingress-nginx"; chart = pkgs.fetchHelm { repo = "https://kubernetes.github.io/ingress-nginx"; chart = "ingress-nginx"; version = "4.10.0"; sha256 = "sha256-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; }; values = { controller = { replicaCount = 2; service.type = "LoadBalancer"; metrics.enabled = true; resources = { requests = { cpu = "100m"; memory = "128Mi"; }; limits = { cpu = "500m"; memory = "512Mi"; }; }; }; }; # Transform rendered chart objects overrides = [ (object: if object.kind == "Deployment" then lib.recursiveUpdate object { spec.template.spec.priorityClassName = "system-cluster-critical"; } else object ) ]; # Include CRDs (use with caution - can break existing CRs) includeCRDs = false; # Exclude Helm hooks (they run immediately without Helm CLI) noHooks = true; # Specify available API versions for capability checks apiVersions = [ "networking.k8s.io/v1" ]; }; cert-manager = { namespace = "cert-manager"; chart = pkgs.fetchHelm { repo = "https://charts.jetstack.io"; chart = "cert-manager"; version = "1.14.4"; sha256 = "sha256-YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"; }; values = { installCRDs = true; replicaCount = 1; prometheus.enabled = true; }; }; }; } ``` -------------------------------- ### Generate VPA for Workloads Source: https://context7.com/lillecarl/easykubenix/llms.txt Automatically generates a VerticalPodAutoscaler for Deployments, StatefulSets, and DaemonSets if they have the 'genvpa' annotation set to 'true'. ```nix { config, lib, ... }: { config.kubernetes.generators = [ # Auto-generate VPA for workloads (object: if lib.elem object.kind [ "Deployment" "StatefulSet" "DaemonSet" ] && (object.metadata.annotations.genvpa or "true") == "true" && !lib.hasAttrByPath [ object.metadata.namespace "VerticalPodAutoscaler" object.metadata.name ] config.kubernetes.objects then { apiVersion = "autoscaling.k8s.io/v1"; kind = "VerticalPodAutoscaler"; metadata = { name = object.metadata.name; namespace = object.metadata.namespace; }; spec = { targetRef = { apiVersion = object.apiVersion; kind = object.kind; name = object.metadata.name; }; updatePolicy.updateMode = "Auto"; }; } else { } ) # Generate PodMonitor for services with prometheus annotations (object: if object.kind == "Service" && (object.metadata.annotations."prometheus.io/scrape" or null) == "true" then { apiVersion = "monitoring.coreos.com/v1"; kind = "PodMonitor"; metadata = { name = "${object.metadata.name}-monitor"; namespace = object.metadata.namespace; }; spec = { selector.matchLabels = object.spec.selector; podMetricsEndpoints = [{ port = object.metadata.annotations."prometheus.io/port" or "metrics"; path = object.metadata.annotations."prometheus.io/path" or "/metrics"; }]; }; } else { } ) # Generate default NetworkPolicy for namespaces (object: if object.kind == "Namespace" && (object.metadata.annotations."generate-network-policy" or "false") == "true" then { apiVersion = "networking.k8s.io/v1"; kind = "NetworkPolicy"; metadata = { name = "default-deny-ingress"; namespace = object.metadata.name; }; spec = { podSelector = { }; policyTypes = [ "Ingress" ]; }; } else { } ) ]; } ``` -------------------------------- ### Define Kubernetes API Mappings in Nix Source: https://context7.com/lillecarl/easykubenix/llms.txt Maps Kubernetes resource kinds to their API group and version. Useful for custom resource definitions or when Nix needs to understand specific Kubernetes API versions. ```nix { ... }: { config.kubernetes.apiMappings = { # Cluster API resources Cluster = "cluster.x-k8s.io/v1beta1"; MachineDeployment = "cluster.x-k8s.io/v1beta1"; KubeadmControlPlane = "controlplane.cluster.x-k8s.io/v1beta1"; # Cert-manager resources Certificate = "cert-manager.io/v1"; ClusterIssuer = "cert-manager.io/v1"; Issuer = "cert-manager.io/v1"; # Prometheus Operator resources ServiceMonitor = "monitoring.coreos.com/v1"; PodMonitor = "monitoring.coreos.com/v1"; PrometheusRule = "monitoring.coreos.com/v1"; # Gateway API resources Gateway = "gateway.networking.k8s.io/v1"; HTTPRoute = "gateway.networking.k8s.io/v1"; # ArgoCD resources Application = "argoproj.io/v1alpha1"; ApplicationSet = "argoproj.io/v1alpha1"; }; # Or use a custom API resources file generated by: # kubectl api-resources --output=json > my-cluster-resources.json # config.kubernetes.apiMappingFile = ./my-cluster-resources.json; } ``` -------------------------------- ### Importing External YAML Files with Nix Source: https://context7.com/lillecarl/easykubenix/llms.txt Imports existing YAML manifests from local files, URLs, or derivations. Imported objects can be transformed using overrides. ```nix # imports.nix { pkgs, lib, ... }: { config.importyaml = { # Import from a local file local-manifests = { src = ./external-manifests.yaml; convertLists = true; # Convert lists to named attrsets for overridability }; # Import from a URL prometheus-operator-crds = { src = "https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/v0.72.0/example/prometheus-operator-crd/monitoring.coreos.com_servicemonitors.yaml"; overrides = [ # Add custom labels to imported resources (object: lib.recursiveUpdate object { metadata.labels."imported-by" = "easykubenix"; } ) ]; }; # Import from a derivation generated-manifests = { src = pkgs.runCommand "generate-manifests" {} '' cat > $out << 'EOF' apiVersion: v1 kind: ConfigMap metadata: name: generated-config namespace: default data: key: value EOF ''; }; }; } ``` -------------------------------- ### Define Kubernetes objects with named lists Source: https://context7.com/lillecarl/easykubenix/llms.txt Use the _namedlist attribute to convert Nix attribute sets into Kubernetes JSON arrays, allowing for granular overrides. ```nix { lib, ... }: { config.kubernetes.objects.default.Deployment.example = { spec.template.spec.containers = { _namedlist = true; # Marks this attrset as a list main = { name = "main"; image = "myapp:latest"; # Environment variables as named list env = { _namedlist = true; DATABASE_URL.value = "postgres://localhost/db"; API_KEY = { valueFrom.secretKeyRef = { name = "api-secrets"; key = "api-key"; }; }; }; # Ports as named list ports = { _namedlist = true; http = { name = "http"; containerPort = 8080; }; metrics = { name = "metrics"; containerPort = 9090; }; }; # Volume mounts as named list volumeMounts = { _namedlist = true; config = { name = "config"; mountPath = "/etc/config"; }; data = { name = "data"; mountPath = "/var/data"; }; }; }; sidecar = { name = "sidecar"; image = "envoyproxy/envoy:v1.29"; }; }; # Volumes as named list spec.template.spec.volumes = { _namedlist = true; config = { name = "config"; configMap.name = "app-config"; }; data = { name = "data"; emptyDir = {}; }; }; }; # Using lib.mkNamedList helper config.kubernetes.objects.default.StatefulSet.database.spec.template.spec.containers = lib.mkNamedList { postgres = { name = "postgres"; image = "postgres:16"; env = lib.mkNamedList { POSTGRES_DB.value = "mydb"; POSTGRES_USER.value = "admin"; }; }; }; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.