### File Driver Configuration Example Source: https://github.com/coryodaniel/k8s/blob/develop/guides/discovery.md An example JSON structure for the File driver's configuration. It maps API versions to lists of resource metadata, including kind, name, namespaced status, and supported verbs. ```json { "v1": [ { "kind": "Namespace", "name": "namespaces", "namespaced": false, "verbs": [ "create", "delete", "get", "list", "patch", "update", "watch" ] } ], "apps/v1": [ { "kind": "Deployment", "name": "deployments", "namespaced": true, "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ] } ``` -------------------------------- ### List Kubernetes Deployments in a Namespace Source: https://github.com/coryodaniel/k8s/blob/develop/guides/usage.md This example shows how to list all deployments within a specific namespace. It requires a kubeconfig and specifies the target namespace. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, deployments} = K8s.Client.list("apps/v1", "Deployment", namespace: "prod") |> K8s.Client.put_conn(conn) |> K8s.Client.run() ``` -------------------------------- ### Configure Default Discovery Driver Source: https://github.com/coryodaniel/k8s/blob/develop/guides/discovery.md Set the default discovery driver and its options using Mix configuration. This example sets the File driver as default, using a specified JSON configuration file. ```elixir use Mix.Config config :k8s, discovery_driver: K8s.Discovery.Driver.File, discovery_opts: [config: "test/support/discovery/example.json"] ``` -------------------------------- ### Build and Use Label Selectors for Listing Deployments Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Construct complex label selectors programmatically to filter listed Deployments. This example filters by 'app' label and 'environment' label. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") operation = K8s.Client.list("apps/v1", :deployments) |> K8s.Selector.label({"app", "nginx"}) |> K8s.Selector.label_in({"environment", ["qa", "prod"]}) K8s.Client.run(conn, operation) ``` -------------------------------- ### Execute Commands in Pods with Specific Options Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Execute a command in a specific container within a pod, enabling TTY for interactive shell-like behavior. This example demonstrates passing the 'container' and 'tty' options to K8s.Client.connect/N. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") op = K8s.Client.connect( "v1", "pods/exec", [namespace: "default", name: "nginx-8f458dc5b-zwmkb"], command: ["/bin/sh", "-c", "nginx -t"], container: "main", tty: true ) {:ok, response} = K8s.Client.run(conn, op) ``` -------------------------------- ### List Operations as Elixir Streams Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Use K8s.Client.Runner.Stream to automatically handle pagination for K8s.Client.list/3 operations. This example streams pods, filters them, maps the results, and collects them into a list. ```elixir operation = K8s.Client.list("v1", "Pod", namespace: :all) {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") conn |> K8s.Client.stream(operation) |> Stream.filter(&my_filter_function?/1) |> Stream.map(&my_map_function?/1) |> Enum.into([]) ``` -------------------------------- ### Implement Custom Request Middleware Source: https://github.com/coryodaniel/k8s/blob/develop/guides/middleware.md Example of a custom request middleware that adds labels to all POST requests. Middleware must return {:ok, %Request{}} to continue or {:error, :my_error} to halt. ```elixir def call(%Request{method: :post, body: body} = req) do metadata = Map.get(body, "metadata", %{}) metadata_with_labels = Map.put(metadata, "labels", %{"env" => "prod"}) updated_body = Map.put(body, "metadata", metadata_with_labels) request_with_labels = %Request{req | body: updated_body} {:ok, request_with_labels} end ``` -------------------------------- ### Get Deployment Status Subresource Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Fetches the status subresource of a specific deployment. Requires a valid connection and deployment name/namespace. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") operation = K8s.Client.get("apps/v1", "deployments/status", name: "nginx", namespace: "default") {:ok, scale} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Get a Specific Kubernetes Deployment Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Retrieve a specific Deployment by its name and namespace. Requires a valid kubeconfig. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") operation = K8s.Client.get("apps/v1", :deployment, [namespace: "default", name: "nginx-deployment"]) {:ok, deployment} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Get Deployment Scale Subresource Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Retrieves the scale subresource for a given deployment. Ensure the connection and deployment details are correct. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") operation = K8s.Client.get("apps/v1", "deployments/scale", [name: "nginx", namespace: "default"]) {:ok, scale} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Get a Specific Kubernetes Deployment Source: https://github.com/coryodaniel/k8s/blob/develop/guides/usage.md Fetch details for a particular deployment by specifying its name and namespace. This requires a kubeconfig and the deployment's identifying information. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, deployment} = K8s.Client.get("apps/v1", :deployment, [namespace: "default", name: "nginx-deployment"]) |> K8s.Client.put_conn(conn) |> K8s.Client.run(conn, operation) ``` -------------------------------- ### Get a Specific Kubernetes Deployment Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Retrieves a specific deployment by its name and namespace from the Kubernetes cluster. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") operation = K8s.Client.get("apps/v1", :deployment, [namespace: "default", name: "nginx-deployment"]) {:ok, deployment} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Async Create Deployments on Staging Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Maps a list of deployment resources to create operations and executes them asynchronously on the staging cluster. Ensure staging connection is established. ```elixir {:ok, staging_conn} = K8s.Conn.from_service_account() # or from_file/2 operations = Enum.map(deployments, fn(deployment) -> K8s.Client.create(deployment) end) K8s.Client.async(staging_conn, operations) ``` -------------------------------- ### Integration Testing Commands Source: https://github.com/coryodaniel/k8s/blob/develop/guides/testing.md Makefile commands for integration testing against k3s. Run `make help` for a full list. ```bash test.integration Run integration tests using k3d `make cluster` test.watch Run all tests with mix.watch test Run all tests ``` -------------------------------- ### Create Kubernetes Deployment Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Creates a Kubernetes deployment by first loading a resource definition from a file and then executing the create operation using the configured connection. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") opts = [namespace: "default", name: "nginx", image: "nginx:nginx:1.7.9"] {:ok, resource} = K8s.Resource.from_file("priv/deployment.yaml", opts) operation = K8s.Client.create(resource) {:ok, deployment} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Configure Kubernetes Connection from File Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Establish a connection to your Kubernetes cluster using a kubeconfig file. `K8s.Conn.from_file/1` uses the current context, while `K8s.Conn.from_file/2` allows specifying user, cluster, or context. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") ``` ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml", [user: "my-user", context: "my-context"]) ``` -------------------------------- ### Create Kubernetes Deployment from YAML File Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Create a Kubernetes Deployment from a YAML file with interpolation support. Provide options for namespace, name, and image. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: <%= name %>-deployment namespace: <%= namespace %> labels: app: <%= name %> spec: replicas: 3 selector: matchLabels: app: <%= name %> template: metadata: labels: app: <%= name %> spec: containers: - name: <%= name %> image: <%= image %> ports: - containerPort: 80 ``` ```elixir opts = [namespace: "default", name: "nginx", image: "nginx:nginx:1.7.9"] resource = K8s.Resource.from_file!("priv/deployment.yaml", opts) operation = K8s.Client.create(resource) {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, deployment} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Create Kubernetes Deployment from Map Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Use this to create a Kubernetes Deployment by defining its resource configuration as a map. Ensure you have a valid kubeconfig file. ```elixir resource = %{ "apiVersion" => "apps/v1", "kind" => "Deployment", "metadata" => %{ "labels" => %{"app" => "nginx"}, "name" => "nginx-deployment", "namespace" => "default" }, "spec" => %{ "replicas" => 3, "selector" => %{"matchLabels" => %{"app" => "nginx"}}, "template" => %{ "metadata" => %{"labels" => %{"app" => "nginx"}}, "spec" => %{ "containers" => [ %{ "image" => "nginx:1.7.9", "name" => "nginx", "ports" => [%{"containerPort" => 80}] } ] } } } } operation = K8s.Client.create(resource) {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, response} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Create Kubernetes Deployment Source: https://github.com/coryodaniel/k8s/blob/develop/guides/usage.md Use this snippet to create a new Kubernetes deployment. Ensure you have a valid kubeconfig file and a deployment resource definition. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") opts = [namespace: "default", name: "nginx", image: "nginx:nginx:1.7.9"] {:ok, resource} = K8s.Resource.from_file("priv/deployment.yaml", opts) {:ok, deployment} = resource |> K8s.Client.create() |> K8s.Client.put_conn(conn) |> K8s.Client.run() ``` -------------------------------- ### List Supported Resources for an API Version via HTTP Source: https://github.com/coryodaniel/k8s/blob/develop/guides/discovery.md Query the HTTP driver to retrieve a list of supported resources for a specific API version (e.g., 'apps/v1'). This helps in understanding the available resource kinds and their operations. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") K8s.Discovery.Driver.HTTP.resources("apps/v1", conn) [ { "kind": "DaemonSet", "name": "daemonsets", "namespaced": true, "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "kind": "Deployment", "name": "deployments", "namespaced": true, "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } # ... ] ``` -------------------------------- ### List Kubernetes Deployments Across All Namespaces Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md List all Deployments across all namespaces. The results will be in the 'items' field of the returned map. Requires a valid kubeconfig. ```elixir operation = K8s.Client.list("apps/v1", "Deployment", namespace: :all) {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, deployments} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Register Staging Cluster Connection Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Establishes a connection to a staging Kubernetes cluster using a kubeconfig file. Ensure the file path is correct. ```elixir {:ok, staging_conn} = K8s.Conn.from_file("~/.kube/config") ``` -------------------------------- ### Stream Logs from Pods with Follow Option Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Connect to the pods/log subresource to stream logs from a specific container in a pod. The 'follow: true' option enables continuous log streaming, and the logs are processed using K8s.Client.stream/N. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") {:ok, stream} = K8s.Client.connect( "v1", "pods/log", [namespace: "default", name: "nginx-8f458dc5b-zwmkb"], command: ["/bin/sh", "-c", "nginx -t"], container: "main", follow: true ) |> K8s.Client.put_conn(conn) |> K8s.Client.stream() ``` -------------------------------- ### List Custom Resources Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Lists custom resources of a specific kind from a given namespace. Ensure the custom resource definition is available. ```elixir operation = K8s.Client.list("hello-operator.example.com/v1", :greeting, [namespace: "default"]) {:ok, greeting} = K8s.Client.run(operation, :dev) ``` -------------------------------- ### Configure File Discovery Driver Source: https://github.com/coryodaniel/k8s/blob/develop/guides/testing.md Set the `K8s.Discovery.Driver.File` to stub API resource and version responses when a Kubernetes cluster is unavailable. Configure for all clusters or per-cluster. ```elixir config :k8s, discovery_driver: K8s.Discovery.Driver.File, discovery_opts: [config: "test/support/discovery/example.json"] ``` -------------------------------- ### Execute Commands in Pods and Wait for Termination Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Connect to the pods/exec subresource using K8s.Client.connect/N and execute a command that terminates. The command's output and exit status are returned by K8s.Client.run/N. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") op = K8s.Client.connect( "v1", "pods/exec", [namespace: "default", name: "nginx-8f458dc5b-zwmkb"], command: ["/bin/sh", "-c", "nginx -t"] ) {:ok, response} = K8s.Client.run(conn, op) ``` -------------------------------- ### Create K8s Connection from Kubeconfig File Source: https://github.com/coryodaniel/k8s/blob/develop/guides/connections.md Establishes a connection using a specified kubeconfig file. Allows selection of a specific cluster, user, or context. ```elixir {:ok, conn} = K8s.Conn.from_file("/path/to/kube/config", context: "your-context-name-here") ``` -------------------------------- ### List Kubernetes Deployments in a Namespace Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md List all Deployments within a specific namespace. Requires a valid kubeconfig. ```elixir operation = K8s.Client.list("apps/v1", "Deployment", namespace: "prod") {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, deployments} = K8s.Client.run(conn, operation) ``` -------------------------------- ### List Supported API Versions via HTTP Source: https://github.com/coryodaniel/k8s/blob/develop/guides/discovery.md Use the HTTP driver directly to list all supported API versions for a given Kubernetes connection. Ensure a valid kubeconfig path is provided. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") K8s.Discovery.Driver.HTTP.versions(conn) ["v1", "apps/v1", "batch/v1"] ``` -------------------------------- ### List Deployments in Production Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Retrieves a list of all deployments within the 'default' namespace of the production cluster. Requires an active production connection. ```elixir {:ok, prod_conn} = K8s.Conn.from_service_account() # or from_file/2 operation = K8s.Client.list("apps/v1", :deployment, namespace: "default") {:ok, deployments} = K8s.Client.run(prod_conn, operation) ``` -------------------------------- ### List Kubernetes Deployments Across All Namespaces Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Fetches a list of all deployments across all namespaces in the Kubernetes cluster. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") operation = K8s.Client.list("apps/v1", "Deployment", namespace: :all) {:ok, deployments} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Configure Dynamic HTTP Provider Source: https://github.com/coryodaniel/k8s/blob/develop/guides/testing.md Enable the `K8s.Client.DynamicHTTPProvider` in your `config.exs` to stub HTTP responses for Kubernetes API requests. ```elixir config :k8s, http_provider: K8s.Client.DynamicHTTPProvider ``` -------------------------------- ### Change Connection Middleware Stack Source: https://github.com/coryodaniel/k8s/blob/develop/guides/middleware.md Demonstrates how to replace the entire middleware stack for a given K8s connection. ```elixir {:ok, conn} = K8s.Conn.from_service_account() new_stack = K8s.Middleware.Stack{request: [MyFirstMiddleware, MySecondMiddleware]} conn_with_new_middleware = %K8s.Conn{conn | middleware: new_stack} ``` -------------------------------- ### List Kubernetes Deployments Across All Namespaces Source: https://github.com/coryodaniel/k8s/blob/develop/guides/usage.md Retrieve a list of all deployments across all namespaces in your Kubernetes cluster. This uses `namespace: :all` to query globally. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, deployments} = K8s.Client.list("apps/v1", "Deployment", namespace: :all) |> K8s.Client.put_conn(conn) |> K8s.Client.run() ``` -------------------------------- ### Configure Custom Authentication Providers Source: https://github.com/coryodaniel/k8s/blob/develop/guides/authentication.md Specify custom authentication providers in your Mix configuration. These providers will be attempted before the default strategies. ```elixir config :k8s, auth_providers: [CustomProvider1, CustomProvider2] ``` -------------------------------- ### Evict Pod by Providing Details Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Evicts a pod by specifying details directly in the K8s.Client.create function. This method is an alternative to building a full Pod map. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") eviction = %{ "apiVersion" => "policy/v1beta1", "kind" => "Eviction", "metadata" => %{ "name" => "nginx", } } subject = K8s.Client.create("v1", "pods/eviction", [namespace: "default", name: "nginx"], eviction) operation = K8s.Client.create(subject, eviction) {:ok, resp} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Create K8s Connection from Environment Variable Source: https://github.com/coryodaniel/k8s/blob/develop/guides/connections.md Reads the KUBECONFIG environment variable to establish a connection. Defaults to the KUBECONFIG variable if none is specified. ```elixir {:ok, conn} = K8s.Conn.from_env() ``` ```elixir {:ok, conn} = K8s.Conn.from_env("K8S_CONFIG_FILE") ``` -------------------------------- ### Create K8s Connection from Service Account Source: https://github.com/coryodaniel/k8s/blob/develop/guides/connections.md Connects using the default service account path. The path can be optionally specified. ```elixir {:ok, conn} = K8s.Conn.from_service_account() ``` ```elixir {:ok, conn} = K8s.Conn.from_service_account("/path/to/service/account/directory") ``` -------------------------------- ### Configure Kubernetes Connection from Service Account Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Create a Kubernetes connection when running inside a cluster using the service account credentials located in the specified directory. ```elixir {:ok, conn} = K8s.Conn.from_service_account("/path/to/service-account/directory") ``` -------------------------------- ### List Kubernetes Deployments in a Namespace Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Retrieves a list of all deployments within a specified namespace using the Kubernetes API. ```elixir {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") operation = K8s.Client.list("apps/v1", "Deployment", namespace: "prod") {:ok, deployments} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Create K8s Connection Struct Programmatically Source: https://github.com/coryodaniel/k8s/blob/develop/guides/connections.md Manually constructs a K8s.Conn struct for advanced use cases like multi-tenant services. Requires PKI certificate generation. ```elixir {:ok, cert} = K8s.Conn.PKI.cert_from_map(cluster, base_path) %K8s.Conn{ url: "https://ip-address-of-cluster", ca_cert: cert, auth: %K8s.Conn.Auth{}, insecure_skip_tls_verify: false, discovery_driver: K8s.Discovery.Driver.HTTP, discovery_opts: [cache: true] } ``` -------------------------------- ### Set Discovery Driver Per Connection Source: https://github.com/coryodaniel/k8s/blob/develop/guides/discovery.md Configure a specific discovery driver for an individual Kubernetes connection. This allows overriding the default driver for particular connection instances. ```elixir {:ok, conn} = K8s.Conn.from_file("....") conn = %K8s.Conn{conn | discovery_driver: AlternateDriver} ``` -------------------------------- ### Register Production Cluster Connection Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Establishes a connection to a production Kubernetes cluster using a service account. This is common for in-cluster applications. ```elixir {:ok, prod_conn} = K8s.Conn.from_service_account() # or from_file/2 ``` -------------------------------- ### Evict Pod using Pod Map Source: https://github.com/coryodaniel/k8s/blob/develop/guides/advanced.md Evicts a pod by providing a Pod map and using K8s.Resource.build/4. Ensure the eviction object and subject details are accurate. ```elixir {:ok, conn} = K8s.Conn.from_file("~/.kube/config") eviction = %{ "apiVersion" => "policy/v1beta1", "kind" => "Eviction", "metadata" => %{ "name" => "nginx", } } # Here we use K8s.Resource.build/4 but this k8s resource map could be built manually or retrieved from the k8s API subject = K8s.Resource.build("v1", "Pod", "default", "nginx") operation = K8s.Client.create(subject, eviction) {:ok, resp} = K8s.Client.run(conn, operation) ``` -------------------------------- ### Migrate K8s Mock Request Query Parameters Source: https://github.com/coryodaniel/k8s/blob/develop/guides/migrations.md Update K8s.Client.Provider.request/N mocks to match the URI struct for query parameter matching. ```elixir defmodule K8sMock do def request(:get, "/api/v1/namespaces", _body, _headers, params: [labelSelector: "app=nginx"]) do # code end end ``` ```elixir defmodule K8sMock do def request(:get, %URI{path: "/api/v1/namespaces", query: "labelSelector=app%3Dnginx"}, _body, _headers, _opts) do # code end end ``` -------------------------------- ### Open Long-Lived Connections to Pods for Interactive Commands Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Use K8s.Client.stream_to/3 to open a persistent connection to a pod for interactive commands like a shell. This function returns a callback for sending messages to the pod and receiving stdout/stderr. ```elixir defmodule TestPodExec do require Logger def recv_loop() do receive do {:open, true} -> Logger.debug("Connection established.") recv_loop() {:stdout, msg} -> Logger.info(~s(Message received on stdout: "#{msg}")) recv_loop() {:close, reason} -> Logger.debug("Connection closed. Reason: #{inspect(reason)}") end end def run() do {:ok, pid} = Task.start_link(fn -> recv_loop() end) {:ok, conn} = K8s.Conn.from_file("~/.kube/config") op = K8s.Client.connect( "v1", "pods/exec", [namespace: "default", name: "nginx-8f458dc5b-zwmkb"], command: ["/bin/sh"], tty: true ) {:ok, send_to_pod} = K8s.Client.stream_to(conn, op, pid) Process.sleep(1000) send_to_pod.(:stdin, ~s(echo "hello world"\n)) Process.sleep(1000) send_to_pod.(:close) Process.sleep(1000) end end TestPodExec.run() ``` -------------------------------- ### Mock K8s API Responses Source: https://github.com/coryodaniel/k8s/blob/develop/guides/testing.md Register a mock module with `DynamicHTTPProvider` to stub HTTP responses for `K8s.Operations`. The mock module must implement a `request/5` function that returns an `HTTPoison.Response`. ```elixir defmodule MyApp.ResourceTest do use ExUnit.Case, async: true defmodule K8sMock do @namespaces_path "/api/v1/namespaces" def request(:get, %URI{path: @namespaces_path}, _, _, _) do namespaces = [%{"metadata" => %{"name" => "default"}}] body = Jason.encode!(namespaces) {:ok, %HTTPoison.Response{status_code: 200, body: body}} end end setup do DynamicHTTPProvider.register(self(), __MODULE__.K8sMock) end test "gets namespaces" do conn = %K8s.Conn{} # set up your conn operation = K8s.Client.get("v1", :namespaces) assert {:ok, namespaces} = K8s.Client.run(conn, operation) assert namespaces == [%{"metadata" => %{"name" => "default"}}] end end ``` -------------------------------- ### Migrate K8s Mock Request Path Source: https://github.com/coryodaniel/k8s/blob/develop/guides/migrations.md Update K8s.Client.Provider.request/N mocks to match the URI struct for path matching. ```elixir defmodule K8sMock do def request(:get, "/api/v1/namespaces", _body, _headers, _opts) do # code end end ``` ```elixir defmodule K8sMock do def request(:get, %URI{path: "/api/v1/namespaces"}, _body, _headers, _opts) do # code end end ``` -------------------------------- ### Stream Watch Events to Self Source: https://github.com/coryodaniel/k8s/blob/develop/guides/migrations.md Use K8s.Client.watch/N and K8s.Client.Runner.Base.stream_to/N to stream watch events to the current process. The `stream_to` option has been removed. ```elixir :ok = K8s.Client.watch("v1", "ConfigMap", namespace: "default") |> K8s.Client.put_conn(conn) |> K8s.Client.Runner.Base.stream_to(self()) receive do event -> IO.inspect(event) end ``` -------------------------------- ### Run Kubernetes Operations Asynchronously Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Execute multiple Kubernetes operations in parallel using the async runner. Results are returned as a list of :ok or :error tuples, and processing continues even if one operation fails. ```elixir operation1 = K8s.Client.get("v1", "Pod", namespace: "default", name: "pod-1") operation2 = K8s.Client.get("v1", "Pod", namespace: "default", name: "pod-2") {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") results = K8s.Client.async(conn, [operation1, operation2]) ``` -------------------------------- ### Stream Kubernetes Events with Watch Operation Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Use the Watch API to stream 'added', 'modified', and 'deleted' events for Deployments across all namespaces. Requires a valid kubeconfig. ```elixir operation = K8s.Client.watch("apps/v1", :deployment, namespace: :all) {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, event_stream} = K8s.Client.stream(conn, operation) ``` -------------------------------- ### Add K8s Dependency to Mix Project Source: https://github.com/coryodaniel/k8s/blob/develop/README.md Add the :k8s package to your `mix.exs` dependencies to include it in your Elixir project. ```elixir def deps do [ {:k8s, "~> 2.0"} ] end ``` -------------------------------- ### Handle HTTP Errors with K8s.Client.HTTPError Source: https://github.com/coryodaniel/k8s/blob/develop/guides/migrations.md Replace HTTPoison error handling with K8s.Client.HTTPError struct for all HTTP-related errors in version 2.0.0 and later. ```elixir # Example of handling K8s.Client.HTTPError would go here. ``` -------------------------------- ### Stream Watch Events to Scoped PID Source: https://github.com/coryodaniel/k8s/blob/develop/guides/migrations.md Stream watch events to a specific process and reference for scoped messages using K8s.Client.watch/N and K8s.Client.Runner.Base.stream_to/N. ```elixir ref = make_ref() :ok = K8s.Client.watch("v1", "ConfigMap", namespace: "default") |> K8s.Client.put_conn(conn) |> K8s.Client.Runner.Base.stream_to({self(), ref}) receive do {^ref, event} -> IO.inspect(event) end ``` -------------------------------- ### Wait for Kubernetes Job Completion Source: https://github.com/coryodaniel/k8s/blob/develop/guides/operations.md Block and wait for a specific Kubernetes Job to reach a desired state, such as 'status.succeeded' equaling 1, with a timeout. Requires a valid kubeconfig. ```elixir operation = K8s.Client.get("batch/v1", :job, namespace: "default", name: "database-migrator") wait_opts = [find: ["status", "succeeded"], eval: 1, timeout: 60] {:ok, conn} = K8s.Conn.from_file("path/to/kubeconfig.yaml") {:ok, job} = K8s.Client.wait_until(conn, operation, wait_opts) ``` -------------------------------- ### Attach K8s System Logger Source: https://github.com/coryodaniel/k8s/blob/develop/guides/observability.md Attach the K8s system logger to your application's telemetry handler to capture and log library events with metadata. ```elixir K8s.Sys.Logger.attach() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.