### Basic `includeWhen` Example Source: https://kro.run/docs/concepts/rgd/resource-definitions/conditional-creation A simple example demonstrating a single `includeWhen` condition for a resource. ```yaml - id: monitor includeWhen: - ${schema.spec.monitoring.enabled} ``` -------------------------------- ### Apply Raw Manifest for kro Installation Source: https://kro.run/docs/getting-started/Installation Installs kro using a raw manifest URL, specifying the version and variant. Ensure the namespace is created beforehand. ```bash kubectl create namespace kro-system kubectl apply -f https://github.com/kubernetes-sigs/kro/releases/download/v$KRO_VERSION/$KRO_VARIANT.yaml ``` -------------------------------- ### Basic Collection Example with `forEach` Source: https://kro.run/docs/concepts/rgd/resource-definitions/collections This example demonstrates how to use `forEach` to create multiple Pods from a single resource definition. When an instance is created with a list of workers, kro generates a Pod for each worker. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: worker-pool spec: schema: apiVersion: v1alpha1 kind: WorkerPool spec: workers: "[]string" image: string resources: - id: workerPods forEach: - worker: ${schema.spec.workers} template: apiVersion: v1 kind: Pod metadata: name: ${schema.metadata.name + '-' + worker} spec: containers: - name: app image: ${schema.spec.image} ``` -------------------------------- ### Example Topological Order Output Source: https://kro.run/docs/concepts/rgd/dependencies-ordering Shows an example of the JSONPath output for the topological order of resources. ```json status: topologicalOrder: - configmap - deployment - service ``` -------------------------------- ### kro Drift Detection Example Source: https://kro.run/docs/concepts/rgd/resource-definitions/collections This example demonstrates how kro detects and restores drifted resource fields. It shows the sequence of events from creation to manual modification and kro's automatic correction. ```bash # 1. kro creates ConfigMap with data.prefix: "original" # 2. Someone manually changes data.prefix to "MODIFIED" # 3. kro detects the drift and restores data.prefix to "original" ``` -------------------------------- ### Complete RGD Example with Schema and Resources Source: https://kro.run/docs/concepts/rgd/schema A comprehensive example demonstrating a Resource Graph Definition (RGD) including schema definition with basic and structured configurations, status fields, conditional fields, additional printer columns, and resource definitions. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: web-application spec: schema: apiVersion: v1alpha1 kind: WebApplication spec: # Basic configuration name: string | required=true replicas: integer | default=3 minimum=1 image: string | required=true # Structured configuration ingress: enabled: boolean | default=false host: string path: string | default="/" # Collections env: "map[string]string" ports: "[]integer | default=[80]" status: # Resource state availableReplicas: ${deployment.status.availableReplicas} serviceIP: ${service.spec.clusterIP} # Conditional fields (only present if ingress enabled) ingressHost: ${ingress.spec.rules[0].host} additionalPrinterColumns: - name: Replicas type: integer jsonPath: .spec.replicas - name: Available type: integer jsonPath: .status.availableReplicas - name: Image type: string jsonPath: .spec.image resources: - id: deployment template: apiVersion: apps/v1 kind: Deployment # ... deployment configuration using ${schema.spec.*} ... - id: service template: apiVersion: v1 kind: Service # ... service configuration ... - id: ingress includeWhen: - ${schema.spec.ingress.enabled} template: apiVersion: networking.k8s.io/v1 kind: Ingress # ... ingress configuration ... ``` -------------------------------- ### Install Specific kro Version with Helm Source: https://kro.run/docs/getting-started/Installation Install a specific version of kro for reproducible deployments by setting the KRO_VERSION environment variable. ```bash # Set the version you want to install export KRO_VERSION=0.9.1 # Install kro helm install kro oci://registry.k8s.io/kro/charts/kro \ --namespace kro-system \ --create-namespace \ --version=${KRO_VERSION} ``` -------------------------------- ### Install Latest Release Version of kro with Helm Source: https://kro.run/docs/getting-started/Installation Automatically install the latest release version of kro by fetching the tag name from the GitHub API and then using it with Helm. ```bash # Fetch latest release version export KRO_VERSION=$(curl -sL \ https://api.github.com/repos/kubernetes-sigs/kro/releases/latest | \ jq -r '.tag_name | ltrimstr("v")') # Verify version echo $KRO_VERSION # Install kro helm install kro oci://registry.k8s.io/kro/charts/kro \ --namespace kro-system \ --create-namespace \ --version=${KRO_VERSION} ``` -------------------------------- ### Example Schema with Various Field Types and Markers Source: https://kro.run/api/specifications/simple-schema A comprehensive example showcasing different data types and validation markers, including string, integer, float, and array types. ```yaml name: string | required=true default="app" description="Application name" id: string | required=true immutable=true description="Unique identifier" replicas: integer | default=3 minimum=1 maximum=10 price: float | minimum=0.01 maximum=999.99 mode: string | enum="debug,info,warn,error" default="info" email: string | pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" description="Valid email address" username: string | minLength=3 maxLength=20 pattern="^[a-zA-Z0-9_]+"" tags: '[]string | uniqueItems=true minItems=1 maxItems=10 description="1-10 unique tags"' ``` -------------------------------- ### Example RGD Status Output Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition This is an example of the output you should expect after successfully deploying and inspecting an RGD. It shows the RGD's name, API version, kind, state, readiness, topological order, and age. ```text NAME APIVERSION KIND STATE READY TOPOLOGICALORDER AGE my-application v1alpha1 Application Active True ["deployment","service","ingress"] 49 ``` -------------------------------- ### Validate ResourceGraphDefinition Installation Source: https://kro.run/examples/gcp/gke-cluster Verify that the RGD is installed correctly by getting its status. ```bash kubectl get rgd gkecluster.kro.run ``` -------------------------------- ### Get Deployed Resources Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition Inspect the Deployment, Service, and Ingress resources created by the Application instance. ```bash kubectl get deployments,services,ingresses ``` -------------------------------- ### Verify kro Pod is Running Source: https://kro.run/docs/getting-started/Installation Check the status of the kro pods to ensure they are running after installation. ```bash kubectl get pods -n kro-system ``` -------------------------------- ### Get Instance Ready Condition Source: https://kro.run/docs/concepts/instances Use this command to check the 'Ready' condition of an instance. This is the first step in debugging instance state. ```bash kubectl get -o jsonpath='{.status.conditions[?(@.type=="Ready")]}' ``` -------------------------------- ### Get Application Instances Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition Check the status of deployed Application instances. ```bash kubectl get applications ``` -------------------------------- ### Install Latest kro Version with Helm Source: https://kro.run/docs/getting-started/Installation Use this command to install the latest available version of kro on your Kubernetes cluster using Helm. ```bash helm install kro oci://registry.k8s.io/kro/charts/kro \ --namespace kro-system \ --create-namespace ``` -------------------------------- ### Resource Definition with References Source: https://kro.run/docs/concepts/rgd/resource-definitions/resource-basics This example shows how to define multiple resources and reference properties from the schema and other resources. Kro automatically determines dependencies based on these references. ```yaml spec: resources: - id: database template: apiVersion: database.example.com/v1 kind: PostgreSQL metadata: # Reference instance spec name: ${schema.spec.name}-db # Reference instance metadata namespace: ${schema.metadata.namespace} labels: ${schema.metadata.labels} spec: version: "15" storage: ${schema.spec.storageSize} replicas: 2 - id: deployment template: apiVersion: apps/v1 kind: Deployment metadata: name: ${schema.spec.name} namespace: ${schema.metadata.namespace} # Reference another resource's metadata annotations: ${database.metadata.annotations} spec: replicas: ${schema.spec.replicas} selector: matchLabels: app: ${schema.spec.name} template: spec: containers: - name: app image: ${schema.spec.image} env: # Reference another resource's status - name: DATABASE_HOST value: ${database.status.endpoint} # Reference another resource's spec - name: DATABASE_VERSION value: ${database.spec.version} ``` -------------------------------- ### Install ResourceGraphDefinition Source: https://kro.run/examples/gcp/gke-cluster Apply the RGD definition to your cluster using kubectl. ```bash kubectl apply -f rgd.yaml ``` -------------------------------- ### Type Checking Example Source: https://kro.run/docs/concepts/rgd/cel-expressions kro performs compile-time type checking. This example shows an RGD that would be rejected because the `appName` (string) is assigned to `replicas` (integer). ```yaml spec: replicas: ${schema.spec.appName} # Error: appName is string, replicas expects integer ``` -------------------------------- ### Collection Readiness with `each` Source: https://kro.run/docs/concepts/rgd/resource-definitions/readiness This example shows how to define readiness for items within a collection using the `each` keyword. It ensures each worker pod is in a 'Running' phase before the collection is considered ready. ```yaml # ✓ Valid for collections - uses each for per-item readiness - id: workerPods forEach: - worker: ${schema.spec.workers} readyWhen: - ${each.status.phase == 'Running'} template: kind: Pod metadata: name: ${schema.metadata.name + '-' + worker} ``` -------------------------------- ### Define Database and App Readiness Source: https://kro.run/docs/concepts/rgd/resource-definitions/readiness This example demonstrates how to define readiness for a database and then use its status to configure an application deployment. The application will only be created after the database is fully ready, including having an endpoint. ```yaml resources: - id: database template: apiVersion: database.example.com/v1 kind: PostgreSQL metadata: name: ${schema.spec.name}-db spec: version: "15" readyWhen: - ${database.status.conditions.exists(c, c.type == "Ready" && c.status == "True")} - ${database.status.?endpoint != ""} - id: app template: apiVersion: apps/v1 kind: Deployment metadata: name: ${schema.spec.name} spec: template: spec: containers: - name: app image: ${schema.spec.image} env: - name: DATABASE_HOST value: ${database.status.endpoint} ``` -------------------------------- ### Get Kro Instance Status Source: https://kro.run/docs/concepts/instances Use `kubectl get webapplication` to retrieve a high-level overview of your instance's status, including its readiness and age. ```bash $ kubectl get webapplication my-app NAME STATUS READY AGE my-app ACTIVE true 30s ``` -------------------------------- ### Validate RGD Installation Source: https://kro.run/examples/gcp/cloud-sql Verify that the CloudSQL RGD has been installed and is in an Active state. This command checks the status and age of the installed RGD. ```bash > kubectl get rgd cloudsql.kro.run NAME APIVERSION KIND STATE AGE cloudsql.kro.run v1alpha1 CloudSQL Active 44m ``` -------------------------------- ### Install ResourceGraphDefinition Source: https://kro.run/examples/gcp/cloud-sql Apply the RGD definition to the cluster using kubectl. Ensure the rgd.yaml file is in the current directory. ```bash kubectl apply -f rgd.yaml ``` -------------------------------- ### Simple Schema Example: Image String Source: https://kro.run/ Defines an 'image' field as a string with a default value of 'nginx' within a SimpleSchema. ```yaml image: string | default=nginx ``` -------------------------------- ### Resource Readiness Conditions Source: https://kro.run/docs/concepts/rgd/resource-definitions/readiness Examples of valid `readyWhen` expressions for a resource. These expressions must reference the resource itself and evaluate to a boolean. ```yaml # ✓ Valid - references the resource itself and returns boolean - id: deployment readyWhen: - ${deployment.status.availableReplicas > 0} - ${deployment.status.conditions.exists(c, c.type == "Available" && c.status == "True")} ``` -------------------------------- ### WebApplication RGD Example Source: https://kro.run/docs/building-abstractions/rgd-chaining Defines a WebApplication RGD that creates a Deployment, Service, and Ingress. It uses templating to configure the application image and database connection URL. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: web-application spec: schema: apiVersion: v1alpha1 kind: WebApplication spec: name: string image: string databaseUrl: string | default="" status: ready: ${deployment.status.availableReplicas == 2} endpoint: "https://${schema.spec.name}.example.com" resources: - id: deployment template: apiVersion: apps/v1 kind: Deployment metadata: name: ${schema.spec.name} spec: replicas: 2 selector: matchLabels: app: ${schema.spec.name} template: metadata: labels: app: ${schema.spec.name} spec: containers: - name: app image: ${schema.spec.image} env: - name: DATABASE_URL value: ${schema.spec.databaseUrl} ports: - containerPort: 8080 readyWhen: - ${deployment.status.availableReplicas == 2} - id: service template: apiVersion: v1 kind: Service metadata: name: ${schema.spec.name} spec: selector: app: ${schema.spec.name} ports: - port: 80 targetPort: 8080 - id: ingress template: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ${schema.spec.name} spec: rules: - host: ${schema.spec.name}.example.com http: paths: - path: / pathType: Prefix backend: service: ``` -------------------------------- ### Define a WebApp API with kro Source: https://kro.run/docs/overview This is an example of a user-defined API instance for a WebApp. It specifies the image and bucket name for the application. ```yaml apiVersion: kro.run/v1alpha1 kind: WebApp metadata: name: my-app spec: image: nginx bucketName: my-app-assets ``` -------------------------------- ### Reference a Shared ConfigMap in a Deployment Source: https://kro.run/docs/concepts/rgd/resource-definitions/external-references This example shows how an application Deployment references a shared ConfigMap for configuration. The Deployment will only be created after the ConfigMap exists and its data is accessible. ```yaml resources: - id: sharedConfig externalRef: apiVersion: v1 kind: ConfigMap metadata: name: platform-config namespace: platform-system - id: app template: apiVersion: apps/v1 kind: Deployment metadata: name: ${schema.spec.name} spec: template: spec: containers: - name: app image: ${schema.spec.image} env: - name: PLATFORM_URL value: ${sharedConfig.data.?platformUrl} - name: REGION value: ${sharedConfig.data.?region} ``` -------------------------------- ### Linear Chain Dependency Example Source: https://kro.run/docs/concepts/rgd/dependencies-ordering Illustrates a linear dependency where each resource depends on the previous one, suitable for sequential processing. ```yaml resources: - id: configmap template: apiVersion: v1 kind: ConfigMap data: key: ${schema.spec.value} - id: deployment template: apiVersion: apps/v1 kind: Deployment spec: template: spec: containers: - envFrom: - configMapRef: name: ${configmap.metadata.name} - id: service template: apiVersion: v1 kind: Service spec: selector: ${deployment.spec.selector.matchLabels} ``` -------------------------------- ### Database RGD Example Source: https://kro.run/docs/building-abstractions/rgd-chaining Defines a Database RGD that creates a StatefulSet, Secret, and Service. It exposes status fields like `ready` and `connectionString` for use by parent RGDs. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: database spec: schema: apiVersion: v1alpha1 kind: Database spec: size: string | default="small" status: ready: ${statefulset.status.readyReplicas == 1} connectionString: "postgresql://postgres@${service.metadata.name}:5432/postgres" resources: - id: secret template: apiVersion: v1 kind: Secret metadata: name: ${schema.metadata.name}-credentials stringData: password: changeme - id: statefulset template: apiVersion: apps/v1 kind: StatefulSet metadata: name: ${schema.metadata.name} spec: serviceName: ${schema.metadata.name} replicas: 1 selector: matchLabels: app: ${schema.metadata.name} template: metadata: labels: app: ${schema.metadata.name} spec: containers: - name: postgres image: postgres:15 env: - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: ${secret.metadata.name} key: password readyWhen: - ${statefulset.status.readyReplicas == 1} - id: service template: apiVersion: v1 kind: Service metadata: name: ${schema.metadata.name} spec: selector: app: ${schema.metadata.name} ports: - port: 5432 ``` -------------------------------- ### Exact Type Match Examples Source: https://kro.run/docs/concepts/rgd/cel-expressions Demonstrates correct and incorrect type assignments for integer fields. Ensure the expression result matches the target field's type. ```cel # ✓ Correct: integer to integer replicas: ${schema.spec.replicaCount} ``` ```cel # ✗ Wrong: string to integer replicas: ${schema.spec.appName} ``` -------------------------------- ### Get Specific GCSBucketWithFinalizerTrigger Details Source: https://kro.run/examples/gcp/eventarc Fetch the detailed YAML configuration and status for a specific GCSBucketWithFinalizerTrigger resource named 'gcsevent-test' in the 'config-connector' namespace. ```bash kubectl get gcsbucketwithfinalizertrigger gcsevent-test -n config-connector -o yaml ``` -------------------------------- ### Parallel Branches Dependency Example Source: https://kro.run/docs/concepts/rgd/dependencies-ordering Demonstrates parallel branches where resources have no interdependencies and can be created concurrently, ideal for independent components like microservices. ```yaml resources: - id: api template: apiVersion: apps/v1 kind: Deployment metadata: name: ${schema.spec.name}-api - id: worker template: apiVersion: apps/v1 kind: Deployment metadata: name: ${schema.spec.name}-worker - id: cron template: apiVersion: batch/v1 kind: CronJob metadata: name: ${schema.spec.name}-cron ``` -------------------------------- ### Conditionally Create Ingress Source: https://kro.run/docs/concepts/rgd/resource-definitions/conditional-creation This example shows how to conditionally create an Ingress resource based on a boolean flag in the instance spec. The Ingress is only created if `schema.spec.ingress.enabled` is true. ```yaml resources: - id: ingress includeWhen: - ${schema.spec.ingress.enabled} template: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ${schema.spec.name} # ... rest of ingress configuration ``` -------------------------------- ### FullStackApp RGD Example Source: https://kro.run/docs/building-abstractions/rgd-chaining Defines a parent RGD that composes Database and WebApplication RGDs. It uses templating to dynamically set resource names and pass status information between child RGDs. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: full-stack-app spec: schema: apiVersion: v1alpha1 kind: FullStackApp spec: name: string dbSize: string | default="small" status: databaseReady: ${database.status.ready} appEndpoint: ${webapp.status.endpoint} resources: # Use an instance of the Database RGD - id: database template: apiVersion: kro.run/v1alpha1 kind: Database metadata: name: ${schema.spec.name}-db spec: size: ${schema.spec.dbSize} readyWhen: - ${database.status.ready == true} # Use an instance of the WebApplication RGD - id: webapp template: apiVersion: kro.run/v1alpha1 kind: WebApplication metadata: name: ${schema.spec.name}-web spec: name: ${schema.spec.name} image: myapp:latest databaseUrl: ${database.status.connectionString} ``` -------------------------------- ### Struct Subset Semantics - Valid Example Source: https://kro.run/docs/concepts/rgd/cel-expressions Demonstrates a valid use of struct subset semantics where the expression result provides a subset of the expected fields for a container. ```cel # ✓ Valid: subset of expected fields containers: - ${{"name": "app", "image": schema.spec.image}} ``` -------------------------------- ### Working with Collections using CEL Source: https://kro.run/docs/concepts/rgd/resource-definitions/external-references Access and manipulate external resource collections using CEL. Examples include getting the count, extracting names, filtering, and checking for existence. ```yaml # Number of matching resources configCount: ${string(size(teamConfigs))} # Extract names names: ${teamConfigs.map(c, c.metadata.name).join(",")} # Filter by a data field critical: ${teamConfigs.filter(c, c.data.?priority == "critical")} # Check if any match a condition hasCritical: ${teamConfigs.exists(c, c.data.?priority == "critical")} ``` -------------------------------- ### Enforce Naming Conventions with RGD Source: https://kro.run/docs/building-abstractions/single-resource-rgd This RGD example demonstrates wrapping a ServiceAccount, enforcing naming conventions derived from the instance namespace and a 'team' label, and exposing the generated name in the status. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: teamserviceaccount.platform spec: schema: apiVersion: v1alpha1 kind: TeamServiceAccount spec: name: string status: generatedName: ${serviceAccount.metadata.name} resources: - id: serviceAccount template: apiVersion: v1 kind: ServiceAccount metadata: namespace: ${schema.metadata.namespace} name: ${schema.metadata.namespace + "-" + schema.metadata.?labels["team"].orValue("platform") + "-" + schema.spec.name + "-sa"} ``` -------------------------------- ### Get WebApp instance status with kubectl Source: https://kro.run/docs/overview After kro has reconciled the resources, this command retrieves the status of the WebApp instance, showing generated details like bucket ARN. ```bash $ kubectl get webapp my-app -o yaml status: bucketArn: arn:aws:s3:::my-app-assets ``` -------------------------------- ### Get All Graph Revisions Source: https://kro.run/docs/advanced/graph-revisions Use `kubectl get gr` or `kubectl get graphrevisions` to list all graph revisions. The `READY` column indicates compilation success (`True`), failure (`False`), or pending status (`Unknown`). ```bash kubectl get gr # or kubectl get graphrevisions ``` -------------------------------- ### Schema Validation Example Source: https://kro.run/docs/concepts/rgd/static-type-checking kro validates the SimpleSchema definition provided in spec.schema. This example shows a basic schema structure. ```yaml spec: schema: spec: # kro validates this schema definition replicas: integer | default=3 ports: array labels: object ``` -------------------------------- ### Apply Tenant Instance Source: https://kro.run/examples/kubernetes/saas-multi-tenant Apply the tenant instance configuration to create a specific tenant's resources. ```bash kubectl apply -f tenant-instance.yaml ``` -------------------------------- ### Diamond Dependency Pattern Example Source: https://kro.run/docs/concepts/rgd/dependencies-ordering Shows a diamond pattern where multiple independent resources converge into a single dependent resource, useful for applications requiring multiple backing services. ```yaml resources: - id: database template: apiVersion: databases.example.com/v1 kind: PostgreSQL spec: name: ${schema.spec.name}-db - id: cache template: apiVersion: caches.example.com/v1 kind: Redis spec: name: ${schema.spec.name}-cache - id: app template: apiVersion: apps/v1 kind: Deployment spec: template: spec: containers: - env: - name: DATABASE_URL value: ${database.status.endpoint} - name: CACHE_URL value: ${cache.status.endpoint} ``` -------------------------------- ### Create Application Instance YAML Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition Define an Application instance with specified name, replicas, and ingress settings. ```yaml apiVersion: kro.run/v1alpha1 kind: Application metadata: name: my-app-instance spec: name: my-app replicas: 1 ingress: enabled: true ``` -------------------------------- ### Manually Add Owner References to Resources Source: https://kro.run/docs/concepts/instances Example of how to manually set owner references in resource templates when needed for specific integrations. Use with caution as it may lead to unexpected behavior. ```yaml resources: - id: configmap template: apiVersion: v1 kind: ConfigMap metadata: name: ${schema.spec.name}-config ownerReferences: - apiVersion: ${schema.apiVersion} kind: ${schema.kind} name: ${schema.metadata.name} uid: ${schema.metadata.uid} controller: true blockOwnerDeletion: true ``` -------------------------------- ### Circular Dependency Example Source: https://kro.run/docs/concepts/rgd/dependencies-ordering This example demonstrates a circular dependency where serviceA depends on serviceB and serviceB depends on serviceA. This will cause a reconciliation failure. ```yaml resources: - id: serviceA template: spec: targetPort: ${serviceB.spec.port} # A → B - id: serviceB template: spec: targetPort: ${serviceA.spec.port} # B → A (circular!) ``` -------------------------------- ### Circular Dependency Detection Example Source: https://kro.run/docs/concepts/rgd/static-type-checking kro detects circular dependencies by identifying cycles in the resource DAG. This example shows a simple A -> B -> A cycle. ```yaml # ✗ This fails validation resources: - id: serviceA template: spec: port: ${serviceB.spec.targetPort} # A → B - id: serviceB template: spec: targetPort: ${serviceA.spec.port} # B → A (cycle!) ``` -------------------------------- ### Apply Application Instance with kubectl Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition Deploy the Application instance to your Kubernetes cluster using kubectl. ```bash kubectl apply -f instance.yaml ``` -------------------------------- ### Nested Field Type Checking Example Source: https://kro.run/docs/concepts/rgd/static-type-checking kro recursively checks type compatibility at any depth within nested structures. This example shows a type error in a deeply nested field. ```yaml spec: template: spec: containers: - env: - name: PORT # Expression returns: int # Field path: spec.template.spec.containers[].env[].value # Field expects: string # kro resolves the full nested path and checks compatibility value: ${schema.spec.port} # ✗ Type error: int → string ``` -------------------------------- ### Create a WebApplication Instance Source: https://kro.run/docs/concepts/instances Define an instance of the WebApplication custom resource. This specifies the application's name, image, and ingress configuration. ```yaml apiVersion: kro.run/v1alpha1 kind: WebApplication metadata: name: my-app spec: name: web-app image: nginx:latest ingress: enabled: true ``` -------------------------------- ### Describe Instance for Conditions and Events Source: https://kro.run/docs/concepts/instances Use `kubectl describe` to view all conditions and recent events for an instance. This provides a comprehensive overview of the instance's state and any issues. ```bash kubectl describe ``` -------------------------------- ### CEL Expression Type Checking Example Source: https://kro.run/docs/concepts/rgd/static-type-checking This example demonstrates the type checking process for a CEL expression, showing inferred and expected types, and the compatibility result. Ensure your CEL expressions are type-safe and compatible with the target schema fields. ```cel # Expression: ${schema.spec.replicas} # Inferred output type: integer (from schema.spec definition) # Expected type: integer (from Deployment.spec.replicas schema) # Result: ✓ Compatible ``` -------------------------------- ### Build pprof Debug Image Source: https://kro.run/docs/advanced/controller-tuning Use these Make targets when building or publishing the pprof-enabled image. Ensure GOFLAGS are set if using 'image.ko=true' or 'ko apply'. ```bash make build-debug-image RELEASE_VERSION=v0.9.1 ``` ```bash make publish-debug-image RELEASE_VERSION=v0.9.1 ``` -------------------------------- ### Invalid includeWhen Expression Source: https://kro.run/docs/concepts/rgd/resource-definitions/conditional-creation An example of an invalid `includeWhen` expression that does not return a boolean value. ```yaml # ✗ Invalid - must return boolean includeWhen: - ${schema.spec.appName} # returns string, not boolean ``` -------------------------------- ### Get KRO ResourceGraphDefinitions Source: https://kro.run/ Use kubectl to retrieve all ResourceGraphDefinition resources managed by KRO. ```bash kubectl get resourcegraphdefinitions ``` -------------------------------- ### Get GCSBucketWithFinalizerTrigger Status Source: https://kro.run/examples/gcp/eventarc Use kubectl to retrieve the status of all GCSBucketWithFinalizerTrigger resources in the 'config-connector' namespace. ```bash kubectl get gcsbucketwithfinalizertrigger -n config-connector ``` -------------------------------- ### Collection Readiness with 'each' Keyword Source: https://kro.run/docs/concepts/rgd/resource-definitions/collections Defines a collection 'workerPods' where readiness is determined by each item meeting a specific status condition. The collection is ready only when all items are 'Running'. ```yaml - id: workerPods forEach: - worker: ${schema.spec.workers} readyWhen: - ${each.status.phase == 'Running'} # Per-item check using `each` template: kind: Pod metadata: name: ${schema.metadata.name + '-' + worker} spec: containers: - name: app image: ${schema.spec.image} ``` -------------------------------- ### Get Topological Order Source: https://kro.run/docs/concepts/rgd/dependencies-ordering Retrieves the computed topological order of resources from the RGD status using kubectl. ```bash kubectl get rgd my-app -o jsonpath='{.status.topologicalOrder}' ``` -------------------------------- ### List kro-created resources with kubectl Source: https://kro.run/docs/overview This command lists the Kubernetes resources (ConfigMap, Bucket, Deployment, Service) that kro automatically created based on the WebApp definition. ```bash $ kubectl get configmap,bucket,deploy,svc NAME AGE configmap/my-app-config 45s NAME AGE bucket.s3.services.k8s.aws/my-app-assets 45s NAME READY AGE deployment.apps/my-app 1/1 45s NAME TYPE PORT(S) service/my-app ClusterIP 80/TCP ``` -------------------------------- ### Upgrade kro to Latest Version with Helm Source: https://kro.run/docs/getting-started/Installation Upgrade an existing kro Helm installation to the latest available version. ```bash helm upgrade kro oci://registry.k8s.io/kro/charts/kro \ --namespace kro-system ``` -------------------------------- ### Standalone Boolean Field Expression Source: https://kro.run/docs/concepts/rgd/cel-expressions Example of a standalone CEL expression for a boolean field. The result must be a boolean. ```yaml enabled: ${schema.spec.featureEnabled} ``` -------------------------------- ### Define a Web Application Resource Graph Source: https://kro.run/api/specifications/simple-schema This example demonstrates defining a namespaced WebApplication resource with various field types, including strings, integers, booleans, objects, arrays, and maps, along with custom types and status field references. ```yaml apiVersion: kro.run/v1alpha1 kind: ResourceGraphDefinition metadata: name: web-application spec: schema: apiVersion: v1alpha1 kind: WebApplication scope: Namespaced # or "Cluster" for cluster-scoped instances spec: # Basic types name: string | required=true immutable=true description="My Name" replicas: integer | default=1 minimum=1 maximum=100 image: string | required=true # Unstructured objects values: object | required=true # Structured type ingress: enabled: boolean | default=false host: string | default="example.com" path: string | default="/" # Array type ports: "[]integer" # Map type env: "map[string]myType" # Custom Types types: myType: value1: string | required=true value2: integer | default=42 status: # Status fields with auto-inferred types availableReplicas: ${deployment.status.availableReplicas} serviceEndpoint: ${service.status.loadBalancer.ingress[0].hostname} ``` -------------------------------- ### Valid includeWhen Expressions Source: https://kro.run/docs/concepts/rgd/resource-definitions/conditional-creation Examples of valid `includeWhen` expressions that reference `schema.spec` fields and return boolean values. ```yaml # ✓ Valid - references schema.spec and returns boolean includeWhen: - ${schema.spec.ingress.enabled} - ${schema.spec.environment == "production"} - ${schema.spec.replicas > 3} ``` ```yaml # ✓ Valid - references an upstream resource includeWhen: - ${deployment.status.availableReplicas > 0} ``` -------------------------------- ### Watch Deployment Scaling Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition Monitor the deployment as it scales up to the new replica count. ```bash kubectl get deployment my-app ``` -------------------------------- ### Referencing External Resources and Dependencies Source: https://kro.run/docs/concepts/rgd/resource-definitions/external-references Define an external resource and show how it creates a dependency chain with other resources. kro waits for external resources before creating dependent ones. ```yaml resources: - id: platformConfig externalRef: apiVersion: v1 kind: ConfigMap metadata: name: platform-config - id: database template: spec: region: ${platformConfig.data.?region} - id: app template: spec: env: - name: DB_ENDPOINT value: ${database.status.endpoint} ``` -------------------------------- ### Generate Integer Range with lists.range() Source: https://kro.run/docs/concepts/rgd/cel-libraries Create a list of integers starting from 0 up to (but not including) the specified number `n`. ```cel indices: ${lists.range(schema.spec.count)} ``` -------------------------------- ### Check Tenant Instance Status Source: https://kro.run/examples/kubernetes/saas-multi-tenant Verify the status and synchronization of the applied tenant instance. ```bash kubectl get tenant ``` -------------------------------- ### Defining Resource Dependencies with Collections Source: https://kro.run/docs/concepts/rgd/resource-definitions/collections Illustrates how collections establish dependencies. 'backupJobs' depends on 'databases', and 'summary' depends on 'backupJobs', ensuring sequential reconciliation. ```yaml resources: # Collection A: creates multiple databases - id: databases forEach: - dbSpec: ${schema.spec.databases} template: kind: Database metadata: name: ${schema.metadata.name + '-' + dbSpec.name} # ... # Collection B: depends on Collection A # kro waits for ALL databases to be ready before creating backup jobs - id: backupJobs forEach: - db: ${databases} template: kind: CronJob metadata: name: ${schema.metadata.name + '-backup-' + db.metadata.name} # ... # Resource C: depends on Collection B # kro waits for ALL backup jobs to be ready before creating the summary - id: summary template: kind: ConfigMap metadata: name: ${schema.metadata.name + '-summary'} data: backupCount: ${string(size(backupJobs))} ``` -------------------------------- ### Enable Feature Gates via Command-Line Flag Source: https://kro.run/docs/advanced/feature-gates Pass feature gates directly to the controller binary using the '--feature-gates' flag, separating multiple gates with commas. ```bash --feature-gates=CELOmitFunction=true,InstanceConditionEvents=true ``` -------------------------------- ### Get GraphRevision Topological Order Source: https://kro.run/docs/advanced/graph-revisions After a successful compilation, retrieve the resource creation order from the `status.topologicalOrder` field of a graph revision. ```bash kubectl get gr my-webapp-r00003 -o jsonpath='{.status.topologicalOrder}' ``` ```json ["config","bucket","deployment","service"] ``` -------------------------------- ### Apply Tenant Environment RGD Source: https://kro.run/examples/kubernetes/saas-multi-tenant Apply the tenant environment ResourceGraphDefinition to set up isolated namespaces with resource quotas and NetworkPolicy. ```bash kubectl apply -f tenant-environment-rgd.yaml ``` -------------------------------- ### Tolerant Version Parsing with CEL Source: https://kro.run/docs/concepts/rgd/cel-libraries Demonstrates tolerant parsing of version strings using CEL's `isSemver` and `semver` functions. Allows for formats like 'v1.0' and '01.02.03'. ```cel valid: ${isSemver(schema.spec.version, true)} parsed: ${semver(schema.spec.version, true).minor()} ``` -------------------------------- ### Example of Dimension Explosion Source: https://kro.run/docs/concepts/rgd/resource-definitions/collections Illustrates how multiplying dimensions can lead to a large number of resources. Keep iterator lists bounded to avoid this. ```text 3 regions × 5 tiers × 10 shards = 150 resources ``` -------------------------------- ### Resource Template Validation Source: https://kro.run/docs/concepts/rgd/static-type-checking kro validates resource templates against Kubernetes OpenAPI schemas. This example shows a basic Deployment template. ```yaml resources: - id: deployment template: apiVersion: apps/v1 # kro fetches Deployment schema kind: Deployment # ... validates template against Deployment schema ``` -------------------------------- ### String Template with Simple Concatenation Source: https://kro.run/docs/concepts/rgd/cel-expressions A string template example showing simple concatenation of a literal string and a CEL expression result. ```yaml name: "app-${schema.spec.name}" ``` -------------------------------- ### Fetch Latest Release Version and Set Variant Source: https://kro.run/docs/getting-started/Installation This snippet fetches the latest release version of kro from GitHub and sets the desired installation variant. It's a precursor to applying the raw manifest. ```bash export KRO_VERSION=$(curl -sL \ https://api.github.com/repos/kubernetes-sigs/kro/releases/latest | \ jq -r '.tag_name | ltrimstr("v")' ) export KRO_VARIANT=kro-core-install-manifests echo $KRO_VERSION ``` -------------------------------- ### Resource Naming Validation Source: https://kro.run/docs/concepts/rgd/static-type-checking Resource IDs must be valid CEL identifiers. Avoid hyphens, special characters, and starting with numbers. ```yaml # ✓ Valid IDs resources: - id: deployment - id: configMap - id: servicePrimary # ✗ Invalid IDs resources: - id: my-deployment # Hyphens not allowed (CEL subtraction operator) - id: 1st-service # Can't start with number ``` -------------------------------- ### Printf-style Formatting with String.format() Source: https://kro.run/docs/concepts/rgd/cel-libraries Use the `format()` function for printf-style string formatting, supporting placeholders like %s, %d, %f, %e, %b, %x, %X, and %o. Requires a list of arguments. ```cel roleArn: ${"arn:aws:iam::%s:role/%s".format([schema.spec.accountId, schema.spec.roleName])} ``` -------------------------------- ### Upgrade kro to Specific Version with Helm Source: https://kro.run/docs/getting-started/Installation Upgrade an existing kro Helm installation to a specific version by setting the KRO_VERSION environment variable. ```bash export KRO_VERSION=0.9.1 helm upgrade kro oci://registry.k8s.io/kro/charts/kro \ --namespace kro-system \ --version=${KRO_VERSION} ``` -------------------------------- ### Watch Service Recreation Source: https://kro.run/docs/getting-started/deploy-a-resource-graph-definition Observe kro automatically recreating the service after it has been deleted. ```bash kubectl get service my-app-svc -w ``` -------------------------------- ### String Template with Literal Text and Expressions Source: https://kro.run/docs/concepts/rgd/cel-expressions Example of a string template that combines literal text with multiple CEL expressions to form a message. ```yaml message: "Application ${schema.spec.name} is running version ${schema.spec.version}" ``` -------------------------------- ### Instance Spec for Conditional Ingress Source: https://kro.run/docs/concepts/rgd/resource-definitions/conditional-creation This is an example of an instance spec where the `ingress.enabled` field is set to true, which would result in the Ingress resource being created. ```yaml apiVersion: example.com/v1 kind: Application metadata: name: my-app spec: name: my-app ingress: enabled: true # Ingress will be created ```