k8s-rails
A Kubernetes API access convention layer for Rails applications.
k8s-rails provides the connection, resource access, and error-handling
convention layer for Rails applications that talk to the Kubernetes API. It
covers every resource kruby can address: core v1 built-ins (Pod, Service,
ConfigMap, ...), named-group built-ins (Deployment, Ingress, ...), and
CRDs.
For the design rationale, see the design document (docs/design.md) (KBR-DESIGN-001).
Requirements
| Item | Supported range | Notes |
|---|---|---|
| Ruby |
>= 3.3, < 4.1 (excluding 4.1.0.preview1) |
Floor: kruby 1.36.x requires Ruby 3.3. Ruby 4.0 support verified on Ruby 4.0.7 (2026-09-22, re-verified with kruby 1.36.5.2 on 2026-10-18); Ruby 3.5 verified on 3.5.0-preview1 (the only released 3.5, re-verified 2026-10-18). CI verifies the declared range with a 3.3.0 / 3.3.8 / 3.4.10 / 3.5.0-preview1 / 4.0.7 matrix. Ruby 4.1.0-preview1 (published 2026-10-17) is excluded from the range with != 4.1.0.preview1: Gem.ruby_version reports the prerelease form 4.1.0.preview1, which < 4.1 alone admits. The preview has no runnable CI shard yet (bundle install fails under it with the upstream RubyGems/Bundler bug uninitialized constant Pathname::SEPARATOR_PAT, Bundler 4.0.23; verified 2026-10-17) — the exclusion lifts and the shard lands once rubygems fixes it or 4.1 goes stable. != excludes exactly one version, so later previews (4.1.0.preview2+) need their own entries until then |
| kruby | ~> 1.36.0 |
The official Kubernetes OpenAPI client |
| Kubernetes server | Verified on v1.33.x (real cluster, microk8s v1.33.13, 2026-09-21) | The transport speaks the generic Kubernetes REST API, so newer servers (1.36, etc.) are expected to work but are not yet verified on a real cluster |
| Dependencies | kruby only at runtime | ActiveSupport is used only for optional instrumentation (no-op when absent) |
Installation
# Gemfile
gem "k8s-rails", "~> 0.4"require "k8s-rails"
K8sRails::VERSION # => "0.4.0"require is side-effect-free and needs no cluster. kruby itself is loaded
lazily on the first K8sRails.client / K8sRails.connected? / CRD operation
(lazy connect), so the gem can be required even when no cluster is
reachable.
Quick start
k8s-rails reaches every resource the Kubernetes API exposes — core v1
built-ins (Pod, Service, ConfigMap, ...), named-group built-ins (Deployment,
Ingress, ...), and CRDs — through one declaration API. The transport speaks
the generic REST API: a core v1 resource is declared with an empty group
(group: "" → /api/v1/...), any other resource with its API group
(/apis/{group}/{version}/...).
1. Configure (once, in an initializer)
# config/initializers/k8s-rails.rb
K8sRails.configure do |config|
config.namespace = "team-a" # default namespace (can be overridden per declaration or per call)
end2. Declare the resource you work with
Coordinates are declared explicitly — group / version / plural / kind are never guessed. A core v1 resource (Pods) uses an empty group:
Pod = K8sRails.crd(
group: "", # core v1 (the "/api/v1" API group)
version: "v1",
plural: "pods",
kind: "Pod",
readonly: false, # default true; only an explicit false enables create/patch/delete
)A named-group built-in (Deployments) is identical except for the group:
Deployment = K8sRails.crd(
group: "apps", # "/apis/apps/v1"
version: "v1",
plural: "deployments",
kind: "Deployment",
readonly: false, # enables create/patch/delete in the example below
)3. Read and write (CRUD)
All return values are string-keyed hashes:
Pod.list # => [{"metadata" => {"name" => "..."}, "spec" => {...}}, ...]
Pod.find("api-7d9f8b6c5-xk2lt") # the full object; raises K8sRails::NotFound when absent
Pod.find_or_nil("missing") # same, but returns nil instead of raising
# readonly: false only
Pod.create({
apiVersion: "v1",
kind: "Pod",
metadata: { name: "busybox" },
spec: { containers: [{ name: "busybox", image: "busybox" }] }
})
Pod.patch("busybox", [{ op: "replace", path: "/spec/containers/0/image", value: "busybox:1.36" }])
Pod.delete("busybox") # => the API's delete response, string-keyed (see "What delete returns" below)
# Deployment (named group) is used exactly the same way
Deployment.list # all Deployments in the default namespace
Deployment.find("web")
Deployment.delete("web") # readonly: false only
K8sRails.connected? # true on success; raises K8sRails::Unavailable / ApiError on failureWhat delete returns
delete / delete_cluster return the API's delete response as-is,
deep-stringified — the gem never rewrites it into a fixed shape. Which shape
you get depends on the resource and its deletion path:
-
A Status object for immediately-deleted resources. A ConfigMap on
Kubernetes 1.36 answers
{"kind" => "Status", "apiVersion" => "v1", "metadata" => {}, "status" => "Success", "details" => {"name" => "...", "kind" => "configmaps", ...}}. -
The object itself for graceful deletion — a Pod under its default grace
period answers the Pod body with
metadata.deletionTimestampset (the Pod API contract defines the DELETE response as the Pod object, 200/202).
Deletion acceptance is not the same as the object being gone:
finalizers or a grace period keep the object around after a successful call.
To confirm the object no longer exists, poll with find_or_nil (returns
nil once it is gone).
Example: Argo Workflows (CRD)
The same declaration and operations work for any CRD — here, the Argo
Workflows Workflow CRD:
Workflow = K8sRails.crd(
group: "argoproj.io",
version: "v1alpha1",
plural: "workflows",
kind: "Workflow",
readonly: false, # default true; false enables create/patch/delete
)
Workflow.list # => [{"metadata" => {"name" => "...", ...}}, ...]
Workflow.find("wf-1") # same shape / raises K8sRails::NotFound when absent
Workflow.find_or_nil("wf-1") # same, but returns nil instead of raising
Workflow.create({ metadata: { name: "wf-1" } }) # readonly: false only
Workflow.patch("wf-1", [{ op: "replace", path: "/spec/a", value: 2 }]) # readonly: false only
Workflow.delete("wf-1") # readonly: false onlyConfiguration
K8sRails.configure do |config|
config.namespace = "team-a" # default namespace (default: "default")
# config.http_timeout = 30 # HTTP timeout in seconds (default: 30; 0 = unlimited)
# config.connection = my_config # pass a Kubernetes::Configuration directly (optional)
# config.instrumentation = false # disable instrumentation (default true; only effective when ActiveSupport is present)
# config.api_client = stub # test-only: inject a transport (see [Testing](#testing))
end-
configureis effective only once — but only when the block returns normally. If the block exits abnormally (any exception, includingLoadError;throw; non-local return), the "configured" flag is reset, so a laterconfigureruns normally. Note that attribute writes made before the abnormal exit remain on the shared configuration (a partially applied state is possible); a re-run block should set every attribute it depends on. A second call on an already-configured gem prints a warning and is ignored (useK8sRails.reset!to reset the configuration, the cached transport, and declared CRDs — primarily for tests). - Connection resolution order:
config.api_client(test injection) →config.connection→Kubernetes::Configuration.default_config(automatic detection in kruby 1.36.x:KUBECONFIG→~/.kube/config→ in-cluster. Note in-cluster is tried last, after the file-based sources — re-verifykruby's loader when upgrading kruby).
HTTP timeouts (default 30s)
kruby's Kubernetes::Configuration defaults timeout to 0, which in
libcurl means no timeout — an unresponsive API server can hold a Rails
request or background job indefinitely. To make that safe by default, the gem
applies a finite timeout at connection resolution:
K8sRails.configure do |config|
config.http_timeout = 30 # seconds (default: 30)
end-
The value applies only when the resolved connection's
timeoutstill carries kruby's unset value (0). If you set one explicitly, the gem never overrides it:require "kubernetes" my_config = Kubernetes::Configuration.default_config my_config.timeout = 60 # explicit value — the gem never overrides it K8sRails.configure do |config| config.connection = my_config end
-
config.http_timeout = 0opts out entirely and restores kruby's unlimited wait. (kruby's owntimeout = 0is indistinguishable from "never set", so the opt-out lives on this knob rather than on the kruby configuration.) -
The same policy covers Resource operations and
K8sRails.connected?— both resolve the connection through the same path. -
A finite timeout turns a hung connection into
K8sRails::Unavailable(kruby surfaces it asApiErrorcode 0 with a "Connection timed out" message; the gem converts it — see Exception hierarchy). -
Set
http_timeoutbefore the firstK8sRails.client/ API call: it is applied once, when the connection is resolved. Changingconfig.connection.timeoutdirectly works at any time (kruby re-reads it for every request). -
http_timeoutaccepts a non-negative Integer ornil(built-in default). Other values raiseArgumentError— aFloatlike0.5would be truncated by libcurl to0(= unlimited), silently recreating the unbounded wait this default exists to prevent.
Retries
The gem does not add its own retry/backoff layer. kruby 1.36.x offers retries
on the resolved connection's retry_configuration hash
({ max_retries: N, base_interval_seconds: F, retry_statuses: [...] };
disabled by default — max_retries 0, and even when enabled only the status
codes 429/500/501/502/503 are retried, with the server's Retry-After taken
into account when present). When enabled, the total wait scales with
max_retries: every retryable response re-runs the full request plus the
exponential backoff between attempts, so one call can take roughly
(1 + max_retries) × timeout plus the intervals. Timed-out requests are
not retried. For broader failure handling, rely on Rails middleware /
background-job retries.
Resource declaration and access
The same K8sRails.crd API covers core v1 built-ins, named-group built-ins,
and CRDs. plural / kind are never guessed (many resources do not
follow the obvious naming convention). Re-declaring the same kind raises
K8sRails::RedeclarationError (configuration-mistake detection).
-
core v1 resources (Pod, Service, ConfigMap, ...):
group: "" -
named-group resources (Deployment =
apps, Ingress =networking.k8s.io, any CRD group): the resource's API group -
cluster-scoped resources (Node, ClusterIssuer, ...):
scope: :clusterand nonamespace:(see Cluster-scoped resources)
Return values are always string-keyed hashes. kruby returns symbol keys,
but Rails-side JSON/views work with string keys, so the gem normalizes
internally in pure Ruby (no ActiveSupport dependency). Every namespaced
method accepts a namespace: argument to override the namespace from the
declaration (the *_cluster methods take no namespace:).
readonly must be an explicit boolean (nil or other values raise
ArgumentError). Writes (create / patch / delete) are enabled only
by readonly: false, so a missing flag can never fail open.
Object-name arguments of find / find_or_nil / patch / delete (and
their *_cluster counterparts) are validated before any request is
issued: nil, an empty string, "." or ".." raise ArgumentError.
This keeps delete(nil) from degrading into a Delete Collection call
against the whole collection, and keeps "." / ".." from being normalized
away by the HTTP client into a different resource path.
Cluster-scoped resources
Both namespaced and cluster-scoped resources are supported. Declare a
cluster-scoped resource (Node, ClusterIssuer, ClusterWorkflowTemplate, ...)
with scope: :cluster and without namespace: (combining the two raises
ArgumentError):
ClusterIssuer = K8sRails.crd(
group: "cert-manager.io",
version: "v1",
plural: "clusterissuers",
kind: "ClusterIssuer",
scope: :cluster, # cluster-scoped endpoints (no namespace)
)
ClusterIssuer.list_cluster # all objects cluster-wide
ClusterIssuer.find_cluster("letsencrypt")
ClusterIssuer.find_or_nil_cluster("x")
ClusterIssuer.create_cluster({ ... }) # readonly: false only
ClusterIssuer.patch_cluster("letsencrypt", [{ ... }]) # readonly: false only
ClusterIssuer.delete_cluster("letsencrypt") # readonly: false onlyCore v1 has cluster-scoped resources too (Node, Namespace):
Node = K8sRails.crd(group: "", version: "v1", plural: "nodes", kind: "Node", scope: :cluster)
Node.list_cluster # all nodes
Node.find_cluster("n1")On a scope: :namespaced declaration (the default) the *_cluster methods
raise ArgumentError — the resource is namespaced, so the cluster endpoints
would 404 anyway. For a cluster-scoped declaration, use the *_cluster
methods (the plain list/find/... would call the namespaced endpoints and
404, so they raise ArgumentError there as well).
Connectivity check
K8sRails.connected? # true on success; raises K8sRails::Unavailable / ApiError on failure
# a lightweight /version-equivalent checkIt never returns false — a connection failure surfaces as an exception
(handle it with rescue). The actual API connection is established lazily on
the first API call.
The probe inspects the same cached connection the Resource operations
use — the resolved configuration is memoized for the lifetime of the cached
transport, so a config resolution that changes after the first call is not
re-resolved for the probe (it would otherwise validate connection B while
operations still use connection A). The first resolution, the K1 bridge, and
the transport build run inside one internal lock, so a concurrent Resource
operation and connected? call resolve the configuration exactly once (the
probe's HTTP I/O stays outside the lock). K8sRails.reset! is the explicit reload
path: after it, both the probe and the next API call resolve the
configuration anew.
When a test transport is injected via config.api_client, connected?
returns true without any network I/O — the injected transport is the
connection surface, so probing a real endpoint would contradict the Resource
operations that the same injection serves.
Exception hierarchy
K8sRails::Error < StandardError
├── K8sRails::Unavailable # connection-level failure: transport (DNS/timeout/connection refused — kruby 1.36.x reports these as ApiError code 0) and kubeconfig load failures (original Kubernetes::ConfigError kept as #cause)
├── K8sRails::NotFound # HTTP 404
├── K8sRails::ApiError # other API errors (401/403/409/422/5xx); holds #code and #response
├── K8sRails::ReadOnlyError # create/patch/delete called on a readonly: true declaration
└── K8sRails::RedeclarationError # re-declaration of an already-declared kind
Recommended caller pattern:
begin
Workflow.list
rescue K8sRails::Unavailable
# cluster-side problem → "unable to load" fallback UI, etc.
rescue K8sRails::ApiError => e
# inspect e.code / e.response to determine the cause
endInstrumentation (optional ActiveSupport)
When config.instrumentation = true (the default) and ActiveSupport is loaded,
each API call is published as a k8s-rails.request notification (no-op when
ActiveSupport is absent):
k8s-rails.request
payload: { operation:, group:, version:, plural:, namespace:, duration_ms:,
status: "ok" | "unavailable" | "api_error" }
The API call runs inside the standard notification block, so the event's
start/finish times bracket the real processing (Event#duration reports the
actual call duration) and a failure attaches the standard
exception / exception_object metadata next to the custom status. The
finish event payload always carries status and duration_ms.
In a Rails app you can subscribe with ActiveSupport::Notifications:
ActiveSupport::Notifications.subscribe("k8s-rails.request") do |name, start, finish, id, payload|
Rails.logger.info("[k8s-rails] #{payload[:operation]} #{payload[:plural]} (#{payload[:duration_ms]}ms) #{payload[:status]}")
endTesting
The test suite needs no cluster. Tests inject a transport stub via
config.api_client. The transport speaks kruby's Kubernetes::ApiClient#call_api
protocol, so a stub just implements that one method — call_api(http_method, path, opts) returning [data, status_code, headers]. http_method is one of
:GET / :POST / :PATCH / :DELETE, and path is the fully-built API
path (the gem builds it from the declaration — core v1 as /api/v1/...,
everything else as /apis/{group}/{version}/...):
class StubTransport
def call_api(method, path, opts = {})
case method
when :GET then { items: [] }, 200, {} # ... or a single object
when :POST then { metadata: {} }, 200, {}
when :PATCH then { metadata: {} }, 200, {}
when :DELETE then { kind: "Status", status: "Success" }, 200, {}
end
end
end
K8sRails.configure { |c| c.api_client = StubTransport.new }A realistic stub routes on path (and opts[:body] for writes). Responses
may use symbol keys — the gem stringifies them.
With a transport injected, K8sRails.connected? returns true without
network I/O (see Connectivity check).
Development
bundle install
bundle exec rake # rspec + rubocop
Known issue: kruby 1.36 bearer-token key mismatch
kruby 1.36.x's in-cluster / KUBECONFIG configuration writes the bearer token
to api_key['authorization'], but Configuration#auth_settings reads
api_key['BearerToken'] for the Authorization header. Because the keys do
not match, the Authorization header ends up empty and requests fail with
401 when using kruby's configuration directly.
k8s-rails automatically copies authorization to BearerToken when building
its client (the design document calls this the "K1 bridge"). The copy is not
frozen: the bridge re-syncs BearerToken from authorization on every
request (kruby calls auth_settings per request, which is exactly where
kruby's in-cluster token-refresh hook runs), so a rotated ServiceAccount
token reaches long-running processes without rebuilding the client. The
token sent by a request is taken from the value refreshed on that same call
and is never re-read from the shared configuration afterwards, so concurrent
requests in a threaded process cannot send a stale copy. A BearerToken set
by your application is never bridged or overwritten — before client creation
the bridge is simply not installed, and if your app replaces the value after
the client exists (explicit credential rotation), the bridge detects the
override, stops syncing, and your value stays authoritative. If you see 401s
from a cluster connection that relies on kruby's own configuration behavior
(outside this gem), check this token-key issue first.
Roadmap (v0.5+)
- Update the CI matrix when Ruby 3.5 reaches a stable release (3.5 is verified today on 3.5.0-preview1, the only released 3.5)
- When Ruby 4.1 goes stable, drop the
!= 4.1.0.preview1gemspec exclusion, extend the declared range to< 4.2, and add 4.1 to the matrix after verification (the preview is excluded until the upstream BundlerPathname::SEPARATOR_PATbug is fixed) - CI-based E2E tests using kind
- watch (streaming) support, under consideration
License
MIT (LICENSE)