### Create Kubernetes IngressRoute Resource Instance in PHP Source: https://php-k8s.renoki.org/advanced/create-classes-for-crds/getting-started This PHP snippet demonstrates how to instantiate the `IngressRoute` class with a cluster object and resource specifications. It then calls the `create()` method to deploy the `IngressRoute` resource to the Kubernetes cluster. ```php $ir = new IngressRoute($cluster, [ 'spec' => [ 'entryPoints' => ... ], ]); $ir->create(); ``` -------------------------------- ### Install PHP-K8s Package via Composer Source: https://php-k8s.renoki.org/getting-started/installation This command installs the `renoki-co/php-k8s` package using Composer, the dependency manager for PHP. It is the standard method for integrating the package into a vanilla PHP project. ```bash composer require renoki-co/php-k8s ``` -------------------------------- ### Install a Helm release in PHP Source: https://php-k8s.renoki.org/frameworks/php-helm This PHP snippet demonstrates how to install a new Helm release using the `PhpHelm` library. It specifies the release name and the chart to install (e.g., 'stable/postgres'), then executes the command to deploy the release. ```php use RenokiCo\PhpHelm\Helm; $helm = Helm::install('my-release', 'stable/postgres'); $helm->run(); ``` -------------------------------- ### Install PHP Helm package via Composer Source: https://php-k8s.renoki.org/frameworks/php-helm This command installs the `renoki-co/php-helm` package into your PHP project using Composer, making the Helm wrapper available for use. It's the primary method for integrating the library. ```bash composer require renoki-co/php-helm ``` -------------------------------- ### Get Kubernetes Job Start and Completion Times in PHP Source: https://php-k8s.renoki.org/resources/workloads/job Illustrates how to retrieve the start and completion timestamps for a Kubernetes Job, which can be `null` or `DateTime` instances. ```php $start = $job->getStartTime(); $end = $job->getCompletionTime(); ``` -------------------------------- ### Install Laravel PHP K8s Package Source: https://php-k8s.renoki.org/frameworks/laravel Installs the `renoki-co/laravel-php-k8s` package using Composer, the dependency manager for PHP. This command adds the package to your project's dependencies. ```bash composer require renoki-co/laravel-php-k8s ``` -------------------------------- ### Create Kubernetes ClusterRole with RBAC Rules (PHP) Source: https://php-k8s.renoki.org/resources/rbac/cluster-role This snippet demonstrates how to define a Kubernetes RBAC rule to grant 'get', 'list', and 'watch' permissions on 'pods' and 'configmaps' with specific names. It then shows how to create a ClusterRole named 'admin' with labels and attach the defined rule to it, using the RenokiCo\PhpK8s library. ```php use RenokiCo\PhpK8s\Kinds\K8sPod; $rule = K8s::rule() ->core() ->addResources([K8sPod::class, 'configmaps']) ->addResourceNames(['pod-name', 'configmap-name']) ->addVerbs(['get', 'list', 'watch']); $role = $this->cluster ->clusterRole() ->setName('admin') ->setLabels(['tier' => 'backend']) ->addRules([$rule]) ->create(); ``` -------------------------------- ### Create Kubernetes RBAC Role, Rule, Subject, and RoleBinding in PHP Source: https://php-k8s.renoki.org/resources/rbac/rolebinding This PHP example demonstrates the creation of a Kubernetes RBAC Rule, Role, Subject, and RoleBinding using the RenokiCo\PhpK8s library. It defines a rule to grant 'get', 'list', and 'watch' permissions on pods and configmaps, assigns it to a role, creates a user subject, and binds the role to the subject. ```php use RenokiCo\PhpK8s\Kinds\K8sPod; $rule = K8s::rule() ->core() ->addResources([K8sPod::class, 'configmaps']) ->addResourceNames(['pod-name', 'configmap-name']) ->addVerbs(['get', 'list', 'watch']); $role = $this->cluster ->role() ->setName('admin') ->addRules([$rule]) ->create(); $subject = K8s::subject() ->setApiGroup('rbac.authorization.k8s.io') ->setKind('User') ->setName('user-1'); $rb = $this->cluster ->roleBinding() ->setName('user-binding') ->setRole($role, 'rbac.authorization.k8s.io') ->setSubjects([$subject]) ->create(); ``` -------------------------------- ### Initialize KubernetesCluster from kubectl proxy URL in PHP Source: https://php-k8s.renoki.org/getting-started/authentication This snippet demonstrates how to initialize a `KubernetesCluster` instance by providing a URL, typically for a `kubectl proxy` setup. It uses the `fromUrl` static method to connect to the local Kubernetes API. ```php use RenokiCo\PhpK8s\KubernetesCluster; $cluster = KubernetesCluster::fromUrl('http://127.0.0.1:8080'); ``` -------------------------------- ### Attach Liveness, Startup, and Readiness Probes to Container in PHP Source: https://php-k8s.renoki.org/instances/container This example shows how to configure and attach liveness, startup, and readiness probes to a Kubernetes container using the K8s fluent API in PHP. It demonstrates setting command, HTTP, and TCP probes with various parameters like initial delay, period, timeout, and thresholds to ensure container health and availability. ```php $container->setLivenessProbe( K8s::probe() ->command(['sh', 'test.sh']) ->setInitialDelaySeconds(10) ->setPeriodSeconds(60) ->setTimeoutSeconds(10) ->setFailureThreshold(3) ->setSuccessThreshold(2) ); $container->setStartupProbe( K8s::probe() ->http('/health', 80, ['X-CSRF-TOKEN' => 'some-token']) ->setInitialDelaySeconds(10) ->setPeriodSeconds(60) ->setTimeoutSeconds(10) ->setFailureThreshold(3) ->setSuccessThreshold(2) ); $container->setReadinessProbe( K8s::probe() ->tcp(3306, '10.0.0.0') ->setInitialDelaySeconds(10) ->setPeriodSeconds(60) ->setTimeoutSeconds(10) ->setFailureThreshold(3) ->setSuccessThreshold(2) ); ``` -------------------------------- ### Define and Create Kubernetes RBAC Role with PHP K8s Source: https://php-k8s.renoki.org/resources/rbac/role This snippet demonstrates how to define a Kubernetes RBAC rule to grant 'get', 'list', and 'watch' verbs on 'K8sPod' and 'configmaps' resources with specific names. It then creates a 'Role' named 'admin' and attaches the defined rule to it using the RenokiCo\PhpK8s library. ```php use RenokiCo\PhpK8s\Kinds\K8sPod; $rule = K8s::rule() ->core() ->addResources([K8sPod::class, 'configmaps']) ->addResourceNames(['pod-name', 'configmap-name']) ->addVerbs(['get', 'list', 'watch']); $role = $this->cluster ->role() ->setName('admin') ->addRules([$rule]) ->create(); ``` -------------------------------- ### Define Kubernetes IngressRoute CRD Class in PHP Source: https://php-k8s.renoki.org/advanced/create-classes-for-crds/getting-started This PHP class defines an `IngressRoute` Custom Resource Definition (CRD) by extending `K8sResource` and implementing `InteractsWithK8sCluster`. It specifies the resource kind, default API version, and namespaceability. ```php use RenokiCo\PhpK8s\Contracts\InteractsWithK8sCluster; use RenokiCo\PhpK8s\Kinds\K8sResource; class IngressRoute extends K8sResource implements InteractsWithK8sCluster { /** * The resource Kind parameter. * * @var null|string */ protected static $kind = 'IngressRoute'; /** * The default version for the resource. * * @var string */ protected static $defaultVersion = 'traefik.containo.us/v1alpha1'; /** * Wether the resource has a namespace. * * @var bool */ protected static $namespaceable = true; } ``` -------------------------------- ### Define Templated YAML for Dynamic Values Source: https://php-k8s.renoki.org/interacting-with-the-cluster/import-from-yaml Shows an example of a YAML file structure with placeholders (curly brackets `{}`) for dynamic values. This templated YAML can be used with `fromTemplatedYamlFile` to inject data programmatically at runtime. ```YAML apiVersion: v1 kind: ConfigMap metadata: name: settings data: key1: "{value1}" key2: "{value2}" ``` -------------------------------- ### Create HorizontalPodAutoscaler with PHP K8s Source: https://php-k8s.renoki.org/resources/scaling-and-availability/horizontalpodautoscaler This example demonstrates the full process of defining a container, pod, and deployment, then creating a Horizontal Pod Autoscaler (HPA) that targets the deployment based on CPU utilization. It shows how to set minimum and maximum replica counts for the HPA. ```php use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306], ]); $pod = K8s::pod() ->setName('mysql') ->setLabels(['tier' => 'backend']) ->setContainers([$mysql]); $dep = $this->cluster ->deployment() ->setName('mysql') ->setSelectors(['matchLabels' => ['tier' => 'backend']]) ->setReplicas(1) ->setTemplate($pod) ->create(); $cpuMetric = K8s::metric() ->cpu() ->averageUtilization(70); $hpa = $this->cluster ->horizontalPodAutoscaler() ->setName('deploy-mysql') ->setResource($dep) ->addMetrics([$cpuMetric]) ->min(1) ->max(10) ->create(); ``` -------------------------------- ### PHP K8s: Initialize KubernetesCluster with 2.x and 3.x Authentication Methods Source: https://php-k8s.renoki.org/upgrading-from-2 This snippet demonstrates the evolution of authentication methods for the `RenokiCo\PhpK8s\KubernetesCluster` class. It compares older instance-based methods (2.x) with new static factory methods (3.x) for initializing a cluster using URLs, KubeConfig variables, files, or in-cluster configurations. An example of iterating through all pods after cluster initialization is also included. ```PHP use RenokiCo\PhpK8s\KubernetesCluster; // 2.x method $cluster = new KubernetesCluster('http://127.0.0.1:8080'); $cluster = (new KubernetesCluster(...))->fromKubeConfigVariable('context-name'); $cluster = (new KubernetesCluster(...))->fromKubeConfigYamlFile('/.kube/config', 'context-name'); $cluster = (new KubernetesCluster(...))->inClusterConfiguration(); // 3.x method $cluster = KubernetesCluster::fromUrl('http://127.0.0.1:8080'); $cluster = KubernetesCluster::fromKubeConfigVariable('context-name'); $cluster = KubernetesCluster::fromKubeConfigYamlFile('/.kube/config', 'context-name'); $cluster = KubernetesCluster::inClusterConfiguration(); // Example on using the $cluster method. foreach ($cluster->getAllPods() as $pod) { // } ``` -------------------------------- ### Creating a Kubernetes CronJob with PHP K8s Source: https://php-k8s.renoki.org/resources/workloads/cronjob This example demonstrates how to define and create a Kubernetes CronJob using the `RenokiCo\PhpK8s` library. It involves setting up a container, a pod template, and a job template, then configuring the CronJob with a schedule (e.g., hourly) before deploying it to the cluster. ```php use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('pi') ->setImage('perl') ->setCommand(['perl', '-Mbignum=bpi', '-wle', 'print bpi(2000)']); $pod = K8s::pod() ->setName('pi') ->setLabels(['job-name' => 'pi']) // needs job-name: pi so that ->getPods() can work ->setContainers([$container]) ->restartOnFailure(); $job = K8s::job() ->setName('pi') ->setSelectors(['matchLabels' => ['tier' => 'backend']]) ->setTemplate($pod); $cronjob = $this->cluster ->cronjob() ->setName('pi') ->setLabels(['tier' => 'backend']) ->setAnnotations(['perl/annotation' => 'yes']) ->setJobTemplate($job) ->setSchedule(CronExpression::factory('@hourly')) ->create(); ``` -------------------------------- ### Initialize KubernetesCluster from remote cluster URL in PHP Source: https://php-k8s.renoki.org/getting-started/authentication This example shows how to initialize a `KubernetesCluster` instance by providing a full URL to a remote Kubernetes cluster endpoint. It uses the `fromUrl` static method to establish a connection. ```php use RenokiCo\PhpK8s\KubernetesCluster; $cluster = KubernetesCluster::fromUrl( 'https://cluster-id.api.k8s.fr-par.scw.cloud:6443' ); ``` -------------------------------- ### Create Kubernetes ConfigMap with Data and Labels (PHP) Source: https://php-k8s.renoki.org/resources/configurations/configmap Demonstrates how to create a Kubernetes ConfigMap named 'certificates' with custom labels and data using the PHP Kubernetes client. The data includes example PEM keys. ```php $cm = $this->cluster ->configmap() ->setName('certificates') ->setLabels(['tier' => 'backend']) ->setData([ 'key.pem' => '...', 'ca.pem' => '...' ]) ->create(); ``` -------------------------------- ### Create Kubernetes Service using PHP Library Source: https://php-k8s.renoki.org/resources/networking/service This PHP snippet illustrates how to define and create a Kubernetes Service resource. It uses a fluent interface to set the service's name, associate labels for organization, define selectors to target specific pods (e.g., 'app' => 'frontend'), and configure the network ports (TCP, port 80, targetPort 80) for exposing the application. The `cluster` object is assumed to be an initialized client for interacting with the Kubernetes API. ```php $svc = $this->cluster ->service() ->setName('nginx') ->setLabels(['tier' => 'backend']) ->setSelectors(['app' => 'frontend']) ->setPorts([ ['protocol' => 'TCP', 'port' => 80, 'targetPort' => 80] ]) ->create(); ``` -------------------------------- ### Create a MySQL StatefulSet with PHP K8s Source: https://php-k8s.renoki.org/resources/workloads/statefulset Demonstrates how to define and create a Kubernetes StatefulSet for a MySQL application using the PHP K8s library, including container, pod, service, and persistent volume claim definitions. This example sets up a MySQL instance with a persistent volume and a headless service. ```PHP use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306], ]); $pod = K8s::pod() ->setName('mysql') ->setLabels(['statefulset-name' => 'mysql']) // needs statefulset-name: mysql so that ->getPods() can work ->setContainers([$mysql]); $svc = $this->cluster ->service() ->setName('mysql') ->setPorts([ ['protocol' => 'TCP', 'port' => 3306, 'targetPort' => 3306], ])->create(); $pvc = $this->cluster ->persistentVolumeClaim() ->setName('mysql-pvc') ->setCapacity(1, 'Gi') ->setAccessModes(['ReadWriteOnce']) ->create(); $sts = $this->cluster ->statefulSet() ->setName('mysql') ->setSelectors(['matchLabels' => ['tier' => 'backend']]) ->setReplicas(1) ->setService($svc) ->setTemplate($pod) ->setVolumeClaims([$pvc]) ->create(); ``` -------------------------------- ### PHP K8s: Chain Authentication Options to KubernetesCluster Instances Source: https://php-k8s.renoki.org/upgrading-from-2 This snippet illustrates how to apply additional authentication options like tokens, certificates, and private keys to a `KubernetesCluster` instance. These methods can be chained directly during initialization or called on an existing cluster object to secure API access. The example concludes by fetching all pods, demonstrating successful authentication. ```PHP $cluster = KubernetesCluster::fromUrl('http://127.0.0.1:8080') ->withToken('ey...'); $cluster->withToken('ey...') ->withCertificate($pathToCert) ->withPrivateKey($pathToKey); $pods = $cluster->getAllPods(); ``` -------------------------------- ### Iterate Through Pod Container Statuses (PHP) Source: https://php-k8s.renoki.org/resources/workloads/pod Provides examples of iterating through the statuses of both regular and init containers within a pod using `getContainerStatuses()` and `getInitContainerStatuses()` to access individual container details. ```PHP foreach ($pod->getContainerStatuses() as $container) { // $container->getName(); } foreach ($pod->getInitContainerStatuses() as $container) { // $container->getName(); } ``` -------------------------------- ### Upgrade a Helm release in PHP Source: https://php-k8s.renoki.org/frameworks/php-helm This PHP example illustrates how to upgrade an existing Helm release using the `PhpHelm` library. It specifies the release name and the chart to upgrade to, then executes the command to apply updates to the deployed release. ```php use RenokiCo\PhpHelm\Helm; $helm = Helm::upgrade('my-release', 'stable/postgres'); $helm->run(); ``` -------------------------------- ### Create Kubernetes Service using PHP K8s Library Source: https://php-k8s.renoki.org/getting-started/showcase Illustrates how to define and create a Kubernetes Service resource programmatically using the RenokiCo\PhpK8s library. It connects to a Kubernetes cluster and configures an NGINX service with selectors and port mappings similar to the YAML example. ```php use RenokiCo\PhpK8s\KubernetesCluster; // Create a new instance of KubernetesCluster. $cluster = KubernetesCluster::fromUrl('http://127.0.0.1:8080'); // Create a new NGINX service. $svc = $cluster->service() ->setName('nginx') ->setNamespace('frontend') ->setSelectors(['app' => 'frontend']) ->setPorts([ ['protocol' => 'TCP', 'port' => 80, 'targetPort' => 80], ]) ->create(); ``` -------------------------------- ### Watch Specific Kubernetes Pod with Resource Version (PHP) Source: https://php-k8s.renoki.org/interacting-with-the-cluster/watching-resources Illustrates how to pass additional query parameters, like `resourceVersion`, to the `watchByName` method. This allows for more precise control over the watch operation, starting from a specific point in time. ```PHP $cluster->pod()->watchByName('mysql', function ($type, $pod) { // Waiting for a change. }, ['resourceVersion' => $pod->getResourceVersion()]); ``` -------------------------------- ### Refresh Pod Status and Retrieve Network Information (PHP) Source: https://php-k8s.renoki.org/resources/workloads/pod Shows how to refresh a pod's status to get the latest information and retrieve its IP addresses, host IP, and Quality of Service (QoS) class using the `refresh()`, `getPodIps()`, `getHostIp()`, and `getQos()` methods. ```PHP $pod->refresh(); $pod->getPodIps(); $pod->getHostIp(); $pod->getQos(); ``` -------------------------------- ### Retrieve All Kubernetes Config Maps in Laravel Source: https://php-k8s.renoki.org/frameworks/laravel Demonstrates how to use the `LaravelK8sFacade` to fetch and iterate through all Kubernetes Config Maps. This example assumes a default cluster configuration, typically from `~/.kube/config`. ```php use RenokiCo\LaravelK8s\LaravelK8sFacade as K8s; foreach (K8s::getAllConfigMaps() as $cm) { // $cm->getName(); } ``` -------------------------------- ### APIDOC: whereNamespace Method Alias Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods An alias method designed to improve filtering capabilities for 'get' methods by providing a more descriptive naming convention. ```APIDOC whereNamespace($namespace): Alias for getNamespace(). Used for better filtering on get methods. ``` -------------------------------- ### Retrieving Job Template from a CronJob in PHP Source: https://php-k8s.renoki.org/resources/workloads/cronjob These snippets illustrate how to retrieve the job template associated with a CronJob. The first example fetches the template as a `K8sJob` instance, allowing direct method calls. The second example retrieves the template as a raw PHP array by passing `false` to the retrieval method. ```php $template = $cronjob->getJobTemplate(); $jobName = $template->getName(); ``` ```php $pod = $cronjob->getJobTemplate(false); $jobName = $template['name']; ``` -------------------------------- ### Create an HTTP Probe for Kubernetes Containers in PHP Source: https://php-k8s.renoki.org/instances/container-probes This snippet shows how to define an HTTP-based liveness or readiness probe using the PHP K8s client. The probe makes an HTTP GET request to a specified path and port, optionally including custom headers, to check the container's health. ```php $probe = K8s::probe()->http('/health', 80, ['X-CSRF-TOKEN' => 'some-token']) ``` -------------------------------- ### Get Annotations for PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve all annotations associated with the Kubernetes resource. This returns an array of key-value pairs. ```php $service->getAnnotations(); ``` -------------------------------- ### Add Helm repository with multiple flags in PHP Source: https://php-k8s.renoki.org/frameworks/php-helm This PHP example shows how to add a Helm repository while specifying multiple flags like `--no-update` and `--debug`. The flags are passed as an associative array to the `addRepo` method, providing fine-grained control over the command execution. ```php use RenokiCo\PhpHelm\Helm; $helm = Helm::addRepo('stable', 'https://charts.helm.sh/stable', [ '--no-update' => true, '--debug' => true, ]); $helm->run(); ``` -------------------------------- ### Attach K8sSecret Instance to Service Account (PHP) Source: https://php-k8s.renoki.org/resources/rbac/service-account This example shows how to create a Kubernetes Secret instance and then attach it to an existing Service Account by passing the K8sSecret object, followed by updating the Service Account. ```php $secret = $this->cluster ->secret() ->setName('passwords') ->addData('postgres', 'postgres') ->create(); $sa->addSecrets([$secret])->update(); ``` -------------------------------- ### Get Kubernetes Cluster Instance in Laravel Source: https://php-k8s.renoki.org/frameworks/laravel Shows how to retrieve the underlying `\RenokiCo\PhpK8s\KubernetesCluster` instance from the Laravel facade. This allows direct access to the full API of the `php-k8s` library. ```php $cluster = K8s::getCluster(); ``` -------------------------------- ### Retrieve StatefulSet Pod Template as K8sPod Object Source: https://php-k8s.renoki.org/resources/workloads/statefulset Shows how to get the pod template associated with a StatefulSet as a `K8sPod` class instance, allowing access to its properties like name through object methods. ```PHP $template = $sts->getTemplate(); $podName = $template->getName(); ``` -------------------------------- ### Retrieve StatefulSet Replica Status Counts in PHP Source: https://php-k8s.renoki.org/resources/workloads/statefulset Shows how to refresh a StatefulSet instance to get the latest status and then retrieve various replica counts, including current, ready, and desired replicas, using the Status API methods. ```PHP $sts->refresh(); $sts->getCurrentReplicasCount(); $sts->getReadyReplicasCount(); $sts->getDesiredReplicasCount(); ``` -------------------------------- ### Retrieve RBAC Rules from a Role in PHP K8s Source: https://php-k8s.renoki.org/resources/rbac/role This snippet shows how to iterate through and retrieve the 'Rule' instances associated with a previously created 'Role' object using the `getRules()` method provided by the RenokiCo\PhpK8s library. ```php foreach ($role->getRules() as $rule) { // } ``` -------------------------------- ### Iterate Through Kubernetes RBAC Rules (PHP) Source: https://php-k8s.renoki.org/resources/rbac/cluster-role This snippet illustrates how to retrieve and iterate over the rules associated with a Kubernetes ClusterRole instance. The `getRules()` method returns a collection of `RenokiCo\PhpK8s\Instances\Rule` objects, allowing programmatic access to each defined rule. ```php foreach ($role->getRules() as $role) { // } ``` -------------------------------- ### Set Helm binary path programmatically in PHP Source: https://php-k8s.renoki.org/frameworks/php-helm This PHP snippet shows how to programmatically set the path to the Helm CLI binary using `Helm::setHelmPath()`. This ensures the library uses the specified Helm executable, which is useful for custom installations or environments. ```php use RenokiCo\PhpHelm\Helm; Helm::setHelmPath('/usr/bin/my-path/helm'); ``` -------------------------------- ### Watch a Specific IngressRoute Resource in PHP Source: https://php-k8s.renoki.org/advanced/create-classes-for-crds/watchable-resources This example shows how to directly call the `watch` method on an instantiated `IngressRoute` object. It targets a specific resource named 'foo' and sets up a callback function that will be executed whenever changes are detected for that resource, providing the event type and the updated resource object. ```php (new IngressRoute($cluster))->whereName('foo')->watch(function ($type, $ir) { // }); ``` -------------------------------- ### Set Resource Limits and Requests for Container in PHP Source: https://php-k8s.renoki.org/instances/container This example shows how to define CPU and memory resource limits and requests for a Kubernetes container using the K8s fluent API in PHP. It allows specifying minimum and maximum values for memory (Mi, Gi) and CPU (m, cores) to manage resource consumption. ```php $container->minMemory(512, 'Mi')->maxMemory(2, 'Gi'); $container->minCpu('500m')->maxCpu(1); ``` -------------------------------- ### PHP K8s: Retrieve a Specific Resource Source: https://php-k8s.renoki.org/interacting-with-the-cluster/crud-operations Illustrates how to retrieve a single Kubernetes resource by name and namespace using the `->get()` method with `whereNamespace()` and `whereName()`, or using shorthand methods like `getByName()` and `getServiceByName()`. Default namespace is 'default'. ```php $service = $cluster->service()->whereNamespace('staging')->whereName('nginx')->get(); // You can also shorten it like $service = $cluster->service()->whereNamespace('staging')->getByName('nginx'); // Or you can use a specific method to call it in at once $service = $cluster->getServiceByName('nginx', 'staging'); ``` -------------------------------- ### Retrieve HorizontalPodAutoscaler Status in PHP K8s Source: https://php-k8s.renoki.org/resources/scaling-and-availability/horizontalpodautoscaler This example shows how to refresh the state of a Horizontal Pod Autoscaler (HPA) instance and retrieve its current, desired, and unavailable replica counts. It provides methods for monitoring the HPA's scaling activity. ```php $hpa->refresh(); $hpa->getCurrentReplicasCount(); $hpa->getDesiredReplicasCount(); $hpa->getUnavailableReplicasCount(); ``` -------------------------------- ### PHP K8s: Add Required Node Scheduling Affinity with addNodeRequirement Source: https://php-k8s.renoki.org/instances/affinity This example shows how to use `addNodeRequirement` for `requiredDuringSchedulingIgnoredDuringExecution`. It defines a strict requirement for node scheduling based on availability zone and tier expressions, ensuring pods are only scheduled on nodes matching these criteria. ```php use RenokiCo\PhpK8s\K8s; $az = K8s::expression()->in('azname', ['us-east-1a', 'us-east-1b']); $tier = K8s::expression()->in('tier', ['backend']); $affinity = K8s::affinity()->addNodeRequirement( [$az], [$type] ); // requires AZ and tier: backend ``` -------------------------------- ### Accessing Status Attributes with HasStatus Trait Source: https://php-k8s.renoki.org/advanced/create-classes-for-crds/helper-traits This example shows how to retrieve a specific status attribute from an instance of a Kubernetes resource that uses the `HasStatus` trait. The `getStatus()` method allows accessing nested values using a dot-separated path. ```PHP $gameServerSet->getStatus('some.path'); ``` -------------------------------- ### Create Kubernetes Deployment with PhpK8s Source: https://php-k8s.renoki.org/resources/workloads/deployment This snippet demonstrates how to create a Kubernetes Deployment using the `PhpK8s` library. It defines a MySQL container, a pod template with labels, and then constructs a Deployment resource with a single replica, linking it to the pod template. ```php use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306], ]); $pod = K8s::pod() ->setName('mysql') ->setLabels(['tier' => 'backend']) // needs deployment-name: mysql so that ->getPods() can work ->setContainers([$container]); $dep = $this->cluster ->deployment() ->setName('mysql') ->setSelectors(['matchLabels' => ['tier' => 'backend']]) ->setReplicas(1) ->setTemplate($pod) ->create(); ``` -------------------------------- ### Dynamically Setting and Getting Node Selector for K8sPod Source: https://php-k8s.renoki.org/resources/base-resource/cluster-methods This snippet demonstrates how to use the dynamic `setNodeSelector` and `getNodeSelector` methods on a `K8sPod` instance. These methods allow you to set or retrieve attributes that do not have explicit function implementations, leveraging the magic method capabilities of the RenokiCo\PhpK8s library. The `getNodeSelector` method shows how to provide a default value if the attribute is not set. ```php $pod->setNodeSelector(['type' => 'spot']); $pod->getNodeSelector([]); // defaults to [] if not existent ``` -------------------------------- ### Scale Deployment Replicas using Shorthand Method Source: https://php-k8s.renoki.org/resources/workloads/deployment This snippet provides a shorthand method to scale a Deployment directly by calling `scale()` on the Deployment object with the desired replica count. It then shows how to retrieve the updated list of pods. ```php $scaler = $dep->scale(3); $pods = $dep->getPods(); // Expecting 3 pods ``` -------------------------------- ### Retrieving Active Jobs for a CronJob in PHP Source: https://php-k8s.renoki.org/resources/workloads/cronjob This example illustrates how to retrieve and interact with active jobs associated with a CronJob. It includes a loop to refresh the CronJob until an active job is found, and then demonstrates how to access the pods related to that active `K8sJob` instance. Active jobs are returned as an `\Illuminate\Support\Collection`. ```php while (! $job = $cronjob->getActiveJobs()->first()) { $cronjob->refresh(); sleep(1); } // You can get the scheduled Job's pods. $job->getPods(); ``` -------------------------------- ### Set Environment Variables for Kubernetes Container in PHP Source: https://php-k8s.renoki.org/instances/container This example illustrates how to directly set and append environment variables to a Kubernetes container object using the `setEnv()` and `addEnv()` methods in PHP. It's used for providing configuration data to the container. ```php $container->setEnv([ 'MYSQL_ROOT_PASSWORD' => 'test', ]); $container->addEnv('MYSQL_DATABASE', 'my_db') // this will append an env ``` -------------------------------- ### Define K8sPod Macro to Change Metadata (PHP) Source: https://php-k8s.renoki.org/advanced/macros This PHP example illustrates defining another custom macro, `changeMetadata`, for the `K8sPod` class. This macro enables setting the metadata of a Kubernetes Pod instance using an array. It showcases how macros can accept parameters and integrate with custom callers for flexible object manipulation. ```php use RenokiCo\PhpK8s\Kinds\K8sPod; K8sPod::macro('changeMetadata', function (array $metadata) { return $this->setMetadata($metadata); }); $pod->changeMetadata(['name' => 'mysql']); ``` -------------------------------- ### Scale Deployment Replicas using K8sScale Object Source: https://php-k8s.renoki.org/resources/workloads/deployment This snippet demonstrates how to scale a Deployment to a desired number of replicas (e.g., 3) by accessing the `K8sScale` resource via the `scaler()` method and then calling `setReplicas()` and `update()`. ```php $scaler = $dep->scaler(); $scaler->setReplicas(3)->update(); // autoscale the Deployment to 3 replicas ``` -------------------------------- ### Execute basic Helm repository add command in PHP Source: https://php-k8s.renoki.org/frameworks/php-helm This PHP snippet demonstrates the fundamental usage of the `PhpHelm` library to add a Helm repository. It initializes a Helm command, executes it using `->run()`, and then retrieves the output from the underlying Symfony process for inspection. ```php use RenokiCo\PhpHelm\Helm; $helm = Helm::repoAdd( 'add', 'stable', 'https://charts.helm.sh/stable' ); $helm->run(); // The process is based on symfony/process echo $helm->getOutput(); ``` -------------------------------- ### Add ConfigMap Reference Environment Variables in PHP Source: https://php-k8s.renoki.org/instances/container This example demonstrates how to add environment variables to a Kubernetes container from a Kubernetes ConfigMap using `addConfigMapRef()` and `addConfigMapRefs()` methods in PHP. ConfigMaps are used for non-sensitive configuration data, referencing a key within a config map. ```php $container->addConfigMapRef('MYSQL_ROOT_PASSWORD', 'configmap-name', 'ref_key'); $container->addConfigMapRefs([ 'MYSQL_ROOT_PASSWORD' => ['cm-name', 'ref_key'], 'MYSQL_DATABASE' => ['cm-name', 'ref_key'], ]); ``` -------------------------------- ### Get Kind of PHP K8s Resource Statically Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve the 'Kind' of the Kubernetes resource. This method is called statically on the resource class to get its type. ```php $kind = $namespace::getKind(); ``` -------------------------------- ### Retrieve Pod Disruption Budget Status in PHP Source: https://php-k8s.renoki.org/resources/scaling-and-availability/poddisruptionbudget This snippet demonstrates how to access the current status of a Pod Disruption Budget (PDB) instance. It shows refreshing the PDB object to get the latest data from the Kubernetes API, and then retrieving the status information using the getStatus() method. ```php $pdb->refresh(); $status = $pdb->getStatus(); ``` -------------------------------- ### Retrieve Pod Template as Array Source: https://php-k8s.renoki.org/resources/workloads/deployment This snippet illustrates how to retrieve the pod template associated with a Deployment as a plain array by passing `false` to the `getTemplate` method, enabling array-style access to its properties. ```php $pod = $dep->getTemplate(false); $podName = $template['name']; ``` -------------------------------- ### Get Labels for PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve all labels associated with the Kubernetes resource. This returns an array of key-value pairs. ```php $service->getLabels(); ``` -------------------------------- ### Get Name for PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve the name of the Kubernetes resource. This method provides the unique identifier assigned to the resource. ```php $namespace->getName(); ``` -------------------------------- ### Create Kubernetes DaemonSet with PHP K8s Source: https://php-k8s.renoki.org/resources/workloads/daemonset Demonstrates how to define and create a Kubernetes DaemonSet using the RenokiCo\PhpK8s library. This snippet shows how to set up a container, a pod template, and then configure the DaemonSet with labels, update strategy, and the pod template. ```php use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306], ]); $pod = K8s::pod() ->setName('mysql') ->setLabels(['daemonset-name' => 'mysql']) // needs daemonset-name: mysql so that ->getPods() can work ->setContainers([$mysql]); $ds = $this->cluster ->daemonSet() ->setName('mysql') ->setLabels(['tier' => 'backend']) ->setUpdateStrategy('RollingUpdate') ->setMinReadySeconds(0) ->setTemplate($pod); ``` -------------------------------- ### Instantiate Custom Podable Resource in PHP K8s Source: https://php-k8s.renoki.org/advanced/create-classes-for-crds/podable-resources Demonstrates how to instantiate the `GameServerSet` class, providing metadata including the resource name and a template spec with matching labels for pod identification. The `metadata.name` must match `spec.template.metadata.labels['game-server-name']` for `podsSelector()` to work correctly. ```php $gameServerSet = new GameServerSet($cluster, [ 'metadata' => [ 'name' => 'some-name', // this is metadata.name ], 'spec' => [ 'template' => [ 'metadata' => [ 'labels' => [ 'game-server-name' => 'some-name', // this must match with metadata.name ], ], ... ], ... ], ... ]); ``` -------------------------------- ### Get Namespace for PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve the namespace that the Kubernetes resource belongs to. This method is typically applicable only to resources that are namespaceable. ```php $service->getNamespace(); ``` -------------------------------- ### Create a Command Probe for Kubernetes Containers in PHP Source: https://php-k8s.renoki.org/instances/container-probes This snippet demonstrates how to create a command-based liveness or readiness probe using the PHP K8s client. The probe executes a specified command inside the container to determine its health. ```php $probe = K8s::probe()->command(['sh', 'test.sh']); ``` -------------------------------- ### Get API Version of PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve the API version of the Kubernetes resource. This indicates the version of the API group that the resource belongs to. ```php $namespace->getApiVersion(); ``` -------------------------------- ### Configure SSL/TLS with certificate and private key for KubernetesCluster in PHP Source: https://php-k8s.renoki.org/getting-started/authentication This snippet demonstrates how to provide SSL/TLS client certificate and private key paths for secure communication with the Kubernetes API. The `withCertificate` and `withPrivateKey` methods are chained to set the SSL credentials. ```php $cluster->withCertificate($pathToCert)->withPrivateKey($pathToKey); ``` -------------------------------- ### Get Specific Annotation from PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve the value of a specific annotation by its key from the Kubernetes resource. An optional default value can be provided if the annotation does not exist. ```php $service->getAnnotation('kubernetes.io/some-annotation'); // "yes" $service->getAnnotation('kubernetes.io/non-existing-annotation'); // null ``` -------------------------------- ### PHP K8s: Retrieve All Resources Source: https://php-k8s.renoki.org/interacting-with-the-cluster/crud-operations Demonstrates how to retrieve all resources of a specific type (e.g., namespaces) or all services within a given namespace using the `->all()` method or specific getter methods like `getAllNamespaces()` and `getAllServices('staging')`. The result is a `RenokiCo\PhpK8s\ResourcesList` instance. ```php $namespaces = $cluster->namespace()->all(); // Or you can use a specific method to call it at once $namespaces = $cluster->getAllNamespaces(); // For namespaced resources, you may pass the namespace $stagingServices = $cluster->getAllServices('staging'); ``` -------------------------------- ### Get Specific Label from PHP K8s Resource Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods Retrieve the value of a specific label by its key from the Kubernetes resource. An optional default value can be provided if the label does not exist. ```php $service->getLabel('tier'); // "backend" $service->getLabel('not-a-label'); // null ``` -------------------------------- ### Retrieve Pod Template as K8sPod Object in PHP Source: https://php-k8s.renoki.org/resources/workloads/job Shows how to get the pod template associated with a Kubernetes Job as a K8sPod object, allowing access to its properties like name. ```php $template = $job->getTemplate(); $podName = $template->getName(); ``` -------------------------------- ### PHP K8s: Get Resource Attribute Source: https://php-k8s.renoki.org/resources/base-resource/attributes-methods-1 Retrieves an attribute from a resource instance. If the attribute does not exist, a default value can be provided. Supports dot notation for accessing nested fields within the attribute structure. ```PHP $configmap->getAttribute('data', []); ``` ```PHP $configmap->getAttribute('data.key', ''); ``` -------------------------------- ### Retrieve Deployment Status Metrics Source: https://php-k8s.renoki.org/resources/workloads/deployment This snippet shows how to refresh a Deployment's status and retrieve various replica counts, including ready, desired, and unavailable replicas, using methods like `getReadyReplicasCount()`. ```php $dep->refresh(); $dep->getReadyReplicasCount(); $dep->getDesiredReplicasCount(); $dep->getUnavailableReplicasCount(); ``` -------------------------------- ### Check if Kubernetes Namespace is Active (PHP) Source: https://php-k8s.renoki.org/resources/namespace Refreshes the namespace instance to get the latest status and then checks if the namespace is currently active. This is useful for verifying the operational status of a namespace after creation or modification. ```php $ns->refresh(); if ($ns->isActive()) { // } ``` -------------------------------- ### Configure and Create a Container with PHP K8s Source: https://php-k8s.renoki.org/resources/workloads/pod This snippet demonstrates how to define a Kubernetes container using the `RenokiCo\PhpK8s\K8s` facade. It sets the container name, image, ports, command, arguments, and environment variables for a MySQL container. ```php use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306], ]) ->addPort(3307, 'TCP', 'mysql-alt') ->setCommand(['mysqld']) ->setArgs(['--test']) ->setEnv(['MYSQL_ROOT_PASSWORD' => 'test']); ``` -------------------------------- ### Define Basic Kubernetes Container in PHP Source: https://php-k8s.renoki.org/instances/container This snippet demonstrates how to initialize a Kubernetes container object using the K8s fluent API in PHP. It sets the container name, image, version, and defines network ports, including adding an additional port. It also shows how to specify the command and arguments for the container. ```php $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306], ]) ->addPort(3307, 'TCP', 'mysql-alt') ->setCommand(['mysqld']) ->setArgs(['--test']); ``` -------------------------------- ### Define CPU and Memory Resource Metrics in PHP Source: https://php-k8s.renoki.org/instances/resource-metrics This snippet demonstrates how to define CPU and memory resource metrics using the K8s::metric() helper in PHP. It shows how to set an average CPU utilization percentage and an average memory value in MiB. ```php $cpuMetric = K8s::metric()->cpu()->averageUtilization(70); $memoryMetric = K8s::metric()->memory()->averageValue('512Mi'); ``` -------------------------------- ### Check if Pod Containers are Ready (PHP) Source: https://php-k8s.renoki.org/resources/workloads/pod Demonstrates how to check if all regular containers or init containers within a pod are in a ready state using `containersAreReady()` and `initContainersAreReady()` methods. ```PHP if ($pod->containersAreReady()) { // } if ($pod->initContainersAreReady()) { // } ``` -------------------------------- ### PHP: Create Kubernetes StorageClass Source: https://php-k8s.renoki.org/resources/storage/storageclass This PHP snippet demonstrates how to instantiate and configure a Kubernetes StorageClass object. It sets the name to 'gp2', specifies 'csi.aws.amazon.com' as the provisioner, defines 'type' as 'gp2' in parameters, and adds 'debug' to mount options before creating the resource. ```php $sc = $this->cluster ->storageClass() ->setName('gp2') ->setProvisioner('csi.aws.amazon.com') ->setParameters(['type' => 'gp2']) ->setMountOptions(['debug']) ->create(); ``` -------------------------------- ### Create Kubernetes Events for Resources (PHP K8s) Source: https://php-k8s.renoki.org/resources/event This snippet demonstrates how to create a Kubernetes Deployment and then emit a custom event associated with it. It uses the `newEvent()` method on an existing resource to set event details like message, reason, and type, finally emitting or updating the event. ```PHP use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('mysql') ->setImage('mysql', '5.7') ->setPorts([ ['name' => 'mysql', 'protocol' => 'TCP', 'containerPort' => 3306] ]); $pod = K8s::pod() ->setName('mysql') ->setLabels(['tier' => 'backend']) ->setContainers([$container]); $dep = $this->cluster ->deployment() ->setName('mysql') ->setSelectors(['matchLabels' => ['tier' => 'backend']]) ->setReplicas(1) ->setTemplate($pod) ->create(); $dep->newEvent() ->setMessage('The deployment failed for some reason...') ->setReason('HardwareFailure') ->setType('Warning') ->emitOrUpdate(); ``` -------------------------------- ### Shorthand Scaling of StatefulSet Replicas in PHP Source: https://php-k8s.renoki.org/resources/workloads/statefulset Demonstrates a shorthand method to scale a StatefulSet directly using the `->scale()` method. This method updates the replica count and can be followed by retrieving the updated list of pods. ```PHP $scaler = $sts->scale(3); $pods = $sts->getPods(); // Expecting 3 pods ``` -------------------------------- ### PHP K8s: Retrieve All Resources from All Namespaces Source: https://php-k8s.renoki.org/interacting-with-the-cluster/crud-operations Shows how to fetch all resources of a specific type (e.g., pods) across all Kubernetes namespaces using the `allNamespaces()` method or the dedicated `getAll[Resource]FromAllNamespaces()` helper method. ```php $allPods = $cluster->pod()->allNamespaces(); // Or you can use the specific method: $allPods = $cluster->getAllPodsFromAllNamespaces(); ``` -------------------------------- ### Retrieve Specific Pod Container by Name (PHP) Source: https://php-k8s.renoki.org/resources/workloads/pod Shows how to retrieve a specific regular container or init container by its name using `getContainer()` and `getInitContainer()` methods, allowing direct access to its properties. ```PHP $mysql = $pod->getContainer('mysql'); $busybox = $pod->getInitContainer('busybox'); // $mysql->getName(); // $busybox->getName(); ``` -------------------------------- ### Create Kubernetes Job with PHP K8s Source: https://php-k8s.renoki.org/resources/workloads/job Demonstrates how to define a container, a pod, and then create a Kubernetes Job using the RenokiCo\PhpK8s library. The pod is configured to restart on failure. ```php use RenokiCo\PhpK8s\K8s; $container = K8s::container() ->setName('pi') ->setImage('perl') ->setCommand(['perl', '-Mbignum=bpi', '-wle', 'print bpi(2000)']); $pod = K8s::pod() ->setName('pi') ->setLabels(['job-name' => 'pi']) // needs job-name: pi so that ->getPods() can work ->setContainers([$container]) ->restartOnFailure(); $job = $this->cluster ->job() ->setName('pi') ->setSelectors(['matchLabels' => ['tier' => 'backend']]) ->setTemplate($pod) ->create(); ```