blib/lib/Kubernetes/REST/Example.pm untested

filter: Statementstmt 0.0% 0 / 2 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 0.0% 0 / 2 SCAR -
1 package Kubernetes::REST::Example;
2 # ABSTRACT: Working examples for Kubernetes::REST with Minikube, K3s, and other clusters
3 our $VERSION = '1.108';
4 1;
5  
6 __END__
7  
8 =pod
9  
10 =encoding UTF-8
11  
12 =head1 NAME
13  
14 Kubernetes::REST::Example - Working examples for Kubernetes::REST with Minikube, K3s, and other clusters
15  
16 =head1 VERSION
17  
18 version 1.108
19  
20 =head1 DESCRIPTION
21  
22 This document walks you through setting up L<Kubernetes::REST> with a local
23 Kubernetes cluster and shows how to manage real resources from Perl using
24 L<IO::K8s> typed objects.
25  
26 Every code snippet is ready to copy-paste into a script once you have a
27 running cluster and the Perl dependencies installed. A comprehensive
28 runnable demo script is included in C<eg/demo.pl>.
29  
30 =head1 NAME
31  
32 Kubernetes::REST::Example - Working examples for Kubernetes::REST with Minikube, K3s, and other clusters
33  
34 =head1 CLUSTER SETUP
35  
36 L<Kubernetes::REST> works with any Kubernetes cluster. Below are setup
37 instructions for common local development environments. All of them write
38 a kubeconfig to C<~/.kube/config> that L<Kubernetes::REST::Kubeconfig> picks
39 up automatically.
40  
41 =head2 Minikube
42  
43 L<Minikube|https://minikube.sigs.k8s.io/> creates a single-node cluster
44 inside a Docker container or VM.
45  
46 # Install (Debian/Ubuntu)
47 curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
48 sudo install minikube-linux-amd64 /usr/local/bin/minikube
49  
50 # Start with Docker driver
51 minikube start --driver=docker
52  
53 # Verify
54 minikube status
55  
56 Minikube uses self-signed certificates and token authentication. The
57 kubeconfig context is named C<minikube>.
58  
59 B<NodePort access:>
60  
61 minikube service <service-name> -n <namespace>
62  
63 =head2 K3s
64  
65 L<K3s|https://k3s.io/> is a lightweight Kubernetes distribution from Rancher.
66 It installs as a single binary and runs directly on the host (no Docker
67 required).
68  
69 # Install
70 curl -sfL https://get.k3s.io | sh -
71  
72 # K3s writes its own kubeconfig to a different path
73 export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
74  
75 # Or copy it so Kubernetes::REST::Kubeconfig finds it automatically
76 mkdir -p ~/.kube
77 sudo cp /etc/rancher/k3s/k3s.yaml ~/.kube/config
78 sudo chown $USER ~/.kube/config
79 chmod 600 ~/.kube/config
80  
81 # Verify
82 kubectl get nodes
83  
84 B<Key differences from Minikube:>
85  
86 =over 4
87  
88 =item * Kubeconfig lives at C</etc/rancher/k3s/k3s.yaml> (not C<~/.kube/config>)
89  
90 =item * The server endpoint is C<https://127.0.0.1:6443>
91  
92 =item * K3s includes Traefik as its default ingress controller
93  
94 =item * K3s uses C<containerd> instead of Docker
95  
96 =item * NodePort services are accessible directly on the host IP
97  
98 =back
99  
100 B<Connecting from Perl with K3s:>
101  
102 use Kubernetes::REST::Kubeconfig;
103  
104 # If you copied the kubeconfig to ~/.kube/config:
105 my $api = Kubernetes::REST::Kubeconfig->new->api;
106  
107 # If using the K3s path directly:
108 my $api = Kubernetes::REST::Kubeconfig->new(
109 kubeconfig_path => '/etc/rancher/k3s/k3s.yaml',
110 )->api;
111  
112 =head2 Kind (Kubernetes in Docker)
113  
114 L<Kind|https://kind.sigs.k8s.io/> runs Kubernetes nodes as Docker containers.
115 Good for CI and testing.
116  
117 # Install
118 go install sigs.k8s.io/kind@latest
119  
120 # Create cluster
121 kind create cluster --name perl-test
122  
123 # Context is named: kind-perl-test
124 my $api = Kubernetes::REST::Kubeconfig->new(
125 context_name => 'kind-perl-test',
126 )->api;
127  
128 =head2 Any cluster with a kubeconfig
129  
130 If you have a kubeconfig (EKS, GKE, AKS, self-managed, etc.):
131  
132 use Kubernetes::REST::Kubeconfig;
133  
134 # Uses current context from ~/.kube/config
135 my $api = Kubernetes::REST::Kubeconfig->new->api;
136  
137 # Or specify a context
138 my $api = Kubernetes::REST::Kubeconfig->new(
139 context_name => 'my-production-cluster',
140 )->api;
141  
142 =head1 INSTALL PERL DEPENDENCIES
143  
144 cpanm Kubernetes::REST
145  
146 =head1 CONNECTING TO THE CLUSTER
147  
148 =head2 Using the kubeconfig (recommended)
149  
150 L<Kubernetes::REST::Kubeconfig> parses your kubeconfig and sets up
151 authentication, SSL certificates, and the server endpoint automatically:
152  
153 use Kubernetes::REST::Kubeconfig;
154  
155 my $kc = Kubernetes::REST::Kubeconfig->new;
156 my $api = $kc->api;
157  
158 say "Cluster version: " . $api->cluster_version;
159  
160 If you have multiple contexts:
161  
162 my $contexts = $kc->contexts;
163 say "Available: @$contexts";
164  
165 my $api = $kc->api('minikube'); # or 'default', 'kind-test', etc.
166  
167 =head2 Manual configuration
168  
169 use Kubernetes::REST;
170  
171 my $api = Kubernetes::REST->new(
172 server => {
173 endpoint => 'https://127.0.0.1:6443',
174 ssl_verify_server => 0,
175 },
176 credentials => { token => $token },
177 resource_map_from_cluster => 0,
178 );
179  
180 =head1 LISTING RESOURCES
181  
182 =head2 Namespaces
183  
184 my $list = $api->list('Namespace');
185  
186 for my $ns (@{ $list->items }) {
187 printf "%-20s %s\n",
188 $ns->metadata->name,
189 $ns->status->phase // 'Unknown';
190 }
191  
192 =head2 Pods in a namespace
193  
194 my $pods = $api->list('Pod', namespace => 'kube-system');
195  
196 for my $pod (@{ $pods->items }) {
197 my $name = $pod->metadata->name;
198 my $phase = $pod->status->phase // 'Unknown';
199 my $ip = $pod->status->podIP // 'pending';
200 printf "%-45s %-10s %s\n", $name, $phase, $ip;
201 }
202  
203 =head2 Services
204  
205 my $services = $api->list('Service', namespace => 'default');
206  
207 for my $svc (@{ $services->items }) {
208 my $name = $svc->metadata->name;
209 my $type = $svc->spec->type // 'ClusterIP';
210 my $ports = join ', ', map {
211 $_->port . '/' . ($_->protocol // 'TCP')
212 } @{ $svc->spec->ports // [] };
213 printf "%-20s %-12s %s\n", $name, $type, $ports;
214 }
215  
216 =head2 Nodes
217  
218 my $nodes = $api->list('Node');
219  
220 for my $node (@{ $nodes->items }) {
221 my $info = $node->status->nodeInfo;
222 printf "%-20s OS=%-8s kubelet=%s\n",
223 $node->metadata->name,
224 $info->operatingSystem // '?',
225 $info->kubeletVersion // '?';
226 }
227  
228 =head1 GETTING A SINGLE RESOURCE
229  
230 C<get()> returns a fully typed L<IO::K8s> object:
231  
232 my $pod = $api->get('Pod', 'my-pod', namespace => 'default');
233  
234 say "Name: " . $pod->metadata->name;
235 say "Namespace: " . $pod->metadata->namespace;
236 say "Kind: " . $pod->kind; # "Pod"
237 say "API: " . $pod->api_version; # "v1"
238 say "Phase: " . $pod->status->phase;
239 say "Node: " . ($pod->spec->nodeName // 'unscheduled');
240  
241 # Access labels (hashref)
242 my $labels = $pod->metadata->labels // {};
243 for my $key (sort keys %$labels) {
244 say " $key = $labels->{$key}";
245 }
246  
247 =head1 CREATING RESOURCES
248  
249 =head2 Namespace
250  
251 my $ns = $api->new_object(Namespace =>
252 metadata => { name => 'perl-test' },
253 );
254  
255 my $created = $api->create($ns);
256 say "Created: " . $created->metadata->name;
257  
258 =head2 ConfigMap
259  
260 my $cm = $api->create($api->new_object(ConfigMap =>
261 metadata => {
262 name => 'app-config',
263 namespace => 'perl-test',
264 },
265 data => {
266 'database.host' => 'postgres.perl-test.svc.cluster.local',
267 'database.port' => '5432',
268 'app.debug' => 'true',
269 },
270 ));
271  
272 =head2 Secret
273  
274 use MIME::Base64 qw(encode_base64);
275  
276 my $secret = $api->create($api->new_object(Secret =>
277 metadata => {
278 name => 'db-credentials',
279 namespace => 'perl-test',
280 },
281 type => 'Opaque',
282 data => {
283 username => encode_base64('admin', ''),
284 password => encode_base64('s3cret', ''),
285 },
286 ));
287  
288 =head2 LimitRange
289  
290 Set default resource limits for all containers in a namespace:
291  
292 my $lr = $api->create($api->new_object(LimitRange =>
293 metadata => {
294 name => 'default-limits',
295 namespace => 'perl-test',
296 },
297 spec => {
298 limits => [{
299 type => 'Container',
300 default => { cpu => '200m', memory => '128Mi' },
301 defaultRequest => { cpu => '50m', memory => '64Mi' },
302 }],
303 },
304 ));
305  
306 =head2 Deployment with volumes, probes, and ServiceAccount
307  
308 my $deploy = $api->create($api->new_object(Deployment =>
309 metadata => {
310 name => 'my-app',
311 namespace => 'perl-test',
312 },
313 spec => {
314 replicas => 2,
315 selector => {
316 matchLabels => { app => 'my-app' },
317 },
318 template => {
319 metadata => {
320 labels => { app => 'my-app' },
321 annotations => { 'managed-by' => 'perl' },
322 },
323 spec => {
324 serviceAccountName => 'default',
325 containers => [{
326 name => 'nginx',
327 image => 'nginx:1.27-alpine',
328 ports => [{ containerPort => 80, name => 'http' }],
329 env => [{
330 name => 'APP_ENV',
331 valueFrom => {
332 configMapKeyRef => {
333 name => 'app-config',
334 key => 'app.debug',
335 },
336 },
337 }, {
338 name => 'DB_USER',
339 valueFrom => {
340 secretKeyRef => {
341 name => 'db-credentials',
342 key => 'username',
343 },
344 },
345 }],
346 volumeMounts => [{
347 name => 'config-volume',
348 mountPath => '/etc/nginx/conf.d',
349 }, {
350 name => 'data-volume',
351 mountPath => '/data',
352 }],
353 resources => {
354 requests => { cpu => '50m', memory => '32Mi' },
355 limits => { cpu => '100m', memory => '64Mi' },
356 },
357 livenessProbe => {
358 httpGet => { path => '/', port => 80 },
359 initialDelaySeconds => 5,
360 periodSeconds => 10,
361 },
362 readinessProbe => {
363 httpGet => { path => '/', port => 80 },
364 initialDelaySeconds => 3,
365 periodSeconds => 5,
366 },
367 }],
368 volumes => [{
369 name => 'config-volume',
370 configMap => {
371 name => 'app-config',
372 items => [{
373 key => 'nginx.conf',
374 path => 'default.conf',
375 }],
376 },
377 }, {
378 name => 'data-volume',
379 persistentVolumeClaim => {
380 claimName => 'my-storage',
381 },
382 }],
383 },
384 },
385 },
386 ));
387  
388 =head2 Service (NodePort)
389  
390 my $svc = $api->create($api->new_object(Service =>
391 metadata => {
392 name => 'my-app',
393 namespace => 'perl-test',
394 },
395 spec => {
396 type => 'NodePort',
397 selector => { app => 'my-app' },
398 ports => [{
399 port => 80,
400 targetPort => 80,
401 protocol => 'TCP',
402 }],
403 },
404 ));
405  
406 my $node_port = $svc->spec->ports->[0]->nodePort;
407 say "NodePort: $node_port";
408  
409 # Minikube: minikube service my-app -n perl-test
410 # K3s: curl http://localhost:$node_port
411  
412 =head2 Job
413  
414 my $job = $api->create($api->new_object(Job =>
415 metadata => {
416 name => 'batch-job',
417 namespace => 'perl-test',
418 },
419 spec => {
420 backoffLimit => 2,
421 template => {
422 spec => {
423 restartPolicy => 'Never',
424 containers => [{
425 name => 'worker',
426 image => 'busybox:latest',
427 command => ['sh', '-c', 'echo "done"; exit 0'],
428 }],
429 },
430 },
431 },
432 ));
433  
434 =head2 CronJob
435  
436 my $cron = $api->create($api->new_object(CronJob =>
437 metadata => {
438 name => 'scheduled-job',
439 namespace => 'perl-test',
440 },
441 spec => {
442 schedule => '*/5 * * * *',
443 jobTemplate => {
444 spec => {
445 template => {
446 spec => {
447 restartPolicy => 'OnFailure',
448 containers => [{
449 name => 'worker',
450 image => 'busybox:latest',
451 command => ['sh', '-c', 'date'],
452 }],
453 },
454 },
455 },
456 },
457 },
458 ));
459  
460 =head2 RBAC (Role + RoleBinding)
461  
462 my $role = $api->create($api->new_object(Role =>
463 metadata => {
464 name => 'pod-reader',
465 namespace => 'perl-test',
466 },
467 rules => [{
468 apiGroups => [''],
469 resources => ['pods'],
470 verbs => ['get', 'list', 'watch'],
471 }],
472 ));
473  
474 my $binding = $api->create($api->new_object(RoleBinding =>
475 metadata => {
476 name => 'read-pods',
477 namespace => 'perl-test',
478 },
479 roleRef => {
480 apiGroup => 'rbac.authorization.k8s.io',
481 kind => 'Role',
482 name => 'pod-reader',
483 },
484 subjects => [{
485 kind => 'ServiceAccount',
486 name => 'default',
487 namespace => 'perl-test',
488 }],
489 ));
490  
491 =head2 PersistentVolumeClaim
492  
493 Works out of the box on Minikube (hostpath provisioner) and K3s (local-path
494 provisioner).
495  
496 my $pvc = $api->create($api->new_object(PersistentVolumeClaim =>
497 metadata => {
498 name => 'my-storage',
499 namespace => 'perl-test',
500 },
501 spec => {
502 accessModes => ['ReadWriteOnce'],
503 resources => {
504 requests => { storage => '100Mi' },
505 },
506 },
507 ));
508  
509 =head2 ResourceQuota
510  
511 my $quota = $api->create($api->new_object(ResourceQuota =>
512 metadata => {
513 name => 'ns-quota',
514 namespace => 'perl-test',
515 },
516 spec => {
517 hard => {
518 pods => '20',
519 'requests.cpu' => '2',
520 'requests.memory' => '1Gi',
521 },
522 },
523 ));
524  
525 =head1 UPDATING RESOURCES
526  
527 Fetch a resource, modify it, send it back:
528  
529 # Scale the deployment
530 my $deploy = $api->get('Deployment', 'my-app',
531 namespace => 'perl-test',
532 );
533 $deploy->spec->replicas(3);
534 my $updated = $api->update($deploy);
535 say "Scaled to " . $updated->spec->replicas . " replicas";
536  
537 # Rolling update (change image)
538 $deploy = $api->get('Deployment', 'my-app', namespace => 'perl-test');
539 $deploy->spec->template->spec->containers->[0]->image('nginx:1.27-bookworm');
540 my $ann = $deploy->spec->template->metadata->annotations // {};
541 $ann->{'kubernetes.io/change-cause'} = 'Image update via Perl';
542 $deploy->spec->template->metadata->annotations($ann);
543 $api->update($deploy);
544  
545 # Add a label
546 my $pod = $api->get('Pod', 'my-pod', namespace => 'perl-test');
547 my $labels = $pod->metadata->labels // {};
548 $labels->{environment} = 'testing';
549 $pod->metadata->labels($labels);
550 $api->update($pod);
551  
552 =head1 PATCHING RESOURCES
553  
554 C<patch()> modifies specific fields without fetching and replacing the
555 entire object. This avoids conflicts when multiple clients update the
556 same resource.
557  
558 =head2 Strategic Merge Patch (default)
559  
560 The Kubernetes-native patch type. Arrays are merged intelligently
561 based on the field's merge strategy.
562  
563 # Add a label without touching other labels
564 my $patched = $api->patch('Pod', 'my-pod',
565 namespace => 'perl-test',
566 patch => {
567 metadata => { labels => { environment => 'staging' } },
568 },
569 );
570  
571 # Scale a deployment (one field only)
572 $api->patch('Deployment', 'my-app',
573 namespace => 'perl-test',
574 patch => { spec => { replicas => 5 } },
575 );
576  
577 =head2 JSON Merge Patch
578  
579 Simple merge where C<null> deletes a key. Arrays are replaced entirely.
580  
581 # Remove an annotation
582 use JSON::PP ();
583 $api->patch('Pod', 'my-pod',
584 namespace => 'perl-test',
585 type => 'merge',
586 patch => {
587 metadata => { annotations => { 'old-key' => JSON::PP::null } },
588 },
589 );
590  
591 =head2 JSON Patch (RFC 6902)
592  
593 An array of precise operations for surgical edits.
594  
595 $api->patch('Deployment', 'my-app',
596 namespace => 'perl-test',
597 type => 'json',
598 patch => [
599 { op => 'replace', path => '/spec/replicas', value => 3 },
600 { op => 'add', path => '/metadata/labels/version', value => '2.0' },
601 ],
602 );
603  
604 =head2 Patch vs Update
605  
606 Use C<patch()> when you only need to change a few fields - it's safer
607 because it won't overwrite changes made by other clients between your
608 C<get()> and C<update()>. Use C<update()> when you need to replace the
609 entire spec.
610  
611 Neither one ever changes a resource's C<status> once that kind has a status
612 subresource - and most kinds with a meaningful C<status> field do, built-in
613 or custom. Writing status needs C<patch_status()>/C<update_status()> instead;
614 see L</The status Subresource> for why, and for the CRD case specifically.
615  
616 =head1 WAITING FOR READINESS
617  
618 Kubernetes operations are asynchronous. Poll the API to wait for a
619 desired state:
620  
621 # Wait for a deployment's pods to be ready
622 for my $i (1..60) {
623 my $d = $api->get('Deployment', 'my-app', namespace => 'perl-test');
624 my $ready = $d->status->readyReplicas // 0;
625 my $desired = $d->spec->replicas // 1;
626 if ($ready == $desired) {
627 say "All $ready replicas ready!";
628 last;
629 }
630 sleep 1;
631 }
632  
633 # Wait for a job to complete
634 for my $i (1..60) {
635 my $j = $api->get('Job', 'batch-job', namespace => 'perl-test');
636 if (($j->status->succeeded // 0) >= 1) {
637 say "Job completed at " . $j->status->completionTime;
638 last;
639 }
640 sleep 1;
641 }
642  
643 # Wait for a pod to reach Running phase
644 for my $i (1..30) {
645 my $p = $api->get('Pod', 'my-pod', namespace => 'perl-test');
646 my $phase = $p->status->phase // 'Unknown';
647 if ($phase eq 'Running') {
648 say "Pod running on " . $p->spec->nodeName;
649 last;
650 }
651 sleep 2;
652 }
653  
654 =head1 INSPECTING POD STATUS
655  
656 my $pod = $api->get('Pod', 'my-pod', namespace => 'perl-test');
657  
658 say "Phase: " . ($pod->status->phase // 'Unknown');
659 say "IP: " . ($pod->status->podIP // 'pending');
660 say "Node: " . ($pod->spec->nodeName // 'unscheduled');
661  
662 # Container-level status
663 for my $cs (@{ $pod->status->containerStatuses // [] }) {
664 say "Container: " . $cs->name;
665 say " Ready: " . ($cs->ready ? 'yes' : 'no');
666 say " Restarts: " . ($cs->restartCount // 0);
667 say " Image: " . $cs->image;
668 }
669  
670 =head1 ERROR HANDLING
671  
672 C<create()> croaks if the resource already exists. Use C<eval> to handle
673 this gracefully:
674  
675 my $ns = eval {
676 $api->create($api->new_object(Namespace =>
677 metadata => { name => 'perl-test' },
678 ));
679 };
680 if ($@) {
681 say "Already exists, fetching instead";
682 $ns = $api->get('Namespace', 'perl-test');
683 }
684  
685 =head1 SERIALIZATION
686  
687 Every L<IO::K8s> object can be serialized to JSON or YAML:
688  
689 my $pod = $api->get('Pod', 'my-pod', namespace => 'perl-test');
690  
691 # To JSON
692 my $json = JSON::MaybeXS->new(
693 canonical => 1, pretty => 1, utf8 => 1,
694 )->encode($pod->TO_JSON);
695  
696 # To YAML (suitable for kubectl apply -f)
697 say $pod->to_yaml;
698  
699 # Save to file
700 $pod->save('/tmp/my-pod.yaml');
701  
702 # Round-trip: hashref -> object
703 my $pod2 = $api->inflate($pod->TO_JSON);
704 say $pod2->metadata->name;
705  
706 =head1 WATCHING FOR CHANGES
707  
708 The Watch API streams events as resources are added, modified, or deleted.
709 This is the foundation for building Kubernetes controllers.
710  
711 =head2 Basic watch
712  
713 $api->watch('Pod',
714 namespace => 'default',
715 timeout => 60,
716 on_event => sub {
717 my ($event) = @_;
718 printf "%-10s %s\n",
719 $event->type,
720 $event->object->metadata->name;
721 },
722 );
723  
724 =head2 Resumable watch loop
725  
726 # Watch indefinitely, surviving timeouts and disconnects
727 my $rv;
728 while (1) {
729 $rv = eval {
730 $api->watch('Pod',
731 namespace => 'default',
732 resourceVersion => $rv,
733 on_event => sub {
734 my ($event) = @_;
735 say $event->type . ": " . $event->object->metadata->name;
736 },
737 );
738 };
739 if ($@ && $@ =~ /410 Gone/) {
740 # resourceVersion too old, re-list to get fresh state
741 warn "Watch expired, re-listing...\n";
742 $api->list('Pod', namespace => 'default');
743 $rv = undef;
744 } elsif ($@) {
745 warn "Watch error: $@\n";
746 sleep 5;
747 }
748 # Normal timeout, just restart the watch
749 }
750  
751 =head2 Watch with selectors
752  
753 $api->watch('Pod',
754 namespace => 'default',
755 labelSelector => 'app=web',
756 fieldSelector => 'status.phase=Running',
757 on_event => sub {
758 my ($event) = @_;
759 say $event->type . ": " . $event->object->metadata->name;
760 },
761 );
762  
763 =head2 Watch any resource type
764  
765 # Watch deployments
766 $api->watch('Deployment',
767 namespace => 'default',
768 on_event => sub {
769 my ($event) = @_;
770 my $deploy = $event->object;
771 printf "%s %s: %d/%d ready\n",
772 $event->type,
773 $deploy->metadata->name,
774 $deploy->status->readyReplicas // 0,
775 $deploy->spec->replicas // 0;
776 },
777 );
778  
779 # Watch namespaces (cluster-scoped)
780 $api->watch('Namespace',
781 on_event => sub {
782 my ($event) = @_;
783 say $event->type . ": " . $event->object->metadata->name;
784 },
785 );
786  
787 =head1 DELETING RESOURCES
788  
789 # Delete by object
790 $api->delete($pod);
791  
792 # Delete by name
793 $api->delete('Pod', 'my-pod', namespace => 'perl-test');
794 $api->delete('Deployment', 'my-app', namespace => 'perl-test');
795 $api->delete('Namespace', 'perl-test');
796  
797 When cleaning up a full namespace, delete dependent resources first to
798 avoid errors (e.g. delete the RoleBinding before the Role it references):
799  
800 for my $r (
801 ['CronJob', 'scheduled-job'],
802 ['Job', 'batch-job'],
803 ['Service', 'my-app'],
804 ['Deployment', 'my-app'],
805 ['RoleBinding', 'read-pods'],
806 ['Role', 'pod-reader'],
807 ['PersistentVolumeClaim','my-storage'],
808 ['Secret', 'db-credentials'],
809 ['ConfigMap', 'app-config'],
810 ['ResourceQuota', 'ns-quota'],
811 ['LimitRange', 'default-limits'],
812 ) {
813 my ($kind, $name) = @$r;
814 eval { $api->delete($kind, $name, namespace => 'perl-test') };
815 }
816 eval { $api->delete('Namespace', 'perl-test') };
817  
818 =head1 RESOURCE QUOTA INSPECTION
819  
820 my $q = $api->get('ResourceQuota', 'ns-quota',
821 namespace => 'perl-test',
822 );
823 my $used = $q->status->used // {};
824 my $hard = $q->status->hard // {};
825 for my $key (sort keys %$hard) {
826 printf "%-25s %s / %s\n", $key,
827 $used->{$key} // '0', $hard->{$key};
828 }
829  
830 =head1 CUSTOM RESOURCE DEFINITIONS (CRDs)
831  
832 L<Kubernetes::REST> can manage Custom Resources the same way it manages
833 built-in ones. You define a Perl class for your CRD, register it in
834 the resource map, and use the standard CRUD API.
835  
836 =head2 Defining the CRD in Kubernetes
837  
838 First, apply a CRD to your cluster. Example - a C<StaticWebSite> resource
839 for hosting static websites in your homelab:
840  
841 # staticwebsite-crd.yaml
842 apiVersion: apiextensions.k8s.io/v1
843 kind: CustomResourceDefinition
844 metadata:
845 name: staticwebsites.homelab.example.com
846 spec:
847 group: homelab.example.com
848 versions:
849 - name: v1
850 served: true
851 storage: true
852 schema:
853 openAPIV3Schema:
854 type: object
855 properties:
856 spec:
857 type: object
858 required: [domain, image]
859 properties:
860 domain: { type: string }
861 image: { type: string }
862 replicas: { type: integer, default: 1 }
863 tls: { type: boolean, default: false }
864 status:
865 type: object
866 properties:
867 readyReplicas: { type: integer }
868 url: { type: string }
869 subresources:
870 status: {}
871 scope: Namespaced
872 names:
873 plural: staticwebsites
874 singular: staticwebsite
875 kind: StaticWebSite
876 shortNames: [sw]
877  
878 $ kubectl apply -f staticwebsite-crd.yaml
879  
880 =head2 Writing a CRD class
881  
882 Create a Perl class using C<IO::K8s::APIObject> with import parameters
883 for C<api_version> and C<resource_plural>:
884  
885 package My::StaticWebSite;
886 use IO::K8s::APIObject
887 api_version => 'homelab.example.com/v1',
888 resource_plural => 'staticwebsites';
889 with 'IO::K8s::Role::Namespaced';
890  
891 k8s spec => { Str => 1 };
892 k8s status => { Str => 1 };
893 1;
894  
895 Key points:
896  
897 =over 4
898  
899 =item * C<api_version> - the CRD's C<group/version> (e.g. C<homelab.example.com/v1>)
900  
901 =item * C<resource_plural> - must match the CRD's C<spec.names.plural>
902  
903 =item * C<kind> is derived automatically from the class name (last C<::> segment)
904  
905 =item * Apply C<IO::K8s::Role::Namespaced> for namespace-scoped CRDs
906  
907 =item * C<spec> and C<status> are opaque hashrefs (C<< { Str => 1 } >>)
908  
909 =back
910  
911 =head2 Registering the CRD class
912  
913 Register your class with the C<+> prefix in the resource map:
914  
915 my $api = Kubernetes::REST::Kubeconfig->new->api;
916 $api->resource_map->{StaticWebSite} = '+My::StaticWebSite';
917  
918 Or pass it at construction time:
919  
920 my $api = Kubernetes::REST->new(
921 server => { endpoint => '...' },
922 credentials => { token => '...' },
923 resource_map => {
924 %{ IO::K8s->default_resource_map },
925 StaticWebSite => '+My::StaticWebSite',
926 },
927 );
928  
929 =head2 CRUD on Custom Resources
930  
931 Once registered, CRDs work exactly like built-in resources:
932  
933 use JSON::PP ();
934  
935 # Create
936 my $site = $api->create($api->new_object(StaticWebSite =>
937 metadata => {
938 name => 'my-blog',
939 namespace => 'default',
940 },
941 spec => {
942 domain => 'blog.example.com',
943 image => 'nginx:1.27-alpine',
944 replicas => 2,
945 tls => JSON::PP::true,
946 },
947 ));
948  
949 # Get
950 my $site = $api->get('StaticWebSite', 'my-blog', namespace => 'default');
951 say $site->spec->{domain}; # blog.example.com
952  
953 # List
954 my $list = $api->list('StaticWebSite', namespace => 'default');
955 for my $s (@{ $list->items }) {
956 say $s->metadata->name . ": " . $s->spec->{domain};
957 }
958  
959 # Update
960 $site->spec->{replicas} = 3;
961 $api->update($site);
962  
963 # Delete
964 $api->delete('StaticWebSite', 'my-blog', namespace => 'default');
965  
966 B<Note:> For boolean CRD fields, use C<JSON::PP::true> and C<JSON::PP::false>
967 instead of C<1> and C<0>. The Kubernetes API validates JSON types strictly
968 for custom resources.
969  
970 =head2 The status Subresource
971  
972 The CRD defined above already carries a status subresource -- the
973 C<subresources: { status: {} }> line under C<spec.versions[0]>. That single
974 line splits C<spec> and C<status> into two separate write paths.
975  
976 B<Once it's set, C<create>, C<update>, C<patch> and server-side apply all
977 stop writing C<status>.> The API server silently strips the C<status> stanza
978 from every write to the main endpoint and still answers 2xx, so the call
979 looks like it worked and nothing is stored:
980  
981 # Looks fine. Does nothing to status.
982 $site->status({ readyReplicas => 2 });
983 $api->update($site); # 200 OK
984  
985 my $refetched = $api->get('StaticWebSite', 'my-blog', namespace => 'default');
986 say defined $refetched->status ? 'status was written' : 'status is still undef';
987 # status is still undef
988  
989 Status has to go through the C</status> subresource instead, with
990 L<Kubernetes::REST/patch_status> or L<Kubernetes::REST/update_status>:
991  
992 # Partial update. Merge patch by default -- custom resources answer
993 # 415 to a strategic merge patch, so patch_status() doesn't use one.
994 my $updated = $api->patch_status('StaticWebSite', 'my-blog',
995 namespace => 'default',
996 patch => { status => { readyReplicas => 2, url => 'blog.example.com' } },
997 );
998  
999 # Full replace, like update() but scoped to status.
1000 $site->status({ readyReplicas => 2, url => 'blog.example.com' });
1001 $updated = $api->update_status($site);
1002  
1003 The built-in kinds (C<Pod>, C<Node>, C<Deployment>, ...) have always worked
1004 this way -- see L</INSPECTING POD STATUS> for reading one. Any controller
1005 that writes status, for a built-in kind or your own CRD, needs C<patch_status>
1006 or C<update_status>; C<create>/C<update>/C<patch> stay for C<spec> and
1007 C<metadata>.
1008  
1009 =head2 Serialization
1010  
1011 CRD objects support the same serialization as built-in resources:
1012  
1013 say $site->to_yaml;
1014 # ---
1015 # apiVersion: homelab.example.com/v1
1016 # kind: StaticWebSite
1017 # metadata:
1018 # name: my-blog
1019 # namespace: default
1020 # spec:
1021 # domain: blog.example.com
1022 # ...
1023  
1024 $site->save('/tmp/my-blog.yaml');
1025  
1026 =head2 AutoGen (dynamic class generation)
1027  
1028 If you don't want to write Perl classes by hand, you can generate them
1029 dynamically using L<IO::K8s::AutoGen>:
1030  
1031 use IO::K8s::AutoGen;
1032  
1033 my $class = IO::K8s::AutoGen::get_or_generate(
1034 'com.example.homelab.v1.StaticWebSite', # definition name
1035 $schema, # OpenAPI schema
1036 {}, # all definitions
1037 'MyApp::K8s', # namespace
1038 api_version => 'homelab.example.com/v1',
1039 kind => 'StaticWebSite',
1040 resource_plural => 'staticwebsites',
1041 is_namespaced => 1,
1042 );
1043  
1044 $api->resource_map->{StaticWebSite} = "+$class";
1045  
1046 # Now use it like any other resource
1047 my $site = $api->k8s->struct_to_object($class, {
1048 metadata => { name => 'my-blog', namespace => 'default' },
1049 spec => { domain => 'blog.example.com', image => 'nginx' },
1050 });
1051 $api->create($site);
1052  
1053 =head2 More CRD ideas
1054  
1055 Custom resources can simplify complex Kubernetes patterns for your homelab:
1056  
1057 =over 4
1058  
1059 =item * B<BackupSchedule> - wraps CronJob for scheduled backups with retention policies
1060  
1061 =item * B<DatabaseCluster> - wraps StatefulSet + PVC + Service for database instances
1062  
1063 =item * B<HomeService> - simplified Deployment + Service + optional Ingress
1064  
1065 =item * B<DNSRecord> - manages external DNS entries alongside cluster resources
1066  
1067 =back
1068  
1069 =head1 IO::K8s CLASS REFERENCE
1070  
1071 The objects returned by L<Kubernetes::REST> are all L<IO::K8s> classes.
1072 Here are the most commonly used ones:
1073  
1074 =over 4
1075  
1076 =item L<IO::K8s::Api::Core::V1::Pod> - Pods
1077  
1078 =item L<IO::K8s::Api::Core::V1::Service> - Services
1079  
1080 =item L<IO::K8s::Api::Core::V1::ConfigMap> - ConfigMaps
1081  
1082 =item L<IO::K8s::Api::Core::V1::Secret> - Secrets
1083  
1084 =item L<IO::K8s::Api::Core::V1::Namespace> - Namespaces
1085  
1086 =item L<IO::K8s::Api::Core::V1::PersistentVolumeClaim> - PersistentVolumeClaims
1087  
1088 =item L<IO::K8s::Api::Core::V1::ResourceQuota> - ResourceQuotas
1089  
1090 =item L<IO::K8s::Api::Core::V1::LimitRange> - LimitRanges
1091  
1092 =item L<IO::K8s::Api::Core::V1::ServiceAccount> - ServiceAccounts
1093  
1094 =item L<IO::K8s::Api::Apps::V1::Deployment> - Deployments
1095  
1096 =item L<IO::K8s::Api::Batch::V1::Job> - Jobs
1097  
1098 =item L<IO::K8s::Api::Batch::V1::CronJob> - CronJobs
1099  
1100 =item L<IO::K8s::Api::Rbac::V1::Role> - Roles
1101  
1102 =item L<IO::K8s::Api::Rbac::V1::RoleBinding> - RoleBindings
1103  
1104 =item L<IO::K8s::Api::Networking::V1::Ingress> - Ingress
1105  
1106 =item L<IO::K8s::Apimachinery::Pkg::Apis::Meta::V1::ObjectMeta> - object metadata
1107  
1108 =back
1109  
1110 All classes share these patterns:
1111  
1112 $obj->metadata->name; # resource name
1113 $obj->metadata->namespace; # namespace (if namespaced)
1114 $obj->metadata->labels; # hashref of labels
1115 $obj->metadata->uid; # unique ID assigned by Kubernetes
1116 $obj->kind; # "Pod", "Service", etc.
1117 $obj->api_version; # "v1", "apps/v1", etc.
1118 $obj->TO_JSON; # serialize to hashref
1119 $obj->to_yaml; # serialize to YAML string
1120  
1121 See L<IO::K8s> for full documentation on the object system, including
1122 type safety, YAML loading, and custom resource support.
1123  
1124 =head1 DEMO SCRIPT
1125  
1126 This distribution ships with a comprehensive runnable demo at
1127 C<eg/demo.pl>. It exercises most of the CRUD and watch functionality
1128 documented above in 22 steps against a live cluster (CRDs are not part of
1129 the script; see L</CUSTOM RESOURCE DEFINITIONS (CRDs)> above for those):
1130  
1131 perl eg/demo.pl
1132  
1133 The script connects via kubeconfig, creates a dedicated namespace, then
1134 walks through: LimitRange, ResourceQuota, ConfigMap, Secret, ServiceAccount,
1135 Role + RoleBinding, PersistentVolumeClaim, Deployment (2 replicas with
1136 volumes, probes, ConfigMap/Secret env vars), Service (NodePort), pod
1137 inspection, scaling to 3 replicas, patching (strategic merge and JSON merge),
1138 rolling image update, Job (run to completion), CronJob, utility Pod (with
1139 volume mounts and env vars from ConfigMap and Secret), full namespace
1140 inventory, YAML/JSON serialization with round-trip inflate, quota usage
1141 inspection, a short pod watch, and ordered cleanup.
1142  
1143 It works on Minikube, K3s, Kind, or any cluster with a kubeconfig.
1144  
1145 =head1 SEE ALSO
1146  
1147 L<Kubernetes::REST>, L<Kubernetes::REST::Kubeconfig>, L<IO::K8s>,
1148 L<https://minikube.sigs.k8s.io/>, L<https://k3s.io/>,
1149 L<https://kind.sigs.k8s.io/>, L<https://kubernetes.io/docs/>
1150  
1151 =head1 SUPPORT
1152  
1153 =head2 Issues
1154  
1155 Please report bugs and feature requests on GitHub at
1156 L<https://github.com/pplu/kubernetes-rest/issues>.
1157  
1158 =head2 IRC
1159  
1160 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
1161  
1162 =head1 CONTRIBUTING
1163  
1164 Contributions are welcome! Please fork the repository and submit a pull request.
1165  
1166 =head1 AUTHORS
1167  
1168 =over 4
1169  
1170 =item *
1171  
1172 Torsten Raudssus <getty@cpan.org>
1173  
1174 =item *
1175  
1176 Jose Luis Martinez Torres <jlmartin@cpan.org>
1177  
1178 =back
1179  
1180 =head1 COPYRIGHT AND LICENSE
1181  
1182 This software is Copyright (c) 2019-2026 by Jose Luis Martinez Torres <jlmartin@cpan.org>.
1183  
1184 This is free software, licensed under:
1185  
1186 The Apache License, Version 2.0, January 2004
1187  
1188 =cut