### Manually Install Kosko Core Dependencies Source: https://github.com/tommy351/kosko/blob/master/website/docs/getting-started.mdx For a manual setup, install the essential Kosko packages: `kosko`, `@kosko/env`, and `kubernetes-models`. These provide the core functionalities for Kosko projects. ```shell npm install kosko @kosko/env kubernetes-models ``` -------------------------------- ### Initialize Kosko Project Automatically Source: https://github.com/tommy351/kosko/blob/master/website/docs/getting-started.mdx Use `npm init kosko@latest` to quickly set up a new Kosko project. This command creates the basic folder structure and installs all necessary dependencies automatically. ```shell npm init kosko@latest example ``` -------------------------------- ### Create New Kosko Component from Template Source: https://github.com/tommy351/kosko/blob/master/website/docs/getting-started.mdx Generate a new component, such as an Nginx deployed service, using the `@kosko/template-deployed-service` template. Specify the component name and desired image. ```shell npx @kosko/template-deployed-service --name nginx --image nginx ``` -------------------------------- ### Generate Kubernetes Manifests to Console Output Source: https://github.com/tommy351/kosko/blob/master/website/docs/getting-started.mdx Execute `kosko generate` to produce and print the Kubernetes manifests directly to your console. This command compiles your Kosko components into deployable YAML. ```shell npx kosko generate ``` -------------------------------- ### Apply Generated Kubernetes Manifests to Cluster Source: https://github.com/tommy351/kosko/blob/master/website/docs/getting-started.mdx Pipe the output of `kosko generate` directly into `kubectl apply -f -`. This allows you to apply the dynamically generated Kubernetes manifests to your cluster without saving them to a file. ```shell npx kosko generate | kubectl apply -f - ``` -------------------------------- ### Install project dependencies with pnpm Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Downloads and installs all required project dependencies. This command utilizes pnpm to resolve and install packages specified in the project's package.json file. ```sh pnpm install ``` -------------------------------- ### Install Helm 3 via curl script Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Installs Helm 3, a package manager for Kubernetes, by downloading and executing an official installation script. This method ensures the latest stable version of Helm is set up on the system. ```sh curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash ``` -------------------------------- ### Install pnpm globally Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Installs the pnpm package manager globally on the system. This command uses npm to perform the global installation, making pnpm available for use across different projects. ```sh npm install -g pnpm ``` -------------------------------- ### Validate Kosko Generated Manifests Source: https://github.com/tommy351/kosko/blob/master/website/docs/getting-started.mdx Run `kosko validate` to check the correctness and validity of your generated Kubernetes manifests. This command performs validation without printing the manifests to the console. ```shell npx kosko validate ``` -------------------------------- ### Install Project Dependencies with Yarn Source: https://github.com/tommy351/kosko/blob/master/website/README.md This command installs all necessary project dependencies listed in the `package.json` file using Yarn, preparing the project for development. ```Shell yarn install ``` -------------------------------- ### Install Kosko Kustomize and YAML Packages Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-kustomize.mdx Instructions to install the @kosko/kustomize package for Kustomize support and @kosko/yaml for YAML loading, which are dependencies for using Kustomize features in Kosko. ```shell npm install @kosko/kustomize @kosko/yaml ``` -------------------------------- ### Install @kosko/kustomize package Source: https://github.com/tommy351/kosko/blob/master/website/blog/2021-12-19-kustomize.md This command installs the @kosko/kustomize package using npm, which is required to enable Kustomize support in Kosko. Ensure kustomize or kubectl CLI is installed beforehand. ```shell npm install @kosko/kustomize ``` -------------------------------- ### Install Kosko Lint Plugin Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/index.mdx Instructions to install the `@kosko/plugin-lint` package using npm or yarn. ```shell npm install @kosko/plugin-lint ``` -------------------------------- ### Initialize New Kosko Project with create-kosko CLI Source: https://github.com/tommy351/kosko/blob/master/packages/create-kosko/README.md This snippet demonstrates how to create a new Kosko project using the `create-kosko` CLI tool. It provides examples for different package managers: npm, Yarn, and pnpm. Replace 'example' with the desired name for your new project directory. ```sh npm create kosko@latest example ``` ```sh yarn create kosko example ``` ```sh pnpm create kosko example ``` -------------------------------- ### Enable a single Kosko plugin in kosko.toml Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/index.md This TOML configuration demonstrates how to enable a plugin named 'example' by adding it to the `plugins` array in the `kosko.toml` file. ```TOML [[plugins]] name = "example" ``` -------------------------------- ### Install Kosko Set Metadata Plugin Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/set-metadata.mdx Instructions to install the `@kosko/plugin-set-metadata` plugin using npm or yarn. ```shell npm install @kosko/plugin-set-metadata ``` -------------------------------- ### Start Local Development Server with Yarn Source: https://github.com/tommy351/kosko/blob/master/website/README.md This command starts a local development server, typically for a Docusaurus website, and automatically opens a browser window. It supports live reloading for most changes, enhancing the development workflow. ```Shell yarn start ``` -------------------------------- ### Install @kosko/yaml package Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-kubernetes-yaml.mdx Installs the `@kosko/yaml` package using npm, which provides utilities for loading and migrating Kubernetes YAML files. ```shell npm install @kosko/yaml ``` -------------------------------- ### Install @kosko/helm npm package Source: https://github.com/tommy351/kosko/blob/master/website/blog/2021-04-05-helm.md This command installs the `@kosko/helm` package using npm. This package is essential for integrating Helm charts into Kosko projects and requires the Helm CLI to be installed beforehand. ```shell npm install @kosko/helm ``` -------------------------------- ### Configure Kosko Plugins in TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Example of defining plugin configurations in kosko.toml, showing how to specify a plugin name and its associated configuration. ```toml [[plugins]] name = "@kosko/plugin-set-metadata" config.namespace.value = "default" ``` -------------------------------- ### Enable Kosko Lint Plugin with Recommended Preset (TOML) Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/index.mdx Configuration example in TOML to enable the `@kosko/plugin-lint` plugin and extend its configuration with the recommended preset. This is the primary way to quickly set up the linter with best practices. ```toml [[plugins]] name = "@kosko/plugin-lint" config.extends = ["@kosko/plugin-lint/presets/recommended"] ``` -------------------------------- ### Install @kosko/yaml for YAML migration Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-kubernetes-yaml.mdx Installs the `@kosko/yaml` package, which is a prerequisite for using the `kosko migrate` command to convert Kubernetes YAML files into JavaScript. ```shell npm install @kosko/yaml ``` -------------------------------- ### Install Kosko Programmatic API Dependencies Source: https://github.com/tommy351/kosko/blob/master/website/docs/programmatic-usage.mdx Installs the `@kosko/env` and `@kosko/generate` packages required for programmatic interaction with Kosko, enabling environment management and manifest generation. ```shell npm install @kosko/env @kosko/generate ``` -------------------------------- ### Run integration tests Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Executes the project's integration tests. These tests verify the interactions between different modules or services, ensuring they work together as expected within the system. ```sh npm run test:integration ``` -------------------------------- ### Install @kosko/helm and @kosko/yaml Packages Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-helm-chart.mdx Instructions to install the necessary Kosko Helm and YAML packages using either npm or yarn package managers. ```shell npm install @kosko/helm @kosko/yaml ``` ```shell yarn add @kosko/helm @kosko/yaml ``` -------------------------------- ### Install Kosko Set Metadata Plugin Source: https://github.com/tommy351/kosko/blob/master/plugins/set-metadata/README.md Installs the `@kosko/plugin-set-metadata` package, a Kosko plugin designed to set metadata for Kubernetes manifests, using npm. ```sh npm install @kosko/plugin-set-metadata ``` -------------------------------- ### Run browser tests Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Launches and runs tests specifically designed for web browser environments. These tests typically involve a headless browser or a real browser instance to simulate user interactions. ```sh npm run test:browser ``` -------------------------------- ### Watch and rebuild TypeScript files Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Starts a development server or process that continuously monitors TypeScript source files for changes. Upon detection, it automatically recompiles them, facilitating rapid development cycles. ```sh npm run watch ``` -------------------------------- ### Configure Kosko Set Metadata Plugin Source: https://github.com/tommy351/kosko/blob/master/website/blog/2024-03-28-kosko-4.1.md Example TOML configuration to enable the @kosko/plugin-set-metadata plugin. This setup allows setting a default namespace, 'dev', for all generated Kubernetes manifests, simplifying environment-specific deployments. ```toml [[plugins]] name = "@kosko/plugin-set-metadata" config.namespace.value = "dev" ``` -------------------------------- ### Install @kosko/plugin-lint Source: https://github.com/tommy351/kosko/blob/master/plugins/lint/README.md Installs the @kosko/plugin-lint package using npm. This package provides linting capabilities for Kubernetes manifests within the Kosko framework. ```sh npm install @kosko/plugin-lint ``` -------------------------------- ### Configure ES Module Preloading in Kosko TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Example of preloading ES modules at startup using the 'import' option in kosko.toml, applicable when ECMAScript modules are enabled. ```toml # Using TypeScript import = ["tsx"] ``` -------------------------------- ### Configure Kosko Components in TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Examples demonstrating how to specify components to generate using various patterns in the kosko.toml file, including glob patterns and exclusion. ```toml # Generate all components in components folder components = ["*"] # Generate components with the specified names components = ["foo", "bar"] # Generate components matched to the glob patterns components = ["foo_*", "bar_*"] # Ignore components components = ["!foo", "!bar"] ``` -------------------------------- ### Configure Environment-Specific Settings in Kosko TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Examples of defining environment-specific configurations in kosko.toml, demonstrating how to apply different component sets based on the active environment. ```toml # Applied when env = "dev" [environments.dev] components = ["*_dev"] # Applied when env = "prod" [environments.prod] components = ["*_prod"] ``` -------------------------------- ### Upgrade kubernetes-models to Latest Version Source: https://github.com/tommy351/kosko/blob/master/website/blog/2022-02-23-kubernetes-models-3.0-released/index.mdx Instructions to upgrade the `kubernetes-models` package to its latest version using npm. This command ensures you get the latest features and bug fixes. Remember to also upgrade any installed CRD packages to maintain compatibility. ```shell npm install kubernetes-models@latest ``` -------------------------------- ### Configure Kosko Browser Entry File with Async Environment Source: https://github.com/tommy351/kosko/blob/master/website/docs/using-in-browser.mdx This example demonstrates a basic entry file for Kosko in a browser environment. It shows how to set up an asynchronous environment loader using `createAsyncLoaderReducers` for dynamic imports, resolve components with `resolve`, and print the resulting manifests in YAML format to the console. It highlights the use of `resolve` instead of `generate` due to browser limitations. ```javascript import env, { createAsyncLoaderReducers } from "@kosko/env"; import { resolve, print, PrintFormat } from "@kosko/generate"; // Load environment variables with dynamic import env.setReducers((reducers) => [ ...reducers, ...createAsyncLoaderReducers({ global: () => import("./environments/dev/index.js").then((mod) => mod.default), component: (name) => import(`./environments/dev/${name}.js`).then((mod) => mod.default) }) ]); (async () => { // Resolve and validate components const manifests = await resolve( import("./components/nginx.js").then((mod) => mod.default) ); // Print resolved manifests print( { manifests }, { format: PrintFormat.YAML, writer: { write: (data) => console.log(data) } } ); })(); ``` -------------------------------- ### Install TypeScript Development Dependencies for Kosko Source: https://github.com/tommy351/kosko/blob/master/website/docs/typescript.mdx This shell command installs `typescript`, `ts-node`, and `@tsconfig/recommended` as development dependencies. `ts-node` enables direct execution of TypeScript files, while `@tsconfig/recommended` provides a robust base configuration for TypeScript projects. ```Shell npm install typescript ts-node @tsconfig/recommended --save-dev ``` -------------------------------- ### Run unit tests Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Initiates the execution of all unit tests defined within the project. This command runs isolated tests for individual components or functions to verify their correctness. ```sh npm run test:unit ``` -------------------------------- ### Install Kosko Set Metadata Plugin Source: https://github.com/tommy351/kosko/blob/master/website/docs/recipes/default-namespace.mdx Command to install the @kosko/plugin-set-metadata package, which allows setting a default namespace for Kubernetes manifests in Kosko. ```shell npm install @kosko/plugin-set-metadata ``` -------------------------------- ### Configure Kosko Component Extensions in TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Example of setting component file extensions in kosko.toml, though typically detected automatically. ```toml extensions = ["js", "json"] ``` -------------------------------- ### Build TypeScript project Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Compiles all TypeScript source files into JavaScript, preparing the project for execution, testing, or deployment. This command is a prerequisite for running integration or browser tests. ```sh npm run build ``` -------------------------------- ### Migrating Kosko Environment Initialization from Class to Function Source: https://github.com/tommy351/kosko/blob/master/website/blog/2021-04-29-browser.md Illustrates the breaking change in @kosko/env where the Environment class constructor is replaced by the createNodeCJSEnvironment function for initializing the Kosko environment. It provides 'Before' and 'After' code examples for migration. ```javascript // Before const { Environment } = require("@kosko/env"); const env = new Environment(process.cwd()); // After const { createNodeCJSEnvironment } = require("@kosko/env"); const env = createNodeCJSEnvironment({ cwd: process.cwd() }); ``` -------------------------------- ### TypeScript Interface for Nullable Type Example Source: https://github.com/tommy351/kosko/blob/master/website/blog/2022-11-06-kosko-3.0.md This TypeScript interface `IPod` defines an optional `spec` property, which is used as an example to demonstrate the improvements in error reporting for nullable types within `kubernetes-models`. ```TypeScript interface IPod { spec?: IPodSpec; } ``` -------------------------------- ### Create a Basic Kosko Plugin Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/creating-plugin.mdx This snippet demonstrates the minimal structure of a Kosko plugin. A plugin is defined as a factory function that takes a `PluginContext` and returns an object of hooks. In this basic example, no hooks are returned, making it a placeholder plugin. ```typescript import type { Plugin, PluginContext } from "@kosko/plugin"; export default function (ctx: PluginContext): Plugin { return {}; } ``` -------------------------------- ### Generate Kubernetes Component with HPA using Kosko Template Source: https://github.com/tommy351/kosko/blob/master/website/docs/templates.mdx This example demonstrates how to use a Kosko template to generate a Kubernetes component, specifically a Horizontal Pod Autoscaler (HPA). The template defines options for deployment name, replica counts, and CPU utilization, and dynamically creates a JavaScript module representing the HPA resource. The generated output can be seen in the provided example link. ```ts import { run } from "@kosko/template"; run({ description: "Create a new HPA", options: { deployment: { type: "string", description: "Deployment name", required: true }, minReplicas: { type: "number", description: "Minimum number of replicas", default: 1 }, maxReplicas: { type: "number", description: "Maximum number of replicas", required: true }, cpu: { type: "number", description: "Target CPU utilization", default: 70 } }, async generate(args) { return { files: [ { path: `components/${args.deployment}_hpa.js`, content: `"use strict"; const { HorizontalPodAutoscaler } = require("kubernetes-models/autoscaling/v1"); module.exports = new HorizontalPodAutoscaler({ metadata: { name: "${args.deployment}" }, spec: { scaleTargetRef: { apiVersion: "apps/v1", kind: "Deployment", name: "${args.deployment}" }, minReplicas: ${args.minReplicas}, maxReplicas: ${args.maxReplicas}, targetCPUUtilizationPercentage: ${args.cpu} } }); ` } ] }; } }); ``` ```js "use strict";\n\nconst { HorizontalPodAutoscaler } = require("kubernetes-models/autoscaling/v1");\n\nmodule.exports = new HorizontalPodAutoscaler({\n metadata: {\n name: "${args.deployment}"\n },\n spec: {\n scaleTargetRef: {\n apiVersion: "apps/v1",\n kind: "Deployment",\n name: "${args.deployment}"\n },\n minReplicas: ${args.minReplicas},\n maxReplicas: ${args.maxReplicas},\n targetCPUUtilizationPercentage: ${args.cpu}\n }\n});\n ``` -------------------------------- ### Retrieve Environment Variables with Async Kosko (Wrapped Function) Source: https://github.com/tommy351/kosko/blob/master/website/docs/using-in-browser.mdx This example provides an alternative for environments or bundlers that do not support top-level `await`. It demonstrates wrapping component resolution logic within an `async` function to correctly handle asynchronous environment variable retrieval. ```javascript import env from "@kosko/env"; export default async function () { const params = await env.component("demo"); return [new Deployment()]; } ``` -------------------------------- ### Configure Kosko Plugin Usage Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/set-metadata.mdx Example TOML configuration to enable the `@kosko/plugin-set-metadata` plugin in Kosko. ```toml [[plugins]] name = "@kosko/plugin-set-metadata" ``` -------------------------------- ### Configure Module Loaders in Kosko TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Example of specifying module loaders in kosko.toml for ECMAScript modules, such as 'ts-node/esm'. ```toml # Using TypeScript loaders = ["ts-node/esm"] ``` -------------------------------- ### Configure `allow` rule for ServiceAccount references Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-service-account.md Examples demonstrating how to configure the `allow` option for the `no-missing-service-account` rule, specifying which ServiceAccount references are permitted to be missing. This option uses TOML syntax. ```TOML allow = [{ namespace = "foo", name = "bar" }] ``` ```TOML allow = [{ namespace = "foo", name = "*" }] ``` -------------------------------- ### Generate Deployed Service Component using Kosko Template Source: https://github.com/tommy351/kosko/blob/master/packages/template-deployed-service/README.md This command-line example demonstrates how to use the `@kosko/template-deployed-service` package via `npx` to generate a new component, specifying the deployment and service name as 'nginx' and the container image as 'nginx'. ```sh npx @kosko/template-deployed-service --name nginx --image nginx ``` -------------------------------- ### Extend an Existing Kosko Preset with Custom Rules Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/creating-preset.mdx This example shows how to extend an existing Kosko preset, such as the recommended linting preset, and add custom rules. It demonstrates adding a 'ban-image' rule with specific configuration to prevent the use of ':latest' image tags. ```ts export default { extends: ["@kosko/plugin-lint/presets/recommended"], rules: { "ban-image": { severity: "error", config: { images: ["*:latest"] } } } }; ``` -------------------------------- ### Load Helm Chart from Remote Repository Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-helm-chart.mdx Shows how to load a Helm chart from a remote Helm repository. This example specifies the chart name, the repository URL, and a particular version of the chart. ```typescript import { loadChart } from "@kosko/helm"; loadChart({ chart: "prometheus", repo: "https://prometheus-community.github.io/helm-charts", version: "13.6.0" }); ``` ```javascript import { loadChart } from "@kosko/helm"; loadChart({ chart: "prometheus", repo: "https://prometheus-community.github.io/helm-charts", version: "13.6.0" }); ``` -------------------------------- ### Configure 'allow' for a specific namespace and name Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-pvc.md This configuration example demonstrates how to allow a specific PersistentVolumeClaim reference to be missing. It targets a PVC by its exact namespace and name. ```toml allow = [{ namespace = "foo", name = "bar" }] ``` -------------------------------- ### Allow All Services in Specific Namespace in TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/require-service-selector.md Configuration example for the 'allow' option, demonstrating how to exempt all services within a given namespace from the 'require-service-selector' rule. ```toml allow = [{ namespace = "foo", name = "*" }] ``` -------------------------------- ### Load Kubernetes YAML from a URL using @kosko/yaml Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-kubernetes-yaml.mdx Shows how to load Kubernetes YAML manifests directly from a remote URL using the `loadUrl` function from `@kosko/yaml`. This example fetches a `cert-manager.yaml` file. ```ts import { loadUrl } from "@kosko/yaml"; // Load from a URL loadUrl( "https://github.com/jetstack/cert-manager/releases/download/v1.0.4/cert-manager.yaml" ); ``` -------------------------------- ### Export Multiple Kubernetes Manifests from a Component Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx Example of a Kosko component `components/nginx.js` that exports an array containing both a `Deployment` and a `Service` manifest, demonstrating how to group related resources. ```ts import { Deployment } from "kubernetes-models/apps/v1/Deployment"; import { Service } from "kubernetes-models/v1/Service"; const labels = { app: "nginx" }; const deployment = new Deployment({ metadata: { name: "nginx" }, spec: { selector: { matchLabels: labels }, template: { metadata: { labels }, spec: { containers: [{ name: "nginx", image: "nginx" }] } } } }); const service = new Service({ metadata: { name: "nginx" }, spec: { selector: labels, ports: [{ port: 80 }] } }); export default [deployment, service]; ``` -------------------------------- ### Configure Kosko Lint Plugin with Recommended Rules Source: https://github.com/tommy351/kosko/blob/master/website/blog/2024-03-28-kosko-4.1.md Example TOML configuration to enable the @kosko/plugin-lint plugin. It extends the plugin's functionality by incorporating a preset of recommended rules, providing comprehensive validation beyond basic OpenAPI schema checks for Kubernetes manifests. ```toml [[plugins]] name = "@kosko/plugin-lint" config.extends = ["@kosko/plugin-lint/presets/recommended"] ``` -------------------------------- ### Export an Iterable (Set) of Kubernetes Manifests Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx Example of exporting a `Set` object containing Kubernetes manifests, demonstrating support for iterable protocols in Kosko components. ```ts // Set export default new Set([new Deployment(), new Service()]); ``` -------------------------------- ### Configure 'allow' for all names in a specific namespace Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-pvc.md This configuration example shows how to allow all PersistentVolumeClaim references within a specified namespace to be missing. The wildcard '*' is used for the name. ```toml allow = [{ namespace = "foo", name = "*" }] ``` -------------------------------- ### Import a Custom Resource Definition (CRD) Model Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx Example of importing a specific Custom Resource Definition (CRD) model, such as `Certificate` from `@kubernetes-models/cert-manager`, demonstrating support for 3rd-party models. ```ts import { Certificate } from "@kubernetes-models/cert-manager/cert-manager.io/v1/Certificate"; ``` -------------------------------- ### Migrate Kubernetes YAML files to JavaScript using kosko CLI Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/loading-kubernetes-yaml.mdx Demonstrates how to use the `kosko migrate` CLI command to convert existing Kubernetes YAML files into JavaScript files. Examples include reading from a file or directory, and piping from standard input. ```shell # Read from file or a directory kosko migrate -f manifest.yaml > components/nginx.js # Read from stdin cat manifest.yaml | kosko migrate -f - > components/nginx.js ``` -------------------------------- ### Configure a Kosko plugin with custom settings in kosko.toml Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/index.md This TOML configuration shows how to provide additional settings to a Kosko plugin. The `config` field allows passing key-value pairs, such as `key = "value"` for the 'example' plugin. ```TOML [[plugins]] name = "example" config.key = "value" ``` -------------------------------- ### Clean built project files Source: https://github.com/tommy351/kosko/blob/master/CONTRIBUTING.md Executes a predefined script to remove compiled or generated files from the project directory. This command is typically used to ensure a clean build environment before a new compilation. ```sh npm run clean ``` -------------------------------- ### Extend Kosko Lint Configuration (TOML) Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/index.mdx Examples of using the `extends` property in TOML to load lint configurations from external sources. This includes loading a predefined preset or a custom configuration from a local JavaScript or JSON file. ```toml # Preset extends = ["@kosko/plugin-lint/presets/recommended"] ``` ```toml # Local file extends = ["./lint-config.js"] ``` -------------------------------- ### Load a Helm chart with @kosko/helm in JavaScript Source: https://github.com/tommy351/kosko/blob/master/website/blog/2021-04-05-helm.md This JavaScript example demonstrates how to use the `loadChart` function from `@kosko/helm` to programmatically load a Helm chart. It specifies the chart's name, repository URL, version, and custom `values` to override default chart configurations. ```js const { loadChart } = require("@kosko/helm"); loadChart({ name: "prom", chart: "prometheus", repo: "https://prometheus-community.github.io/helm-charts", version: "13.6.0", values: { server: { persistentVolume: { enabled: true } } } }); ``` -------------------------------- ### Define a Basic Kubernetes Pod Component in TypeScript Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx Example of creating a simple Kosko component `components/busybox.js` that exports a single Kubernetes `Pod` manifest using the `kubernetes-models` library. This demonstrates importing `Pod` and instantiating it with metadata and spec. ```ts import { Pod } from "kubernetes-models/v1/Pod"; const pod = new Pod({ metadata: { name: "busybox" }, spec: { containers: [{ name: "busybox", image: "busybox" }] } }); export default pod; ``` -------------------------------- ### Initialize Kosko Project with create-kosko Source: https://github.com/tommy351/kosko/blob/master/website/docs/cli/create-kosko.md Demonstrates the basic usage of the `create-kosko` command to initialize a new Kosko project. The `[path]` argument is optional and defaults to the current directory. ```shell create-kosko [path] ``` -------------------------------- ### Configure Individual Kosko Lint Rule Properties (TOML) Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/index.mdx TOML example illustrating how to define the `severity` and `config` properties for a specific lint rule, such as `ban-image`. This demonstrates how to enable a rule as an error and provide rule-specific settings. ```toml [rules."ban-image"] severity = "error" config.images = ["*:latest"] ``` -------------------------------- ### Allow specific namespace in TOML configuration Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-namespace.md This TOML configuration example demonstrates how to allow a specific namespace, 'foo', to be missing without triggering the 'no-missing-namespace' rule. The 'allow' array specifies patterns for namespaces that are permitted to be undefined. ```toml allow = ["foo"] ``` -------------------------------- ### Kosko Streamlined Error Report with Warning Severity Source: https://github.com/tommy351/kosko/blob/master/website/blog/2024-03-28-kosko-4.1.md An example demonstrating the new warning severity in Kosko's error report system. It shows how non-critical issues, like a missing readiness probe, are flagged as warnings, allowing manifest generation to proceed successfully despite the identified potential improvement. ```text components/nginx.ts - apps/v1/Deployment nginx [0] ⚠ require-probe: Container "nginx" must define a readiness probe. warn - Found 1 warning in total info - Components are valid ``` -------------------------------- ### Import Kosko Modules from CDN in JavaScript Source: https://github.com/tommy351/kosko/blob/master/website/docs/using-in-browser.mdx This JavaScript example shows how to import Kosko environment and Kubernetes models directly from a CDN like JSPM. It leverages ECMAScript modules, enabling Kosko usage without a traditional bundler. The code retrieves component parameters and exports a new Deployment. ```js import env from "https://jspm.dev/@kosko/env"; import { Deployment } from "https://jspm.dev/kubernetes-models/apps/v1/Deployment"; const params = await env.component("demo"); export default [new Deployment()]; ``` -------------------------------- ### Correct Kubernetes Pod Manifest with Resource Requests (TypeScript) Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/require-container-resources.md This TypeScript example defines a Kubernetes Pod with a container that correctly specifies CPU and memory resource requests. It adheres to the `require-container-resources` rule, ensuring resource allocation is defined. ```typescript new Pod({ spec: { containers: [ { name: "nginx", image: "nginx", resources: { requests: { cpu: "100m", memory: "100Mi" } } } ] } }); ``` -------------------------------- ### Configure no-missing-pv rule with allow patterns Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-pv.md Examples demonstrating how to configure the 'allow' option for the 'no-missing-pv' rule in TOML. This option specifies PersistentVolume references that are permitted to be missing without triggering a rule violation. ```toml allow = [{ namespace = "foo", name = "bar" }] ``` ```toml allow = [{ namespace = "foo", name = "*" }] ``` -------------------------------- ### Apply TypeScript sidecar helper in Kubernetes Deployment Source: https://github.com/tommy351/kosko/blob/master/website/docs/recipes/sidecar.md This example demonstrates how to integrate the `withEnvoy` helper function into a Kubernetes `Deployment` definition. It shows how to use the function within the `spec.template.spec` to automatically add the Envoy sidecar to the application's pod. ```TypeScript import { Deployment } from "kubernetes-models/apps/v1/Deployment"; new Deployment({ spec: { template: { spec: withEnvoy({ containers: [ { name: "my-app", image: "my-app" } ] }) } } }); ``` -------------------------------- ### Validate Kosko Plugin Configuration with Superstruct Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/creating-plugin.mdx This example shows how to validate a plugin's configuration using Superstruct and Kosko's `validateConfig` function. It defines a schema for the expected configuration object and then applies it to the `ctx.config` property, ensuring that the plugin receives valid input. ```typescript import { type Plugin, type PluginContext, validateConfig } from "@kosko/plugin"; import { object, string } from "superstruct"; const schema = object({ foo: string() }); export default function (ctx: PluginContext): Plugin { const config = validateConfig(ctx.config, schema); return {}; } ``` -------------------------------- ### Configure 'allow' patterns for missing Service references (TOML) Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-service.md Examples demonstrating how to configure the 'allow' option in TOML to permit specific Service references to be missing. This configuration supports exact matches for namespace and name, wildcards for names within a namespace, and specific patterns for services. ```TOML allow = [{ namespace = "foo", name = "bar" }] ``` ```TOML allow = [{ namespace = "foo", name = "*" }] ``` ```TOML allow = [{ namespace = "envoy-gateway-system", name = "envoy-default-*" }] ``` -------------------------------- ### Kosko Streamlined Error Report for Manifest Failures Source: https://github.com/tommy351/kosko/blob/master/website/blog/2024-03-28-kosko-4.1.md This example illustrates Kosko's improved error reporting for manifest generation failures. It displays concise, single-line summaries of manifest information (e.g., file, kind, namespace) followed by detailed validation errors, such as type mismatches or missing references. ```text components/nginx.ts - apps/v1/Deployment dev/nginx [0] ✖ /spec/replicas must be integer ✖ no-missing-namespace: Namespace "dev" does not exist or is not allowed. components/nginx.ts - v1/Service nginx [1] ✖ unique-service-port-name: Service contains multiple ports with the same name "http" error - Found 3 errors in total error - Generate failed ``` -------------------------------- ### Correct Pod Manifest: Defining Volume Mounts and Volumes in TypeScript Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-pod-volume-mount.md This example illustrates a Kubernetes Pod manifest written in TypeScript, demonstrating the correct way to define a volume mount. It shows a "volumeMounts" entry with "name: \"config\"" and a corresponding "volumes" entry with "name: \"config\"", ensuring all mounted volumes are properly defined and satisfying the 'no-missing-pod-volume-mount' rule. ```ts new Pod({ spec: { containers: [ { name: "nginx", image: "nginx", volumeMounts: [{ name: "config", mountPath: "/etc/nginx" }] } ], volumes: [{ name: "config", configMap: { name: "nginx" } }] } }); ``` -------------------------------- ### Initialize Kosko Project using npm or yarn Source: https://github.com/tommy351/kosko/blob/master/website/docs/cli/create-kosko.md Shows how to execute `create-kosko` using `npm init` or `yarn create` commands. This method ensures the latest version of `create-kosko` is used for project initialization. ```npm npm init kosko@latest [path] ``` ```yarn yarn create kosko@latest [path] ``` -------------------------------- ### Configure TOML to allow specific Deployment scale target Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-scale-target.md This configuration example demonstrates how to use the `allow` option to permit a specific Deployment (with `apiVersion`, `kind`, `namespace`, and `name` attributes) to be missing its scale target reference. This is useful for whitelisting known exceptions. ```toml allow = [{ apiVersion = "apps/v1", kind = "Deployment", namespace = "foo", name = "bar" }] ``` -------------------------------- ### Create New Kosko Environment via CLI Source: https://github.com/tommy351/kosko/blob/master/packages/template-environment/README.md This command-line interface (CLI) snippet demonstrates how to initialize a new environment using the `@kosko/template-environment` package. The `--name` option is required to specify the environment's name, as shown with 'dev'. ```sh npx @kosko/template-environment --name dev ``` -------------------------------- ### Create and Export Kubernetes Manifests with Nested Functions Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx This example demonstrates how to define a reusable function `createDatabase` that generates Kubernetes Deployment and Service manifests. It then exports an array combining the output of this function with additional standalone Deployment and Service manifests, showcasing how nested functions and arrays are flattened into a single set of resources, which is then presented as the final YAML output. ```typescript import { Deployment } from "kubernetes-models/apps/v1/Deployment"; import { Service } from "kubernetes-models/v1/Service"; function createDatabase(name: string) { const metadata = { name: `${name}-db` }; return [new Deployment({ metadata }), new Service({ metadata })]; } export default [ createDatabase("my-app"), new Deployment({ metadata: { name: "my-app" } }), new Service({ metadata: { name: "my-app" } }) ]; ``` ```yaml --- apiVersion: apps/v1 kind: Deployment metadata: name: my-app-db --- apiVersion: v1 kind: Service metadata: name: my-app-db --- apiVersion: apps/v1 kind: Deployment metadata: name: my-app --- apiVersion: v1 kind: Service metadata: name: my-app ``` -------------------------------- ### Configure 'allow' option for 'no-missing-role' rule Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/no-missing-role.md Examples demonstrating how to configure the 'allow' option to permit specific Role or ClusterRole references to be missing. This option accepts an array of objects, where each object specifies the 'kind' (Role or ClusterRole), 'name', and optionally 'namespace' for the allowed missing reference. ```TOML allow = [{ kind = "ClusterRole", name = "foo" }] ``` ```TOML allow = [{ kind = "Role", namespace = "foo", name = "bar" }] ``` -------------------------------- ### Programmatically Generate Kosko Manifests with ESM Source: https://github.com/tommy351/kosko/blob/master/website/docs/ecmascript-modules.mdx This JavaScript example illustrates how to programmatically generate and print Kubernetes manifests using @kosko/env and @kosko/generate in an ECMAScript Module (ESM) context. It sets the environment, current working directory, generates manifests from components, and prints them to standard output in YAML format. ```javascript import env from "@kosko/env"; import { generate, print, PrintFormat } from "@kosko/generate"; import { fileURLToPath } from "node:url"; import { join } from "node:path"; // Set environment env.env = "dev"; // Set CWD (optional) env.cwd = fileURLToPath(new URL("./", import.meta.url)); // Generate manifests const result = await generate({ path: join(env.cwd, "components"), components: ["*"] }); // Print manifests to stdout print(result, { format: PrintFormat.YAML, writer: process.stdout }); ``` -------------------------------- ### Configure Kosko Synchronous Environment Source: https://github.com/tommy351/kosko/blob/master/website/docs/using-in-browser.mdx This code shows how to create and configure a synchronous Kosko environment using `createSyncEnvironment` and `createSyncLoaderReducers`. This approach avoids the need for `await` when retrieving environment variables, but restricts the use of dynamic imports within the environment loader. ```javascript import { createSyncEnvironment, createSyncLoaderReducers } from "@kosko/env"; const env = createSyncEnvironment(); env.setReducers((reducers) => [ ...reducers, ...createSyncLoaderReducers({ global: () => {}, component: (name) => {} }) ]); export default env; ``` -------------------------------- ### Load Kustomize files with loadKustomize function Source: https://github.com/tommy351/kosko/blob/master/website/blog/2021-12-19-kustomize.md This JavaScript snippet demonstrates how to use the loadKustomize function from @kosko/kustomize to load Kustomize configurations from a specified directory. The path option indicates the location of the Kustomize files. ```js const { loadKustomize } = require("@kosko/kustomize"); loadKustomize({ path: "./dir" }); ``` -------------------------------- ### Illustrate Kosko Component Folder Structure Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx This shell snippet shows the recommended folder structure for Kosko components, where components are placed in `components/.js` or `components//index.js`. ```shell . └── components ├── foo │ └── index.js └── nginx.js ``` -------------------------------- ### Kosko Configuration File (kosko.toml) API Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Detailed API documentation for the kosko.toml configuration file, covering global settings, environment-specific overrides, and path definitions with their types, defaults, and descriptions. ```APIDOC kosko.toml Configuration: Global Configs: bail: Type: boolean Default: false Description: Stop immediately when an error occurred. Availability: kosko 3.0.0+ baseEnvironment: Type: string (environment name) Description: Specify the base environment for merging variables. Can be used with or without --env, -e. components: Type: array of strings (component names or glob patterns) Description: Components to generate. If not provided in kosko.toml, must be provided via 'kosko generate' command. extensions: Type: array of strings (file extensions) Description: Extension names of components. Automatically detected via 'require.extensions'. import: Type: array of strings (module paths) Availability: kosko 4.2.0+ Description: Preload ES modules at startup. Only works when ECMAScript modules (ESM) is enabled. loaders: Type: array of strings (loader paths) Availability: kosko 3.0.0+ Description: Use module loaders. Only works when ECMAScript modules (ESM) is enabled. require: Type: array of strings (module paths) Description: Require CommonJS modules. plugins: Type: array of objects (plugin configurations) Availability: kosko 4.0.0+ Description: Plugin configurations. See Plugins for more details. Environment Configs: environments.: Type: object Description: Applied when running with '--env, -e'. Merged with global configs. Only 'components', 'loaders', 'require', and 'plugins' can be specified. Paths: Tokens: #{environment}: Environment name #{component}: Component name (Only available in 'paths.environment.component') paths.environment.global: Type: string (path pattern) Description: Specify path to global environment files. Default: environments/#{environment} paths.environment.component: Type: string (path pattern) Description: Specify path to component environment files. Default: environments/#{environment}/#{component} ``` -------------------------------- ### Export Kosko Components with `export default` in ESM Source: https://github.com/tommy351/kosko/blob/master/website/blog/2021-03-09-kosko-1.1.md This JavaScript example illustrates the new method for exporting Kosko components or environments when using ECMAScript Modules (ESM). Instead of the CommonJS `module.exports`, components should now be exported using `export default`. This snippet shows how to export an array containing Kubernetes `Deployment` and `Service` objects. ```js import { Deployment } from "kubernetes-models/apps/v1/Deployment"; import { Service } from "kubernetes-models/v1/Service"; export default [new Deployment({}), new Service({})]; ``` -------------------------------- ### Configure CommonJS Module Requiring in Kosko TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/configuration.mdx Example of requiring CommonJS modules in kosko.toml, useful for integrating with tools like 'ts-node/register'. ```toml # Using TypeScript require = ["ts-node/register"] ``` -------------------------------- ### Build Static Website Content with Yarn Source: https://github.com/tommy351/kosko/blob/master/website/README.md This command generates static HTML, CSS, and JavaScript files into the `build` directory, preparing the website for deployment. The output can be served using any static content hosting service. ```Shell yarn build ``` -------------------------------- ### Add Name Suffix in Kosko Configuration Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/set-metadata.mdx Example TOML configuration to add a suffix to the name of Kubernetes manifests using the Kosko plugin. ```toml name.suffix = "-dev" ``` -------------------------------- ### Validate All Manifests with `validateAllManifests` Hook Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/creating-plugin.mdx This snippet demonstrates the `validateAllManifests` hook, which provides access to all generated manifests for comprehensive validation. The example checks if every namespace referenced by a manifest actually has a corresponding `Namespace` resource defined within the set of manifests. It collects all defined namespaces first, then iterates through all manifests to report errors for undefined namespaces. ```typescript import type { Plugin, PluginContext } from "@kosko/plugin"; export default function (ctx: PluginContext): Plugin { return { validateAllManifests(manifests) { const namespaces = new Set(); // Collect namespaces for (const manifest of manifests) { if (manifest.data.kind === "Namespace") { namespaces.add(manifest.data.metadata.name); } } // Check if all namespaces are defined for (const manifest of manifests) { const namespace = manifest.data.metadata.namespace; if (namespace && !namespaces.has(namespace)) { manifest.report({ severity: "error", message: `Namespace "${namespace}" is not defined` }); } } } }; } ``` -------------------------------- ### Add Name Prefix in Kosko Configuration Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/set-metadata.mdx Example TOML configuration to add a prefix to the name of Kubernetes manifests using the Kosko plugin. ```toml name.prefix = "dev-" ``` -------------------------------- ### Set Namespace Value in Kosko Configuration Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/set-metadata.mdx Example TOML configuration to set a specific namespace value for Kubernetes manifests using the Kosko plugin. ```toml namespace.value = "dev" ``` -------------------------------- ### Initialize New Kosko Project with create-kosko Source: https://github.com/tommy351/kosko/blob/master/website/blog/2024-03-28-kosko-4.1.md This shell command demonstrates how to initialize a new Kosko project using npm init kosko@latest. It replaces the previously deprecated kosko init CLI command, providing a streamlined way to set up a new Kosko development environment. ```shell npm init kosko@latest example ``` -------------------------------- ### CLI Options for @kosko/template-environment Source: https://github.com/tommy351/kosko/blob/master/packages/template-environment/README.md This section documents the command-line options available for the `@kosko/template-environment` tool, detailing their purpose and requirements. ```APIDOC --name: description: Environment name. required: true ``` -------------------------------- ### Add Labels and Annotations in Kosko Configuration Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/set-metadata.mdx Example TOML configuration to add labels and annotations to Kubernetes manifests, including an option to override existing values. ```toml [[labels]] name = "environment" value = "dev" [[annotations]] name = "managed-by" value = "kosko" override = true ``` -------------------------------- ### create-kosko Command Line Interface (CLI) API Source: https://github.com/tommy351/kosko/blob/master/website/docs/cli/create-kosko.md Documents the available positionals and options for the `create-kosko` command-line tool, including their descriptions and usage. ```APIDOC Command: create-kosko Positionals: path: Description: Path to initialize. Default to the current directory. Options: --esm: Description: Generate ECMAScript module (ESM) files. --force, -f: Description: Overwrite existing files. --install: Description: Install dependencies automatically. --package-manager, --pm: Description: Package manager (npm, yarn, pnpm). If this option is not specified, Kosko will detect package manager based on lock files. --typescript, --ts: Description: Generate TypeScript files. ``` -------------------------------- ### Allow Specific Service by Namespace and Name in TOML Source: https://github.com/tommy351/kosko/blob/master/website/docs/plugins/lint/rules/require-service-selector.md Configuration example for the 'allow' option, specifying a service in a particular namespace and with a specific name that is exempt from the 'require-service-selector' rule. ```toml allow = [{ namespace = "foo", name = "bar" }] ``` -------------------------------- ### Import Kubernetes Model Classes and Interfaces Source: https://github.com/tommy351/kosko/blob/master/website/docs/components/index.mdx Demonstrates how to import specific Kubernetes resource classes and interfaces (e.g., `Kind`, `IKind`) from the `kubernetes-models` package, specifying the API version and kind. ```ts // Class import { Kind } from "kubernetes-models//"; // Interface import { IKind } from "kubernetes-models//"; ``` -------------------------------- ### Deploy Website to GitHub Pages with Yarn Source: https://github.com/tommy351/kosko/blob/master/website/README.md This command facilitates the deployment of the website to GitHub Pages. It builds the website and pushes the generated static content to the `gh-pages` branch of a GitHub repository. Remember to replace `` with your actual GitHub username. ```Shell GIT_USER= USE_SSH=true yarn deploy ```