### Install Development Tools (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Installs necessary development tools for the project. This is a one-time setup command. ```bash task install:tools ``` -------------------------------- ### Complete Kubeasy Challenge Workflow Example (Go) Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Provides a comprehensive example of the complete challenge workflow using Kubeasy CLI. This includes starting a challenge, creating a namespace, deploying resources, running validations, and submitting results via the API. It integrates multiple components like API client, deployer, kube utils, and validation executor. ```Go package main import ( "context" "fmt" "log" "github.com/kubeasy-dev/kubeasy-cli/internal/api" "github.com/kubeasy-dev/kubeasy-cli/internal/deployer" "github.com/kubeasy-dev/kubeasy-cli/internal/kube" "github.com/kubeasy-dev/kubeasy-cli/internal/validation" ) func main() { ctx := context.Background() slug := "basic-pod" // 1. Create API client apiClient, err := api.NewAuthenticatedClient() if err != nil { log.Fatal("Auth failed:", err) } // 2. Get Kubernetes clients clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() restConfig, _ := kube.GetRestConfig() // 3. Start challenge on backend _, err = apiClient.StartChallengeWithResponse(ctx, slug) if err != nil { log.Fatal("Failed to start:", err) } // 4. Create namespace kube.CreateNamespace(ctx, clientset, slug) // 5. Deploy challenge resources err = deployer.DeployChallenge(ctx, clientset, dynamicClient, slug) if err != nil { log.Fatal("Deploy failed:", err) } fmt.Println("Challenge deployed! Work on your solution...") fmt.Println("kubectl apply -f solution.yaml") // 6. After user applies solution, run validations config, _ := validation.LoadForChallenge(slug) executor := validation.NewExecutor(clientset, dynamicClient, restConfig, slug) results := executor.ExecuteAll(ctx, config.Validations) // 7. Collect and submit results var apiResults []api.ValidationResult allPassed := true for _, r := range results { apiResults = append(apiResults, api.ValidationResult{ Key: r.Key, Passed: r.Passed, }) if !r.Passed { allPassed = false } fmt.Printf("[%v] %s: %s\n", r.Passed, r.Key, r.Message) } // 8. Submit to API submitResp, _ := apiClient.SubmitChallenge(ctx, slug, api.ChallengeSubmitRequest{ Results: apiResults, }) if allPassed && submitResp.XpAwarded != nil { fmt.Printf("Success! +%d XP\n", *submitResp.XpAwarded) } } ``` -------------------------------- ### Troubleshoot EnvTest Setup Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/test/README.md Commands to manually install the setup-envtest tool and clear the Go test cache. ```bash go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest export PATH=$PATH:$(go env GOPATH)/bin go clean -testcache ``` -------------------------------- ### Development Tool Installation Commands Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Lists Taskfile commands for installing necessary development tools, such as linters and environment test setups. ```bash # Install all development tools task install:tools # Install specific tools task install:lint # golangci-lint task install:envtest # setup-envtest for integration tests ``` -------------------------------- ### Complete Challenge Workflow Example Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt A comprehensive example demonstrating the end-to-end workflow of starting, deploying, validating, and submitting a challenge using the Kubeasy CLI. ```APIDOC ## Complete Challenge Workflow Example ### Description This example illustrates the full lifecycle of interacting with a challenge, from API authentication and setup to deployment, validation, and final submission. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example N/A (Code Example) ### Response N/A (Code Example) ### Code Example (Go) ```go package main import ( "context" "fmt" "log" "github.com/kubeasy-dev/kubeasy-cli/internal/api" "github.com/kubeasy-dev/kubeasy-cli/internal/deployer" "github.com/kubeasy-dev/kubeasy-cli/internal/kube" "github.com/kubeasy-dev/kubeasy-cli/internal/validation" ) func main() { ctx := context.Background() slug := "basic-pod" // 1. Create API client apiClient, err := api.NewAuthenticatedClient() if err != nil { log.Fatal("Auth failed:", err) } // 2. Get Kubernetes clients clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() restConfig, _ := kube.GetRestConfig() // 3. Start challenge on backend _, err = apiClient.StartChallengeWithResponse(ctx, slug) if err != nil { log.Fatal("Failed to start:", err) } // 4. Create namespace kube.CreateNamespace(ctx, clientset, slug) // 5. Deploy challenge resources err = deployer.DeployChallenge(ctx, clientset, dynamicClient, slug) if err != nil { log.Fatal("Deploy failed:", err) } fmt.Println("Challenge deployed! Work on your solution...") fmt.Println("kubectl apply -f solution.yaml") // 6. After user applies solution, run validations config, _ := validation.LoadForChallenge(slug) executor := validation.NewExecutor(clientset, dynamicClient, restConfig, slug) results := executor.ExecuteAll(ctx, config.Validations) // 7. Collect and submit results var apiResults []api.ValidationResult allPassed := true for _, r := range results { apiResults = append(apiResults, api.ValidationResult{ Key: r.Key, Passed: r.Passed, }) if !r.Passed { allPassed = false } fmt.Printf("[%v] %s: %s\n", r.Passed, r.Key, r.Message) } // 8. Submit to API submitResp, _ := apiClient.SubmitChallenge(ctx, slug, api.ChallengeSubmitRequest{ Results: apiResults, }) if allPassed && submitResp.XpAwarded != nil { fmt.Printf("Success! +%d XP\n", *submitResp.XpAwarded) } } ``` ``` -------------------------------- ### Set Up Infrastructure Components with Kubeasy Deployer (Go) Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Shows how to use the Kubeasy Deployer to set up all necessary infrastructure components for challenges. This function installs components like Kyverno, Local Path Provisioner, NGINX Ingress, and others. It requires Kubernetes clients. ```Go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/deployer" ) ctx := context.Background() clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() // Install all infrastructure components results := deployer.SetupAllComponents(ctx, clientset, dynamicClient) for _, r := range results { fmt.Printf("[%s] %s: %s\n", r.Status, r.Name, r.Message) } // Output: // [Ready] Kyverno: Policy engine installed // [Ready] Local Path Provisioner: Storage class configured // [Ready] NGINX Ingress: Ingress controller running // [Ready] Gateway API CRDs: Gateway API installed // [Ready] cert-manager: Certificate manager running // [Ready] cloud-provider-kind: LoadBalancer support enabled ``` -------------------------------- ### Test NPM Package Installation Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md Builds the project and tests the NPM package locally to ensure the CLI is installable and functional. ```bash task build npm pack npm install -g kubeasy-dev-kubeasy-cli-*.tgz kubeasy version ``` -------------------------------- ### Install EnvTest and Development Tools Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/test/README.md Commands to install the necessary Kubernetes control plane binaries and development tools required for running integration tests. ```bash task install:tools task setup:envtest ``` -------------------------------- ### Deployer Usage Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Provides examples for deploying and cleaning up challenge resources, as well as setting up infrastructure components. ```APIDOC ## Deployer Usage ### Description This section covers the usage of the deployer for managing challenge resources and infrastructure setup. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example N/A (Code Example) ### Response N/A (Code Example) ### Code Example (Go) - Challenge Deployment ```go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/deployer" "github.com/kubeasy-dev/kubeasy-cli/internal/kube" ) ctx := context.Background() clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() // Deploy challenge from OCI registry // Pulls from ghcr.io/kubeasy-dev/challenges/basic-pod:latest err := deployer.DeployChallenge(ctx, clientset, dynamicClient, "basic-pod") // Cleanup challenge resources err = deployer.CleanupChallenge(ctx, clientset, "basic-pod") ``` ### Code Example (Go) - Infrastructure Setup ```go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/deployer" ) ctx := context.Background() clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() // Install all infrastructure components results := deployer.SetupAllComponents(ctx, clientset, dynamicClient) for _, r := range results { fmt.Printf("[%s] %s: %s\n", r.Status, r.Name, r.Message) } // Output: // [Ready] Kyverno: Policy engine installed // [Ready] Local Path Provisioner: Storage class configured // [Ready] NGINX Ingress: Ingress controller running // [Ready] Gateway API CRDs: Gateway API installed // [Ready] cert-manager: Certificate manager running // [Ready] cloud-provider-kind: LoadBalancer support enabled ``` ``` -------------------------------- ### Implement Integration Test with EnvTest Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/test/README.md Example of an integration test using the helpers package to set up an isolated Kubernetes environment and validate a resource. ```go // +build integration package integration import ( "testing" "github.com/kubeasy-dev/kubeasy-cli/test/helpers" ) func TestMyValidation(t *testing.T) { env := helpers.SetupEnvTest(t) pod := env.CreatePod(&corev1.Pod{...}) env.SetPodReady(pod.Name) executor := validation.NewExecutor(env.Clientset, env.DynamicClient, env.Config, env.Namespace) result := executor.Execute(ctx, validation) assert.True(t, result.Passed) } ``` -------------------------------- ### Install Kubeasy CLI via Package Managers and Shell Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/README.md Installation commands for Kubeasy CLI on macOS using Homebrew, Windows using Scoop, global installation via NPM, and a universal shell script for Unix-like systems. ```bash brew install kubeasy-dev/homebrew-tap/kubeasy ``` ```powershell scoop bucket add kubeasy https://github.com/kubeasy-dev/scoop-bucket scoop install kubeasy ``` ```bash npm install -g @kubeasy-dev/kubeasy-cli ``` ```bash curl -fsSL https://download.kubeasy.dev/install.sh | sh ``` -------------------------------- ### Go API Client: Challenge Operations Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Provides examples of common challenge operations using the Kubeasy API client in Go, including fetching details, checking status, starting, submitting results, and resetting challenges. ```go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/api" ) ctx := context.Background() client, _ := api.NewAuthenticatedClient() // Get challenge details challenge, err := client.GetChallengeBySlug(ctx, "basic-pod") // challenge.Title, challenge.Description, challenge.Difficulty, challenge.Theme // Check progress status status, err := client.GetChallengeStatus(ctx, "basic-pod") // status.Status: "not_started" | "in_progress" | "completed" // Start a challenge response, err := client.StartChallengeWithResponse(ctx, "basic-pod") // response.Success, response.Message // Submit validation results submitReq := api.ChallengeSubmitRequest{ Results: []api.ValidationResult{ {Key: "deployment-ready", Passed: true}, {Key: "service-reachable", Passed: true}, }, } result, err := client.SubmitChallenge(ctx, "basic-pod", submitReq) // result.XpAwarded, result.TotalXp, result.RankUp // Reset challenge progress resetResp, err := client.ResetChallenge(ctx, "basic-pod") ``` -------------------------------- ### Condition Validation Examples for Kubeasy Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Provides examples of using the 'condition' validation type in Kubeasy, which offers a shorthand syntax for checking common Kubernetes conditions like Ready and Available. ```yaml # Condition validation - pod readiness - key: pod-ready type: condition spec: target: kind: Pod labelSelector: app: nginx checks: - type: Ready status: "True" - type: ContainersReady status: "True" # Condition validation - deployment conditions - key: deployment-available type: condition spec: target: kind: Deployment name: nginx checks: - type: Available status: "True" - type: Progressing status: "True" ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md Examples of commit messages following the Conventional Commits specification, used for automated release note generation. ```text feat: add new command fix: resolve authentication issue docs: update installation guide chore: update dependencies ``` -------------------------------- ### Status Validation Example for Kubeasy Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Demonstrates how to use the 'status' validation type in Kubeasy to check arbitrary resource status fields. It supports nested field paths and array indexing. ```yaml # Status validation - check deployment replicas - key: deployment-scaled type: status spec: target: kind: Deployment name: nginx checks: - field: readyReplicas operator: ">=" value: 3 - field: availableReplicas operator: "==" value: 3 - field: conditions[type=Available].status operator: "==" value: "True" # Status validation - check pod container status - key: container-running type: status spec: target: kind: Pod labelSelector: app: nginx checks: - field: containerStatuses[0].ready operator: "==" value: true - field: containerStatuses[0].restartCount operator: "<" value: 3 ``` -------------------------------- ### Log Validation Example for Kubeasy Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Illustrates the 'log' validation type in Kubeasy, which is used to search container logs for specific strings within a defined time window. ```yaml # Log validation - search for specific string in logs - key: pod-logs-contain-string type: log spec: target: kind: Pod name: my-app-pod matchString: "Error: Connection timed out" window: "5m" ``` -------------------------------- ### Define Complete Microservices Challenge Validation Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md A comprehensive example of a challenge.yaml file, incorporating multiple validation types including resource limits, replica scaling, pod readiness, log verification, and connectivity checks. ```yaml title: Microservices Deployment description: | Deploy and configure a microservices application with proper resource limits, scaling, and network connectivity. theme: microservices difficulty: medium estimated_time: 30 objectives: - key: no-oom-kills title: "No Memory Issues" description: "Pods must not be killed due to out of memory" order: 1 type: event spec: target: kind: Pod labelSelector: tier: backend forbiddenReasons: - OOMKilled - Evicted sinceSeconds: 300 - key: backend-scaled title: "Backend Scaled" description: "Backend must have 3 ready replicas" order: 2 type: status spec: target: kind: Deployment name: backend checks: - field: readyReplicas operator: "==" value: 3 - field: availableReplicas operator: ">=" value: 3 - key: all-pods-ready title: "All Pods Ready" description: "Frontend, backend, and database pods must be ready" order: 3 type: condition spec: target: kind: Pod labelSelector: app: microservices checks: - type: Ready status: "True" - key: app-started title: "Application Started" description: "Backend must log successful startup" order: 4 type: log spec: target: kind: Pod labelSelector: tier: backend expectedStrings: - "Server listening on port 8080" - "Database connection established" sinceSeconds: 300 - key: db-connection title: "Database Reachable" description: "Backend can connect to database" order: 5 type: connectivity spec: sourcePod: labelSelector: tier: backend targets: - url: http://database-service:5432 expectedStatusCode: 200 timeoutSeconds: 5 - key: frontend-backend title: "Frontend to Backend" description: "Frontend can reach backend API" order: 6 type: connectivity spec: sourcePod: labelSelector: tier: frontend targets: - url: http://backend-service:8080/api/health expectedStatusCode: 200 - key: no-crashes title: "No Crash Loops" description: "No pods should be in crash loop" order: 7 type: event spec: target: kind: Pod labelSelector: app: microservices forbiddenReasons: - BackOff - CrashLoopBackOff sinceSeconds: 600 ``` -------------------------------- ### Execute Validations with Kubeasy Executor (Go) Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Demonstrates how to initialize an Executor to run validations for a given challenge. It shows loading validation configurations and executing them in parallel or sequentially. Dependencies include Kubernetes clients and validation configurations. ```Go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/validation" "github.com/kubeasy-dev/kubeasy-cli/internal/kube" ) // Get Kubernetes clients clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() restConfig, _ := kube.GetRestConfig() // Create executor for a namespace executor := validation.NewExecutor(clientset, dynamicClient, restConfig, "my-challenge") // Load validations from challenge config config, _ := validation.LoadForChallenge("basic-pod") // Execute all validations in parallel ctx := context.Background() results := executor.ExecuteAll(ctx, config.Validations) for _, result := range results { fmt.Printf("[%s] %s: %s (took %v)\n", map[bool]string{true: "PASS", false: "FAIL"}[result.Passed], result.Key, result.Message, result.Duration, ) } // Execute sequentially with fail-fast results = executor.ExecuteSequential(ctx, config.Validations, true) ``` -------------------------------- ### Infrastructure Deployment using Kubeasy CLI Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md This section details how Kubeasy CLI manages infrastructure deployment, including Kyverno and local-path-provisioner, by applying official manifests. It also explains how challenges are distributed as OCI artifacts and pulled using `oras-go`. ```go package kube import ( "context" "io/ioutil" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) func ApplyManifest(ctx context.Context, clientset *kubernetes.Clientset, manifestPath string) error { manifestBytes, err := ioutil.ReadFile(manifestPath) if err != nil { return err } // Logic to apply the Kubernetes manifest using the clientset // Example: dynamic client or specific resource clients return nil } func PullOCIArtifact(image string, destinationPath string) error { // Implementation using oras-go to pull OCI artifacts return nil } ``` -------------------------------- ### Deploy and Cleanup Challenge Resources with Kubeasy Deployer (Go) Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Illustrates the usage of the Kubeasy Deployer to manage challenge resources. This includes deploying a challenge from an OCI registry and cleaning up its associated resources. It requires Kubernetes client configurations. ```Go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/deployer" "github.com/kubeasy-dev/kubeasy-cli/internal/kube" ) ctx := context.Background() clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() // Deploy challenge from OCI registry // Pulls from ghcr.io/kubeasy-dev/challenges/basic-pod:latest err := deployer.DeployChallenge(ctx, clientset, dynamicClient, "basic-pod") // Cleanup challenge resources err = deployer.CleanupChallenge(ctx, clientset, "basic-pod") ``` -------------------------------- ### Go API Client: Authentication and Creation Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Demonstrates how to create authenticated and public clients for the Kubeasy API using Go. The authenticated client uses stored credentials or environment variables. ```go import "github.com/kubeasy-dev/kubeasy-cli/internal/api" // Create authenticated client (uses keystore or KUBEASY_API_KEY env var) client, err := api.NewAuthenticatedClient() if err != nil { log.Fatal("Failed to create client:", err) } // Create public client for unauthenticated endpoints publicClient := api.NewPublicClient() ``` -------------------------------- ### Perform Complex Status Validation Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md A comprehensive example combining multiple field checks including nested objects, array filtering, and boolean comparisons. ```yaml validations: - key: complex-check title: "Complex Status Check" type: status spec: target: kind: Pod name: my-pod checks: - field: containerStatuses[0].ready operator: "==" value: true - field: conditions[type=Ready].status operator: "==" value: "True" - field: containerStatuses[0].restartCount operator: "==" value: 0 - field: phase operator: "==" value: "Running" ``` -------------------------------- ### Configure External Connectivity Validation Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md Validates that pods can reach external services over the internet. This requires the target pods to have network utilities like curl or wget installed. ```yaml validations: - key: internet-access title: "Internet Access" description: "Pod can reach external services" order: 1 type: connectivity spec: sourcePod: labelSelector: app: worker targets: - url: https://api.github.com expectedStatusCode: 200 ``` -------------------------------- ### Run Linters and Build Checks (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md This snippet demonstrates manual execution of pre-release checks, including running tests with the race detector, executing linters with a specific configuration, and performing a build. It's useful for local validation before initiating an automated release. ```bash git checkout main git pull origin main go test -v -race ./... golangci-lint run --config .github/linters/.golangci.yml go build . ``` -------------------------------- ### Local Development and Execution Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Explains how to build and run the kubeasy-cli locally, including options for direct execution and enabling debug logging. ```bash # Build and run task dev # Or run directly go run main.go [command] # With debug logging go run main.go --debug [command] ``` -------------------------------- ### Access Nested and Array Fields in Status Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md Examples of using dot notation for nested fields, bracket notation for array indices, and field filtering for Kubernetes status objects. ```yaml checks: # Nested field - field: loadBalancer.ingress[0].hostname operator: "!=" value: "" # Array index - field: containerStatuses[0].restartCount operator: "<" value: 5 # Array filtering - field: conditions[type=Ready].status operator: "==" value: "True" ``` -------------------------------- ### Conditional Postinstall Script for npm Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md A package.json script configuration that allows skipping the postinstall binary download process in CI environments by checking an environment variable. ```json { "scripts": { "postinstall": "node -e \"if (process.env.SKIP_POSTINSTALL !== 'true') require('golang-npm/bin/index.js')\"" } } ``` -------------------------------- ### Version Bumping and Tagging (NPM/Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md This code demonstrates how to perform a version bump using npm and then push the changes along with tags to the Git repository. This is a key step in the manual release process to prepare for a new release. ```bash npm version patch # or minor/major git push --follow-tags ``` -------------------------------- ### Test Release Build Locally Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md Uses GoReleaser to perform a snapshot build, allowing developers to verify artifacts without triggering a full release. ```bash brew install goreleaser goreleaser release --snapshot --clean ls -lh dist/ ``` -------------------------------- ### Build Commands for Kubeasy CLI Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Provides commands for building the kubeasy-cli binary using Taskfile. Supports building a single binary or for all platforms. ```bash # Build the binary task build # Build for all platforms task build:all ``` -------------------------------- ### Scaffold New Challenge with Kubeasy CLI Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Creates a new challenge directory structure with template files for manifests, policies, and validation configuration. This command initializes a new challenge project. ```bash kubeasy dev create my-new-challenge # Created: my-new-challenge/ # Created: my-new-challenge/challenge.yaml # Created: my-new-challenge/manifests/ # Created: my-new-challenge/policies/ ``` -------------------------------- ### Run Local Tests and Linting Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md Executes the Go test suite and runs the golangci-lint tool to ensure code quality and correctness before committing changes. ```bash go test -v ./... golangci-lint run --config .github/linters/.golangci.yml ``` -------------------------------- ### Standardized Build Commands with Taskfile Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md A comprehensive Taskfile configuration providing standardized commands for building, testing, and linting the kubeasy-cli project. It includes targets for cross-platform builds, unit/integration testing, and dependency management. ```yaml task: # Display all available commands task build: # Build binary for current platform task build:all: # Build for all platforms (Linux, macOS, Windows) task test: # Run all tests (unit + integration) task test:unit: # Run unit tests only task test:integration: # Run integration tests task test:coverage: # Generate combined coverage report task lint: # Run golangci-lint task lint:fix: # Auto-fix linting issues task fmt: # Format Go code task deps: # Download and tidy dependencies task vendor: # Generate vendor directory task clean: # Clean build artifacts task dev: # Build and run in development mode task install:tools: # Install all development tools ``` -------------------------------- ### Define Target Using Label Selectors Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md Demonstrates the preferred method of using label selectors over specific names for more flexible resource targeting. ```yaml target: kind: Pod labelSelector: app: my-app ``` -------------------------------- ### Test Challenge Locally with Kubeasy CLI Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Applies manifests and runs validations in a single command for rapid iteration during challenge development. This is equivalent to running 'kubeasy dev apply' followed by 'kubeasy dev validate'. ```bash # Apply and validate in one step kubeasy dev test my-challenge # Equivalent to: # kubeasy dev apply my-challenge # kubeasy dev validate my-challenge ``` -------------------------------- ### Kubernetes Infrastructure Deployment Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Go code for deploying essential Kubernetes infrastructure like Kyverno and local-path-provisioner using HTTP manifests. Includes readiness checks. ```go // Installs Kyverno and local-path-provisioner via HTTP manifests func SetupInfrastructure() { // ... implementation ... } // Checks if all infrastructure deployments are running func IsInfrastructureReady() { // ... implementation ... } // Testable version with injected client for readiness checks func IsInfrastructureReadyWithClient(ctx context.Context, clientset kubernetes.Interface) { // ... implementation ... } ``` -------------------------------- ### Daily Development Workflow (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Executes common development tasks including building, testing, and linting the project. This command is used for daily development activities. ```bash task build test lint ``` -------------------------------- ### Executor Usage Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Demonstrates how to create an executor, load validations, and execute them in parallel or sequentially. ```APIDOC ## Executor Usage ### Description This section shows how to initialize an executor for validating Kubernetes challenges and running validation checks. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example N/A (Code Example) ### Response N/A (Code Example) ### Code Example (Go) ```go import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/validation" "github.com/kubeasy-dev/kubeasy-cli/internal/kube" ) // Get Kubernetes clients clientset, _ := kube.GetKubernetesClient() dynamicClient, _ := kube.GetDynamicClient() restConfig, _ := kube.GetRestConfig() // Create executor for a namespace executor := validation.NewExecutor(clientset, dynamicClient, restConfig, "my-challenge") // Load validations from challenge config config, _ := validation.LoadForChallenge("basic-pod") // Execute all validations in parallel ctx := context.Background() results := executor.ExecuteAll(ctx, config.Validations) for _, result := range results { fmt.Printf("[%s] %s: %s (took %v)\n", map[bool]string{true: "PASS", false: "FAIL"}[result.Passed], result.Key, result.Message, result.Duration, ) } // Execute sequentially with fail-fast results = executor.ExecuteSequential(ctx, config.Validations, true) ``` ``` -------------------------------- ### Log Validation - Application Startup Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Validates application startup by checking for specific strings in container logs within a given time frame. It targets pods based on labels and can specify a container. ```yaml - key: app-started type: log spec: target: kind: Pod labelSelector: app: nginx container: nginx # Optional, defaults to first container expectedStrings: - "Server started" - "Ready to accept connections" - "Listening on port 80" sinceSeconds: 60 # Look back 60 seconds ``` -------------------------------- ### Dependency Management Commands Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Shows Taskfile commands for managing project dependencies, including downloading, tidying, and generating a vendor directory. ```bash # Download and tidy dependencies task deps # Generate vendor directory task vendor ``` -------------------------------- ### Linting and Formatting Commands Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Details Taskfile commands for linting the Go code using golangci-lint, including auto-fixing and code formatting. ```bash # Run golangci-lint task lint # Run with auto-fix task lint:fix # Format code task fmt ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Common command-line operations for developers to build, verify, and test the application using the standardized Taskfile. ```bash # Quick development workflow task build && ./bin/kubeasy version # Before committing task lint fmt # Run all tests task test ``` -------------------------------- ### Basic Challenge Configuration Structure (challenge.yaml) Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Defines the basic structure of a challenge.yaml file, which is used to configure validations for verifying learner solutions. It includes fields like key, title, description, order, type, and spec. ```yaml # challenge.yaml - Basic structure validations: - key: deployment-ready # Unique identifier title: "Deployment Ready" # Human-readable name description: "Ensure deployment has required replicas" # Hint for learners order: 1 # Display order type: status # Validation type spec: # Type-specific configuration target: kind: Deployment name: nginx checks: - field: readyReplicas operator: ">=" value: 3 ``` -------------------------------- ### Go API Client for Kubeasy Backend Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Illustrates Go code snippets for interacting with the kubeasy backend API, including authentication, fetching challenge data, and submitting results. It uses JWT tokens stored in the system keyring. ```go // Authenticates via JWT token from keyring func createSupabaseClient() { // ... implementation ... } // Retrieves user ID from JWT claims func getUserIDFromKeyring() { // ... implementation ... } // Fetches challenge metadata by slug func GetChallenge(slug string) { // ... implementation ... } // Checks user's progress for a challenge func GetChallengeProgress(slug string) { // ... implementation ... } // Creates a progress record for a challenge func StartChallenge(slug string) { // ... implementation ... } // Submits validation results for a challenge // Accepts []ObjectiveResult with key, passed flag, and message // Sends structured payload: {results: [{objectiveKey, passed, message}, ...]}} func SendSubmit(challengeSlug string, results []ObjectiveResult) { // ... implementation ... } // Fetches user profile information func GetProfile() { // ... implementation ... } ``` -------------------------------- ### Show Challenge State with Kubeasy CLI Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Displays the current challenge state, including information about pods, recent events, and resource status. This is helpful for debugging and monitoring. ```bash kubeasy dev status my-challenge # Namespace: my-challenge # # Pods: # nginx-7b94f5cd8-x2k4j Running 1/1 # redis-0 Running 1/1 # # Recent Events: # Pod/nginx-7b94f5cd8-x2k4j Scheduled Successfully assigned # Pod/nginx-7b94f5cd8-x2k4j Pulled Container image pulled ``` -------------------------------- ### Pre-commit Hooks Automation (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Runs formatting and linting checks automatically before committing code, managed by Husky. Ensures code quality and consistency. ```bash task fmt lint ``` -------------------------------- ### Rollback Linting Command (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Provides the command to run golangci-lint directly, allowing for linting checks if the automated CI process encounters issues. This is part of the rollback plan. ```bash golangci-lint ``` -------------------------------- ### Rollback Build Command (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Provides commands for reverting to direct Go builds or using Taskfile targets if issues arise with the new release process. This is part of the rollback plan. ```bash go build ``` -------------------------------- ### Test Commands for Kubeasy CLI Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Lists Taskfile commands for running various test suites in the kubeasy-cli project, including unit, integration, and coverage reports. ```bash # Run all tests (unit + integration) task test # Run unit tests only task test:unit # Run integration tests only task test:integration # Generate coverage report task test:coverage ``` -------------------------------- ### Automate Migration with Sed Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md Provides shell commands to automatically update challenge.yaml files by replacing the type and stripping the status prefix. ```bash sed -i 's/type: metrics/type: status/g' challenge.yaml sed -i 's/field: status\./field: /g' challenge.yaml ``` -------------------------------- ### Configure Integration Test Build Tags Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/test/README.md Required build tag to ensure integration tests are only executed when explicitly requested. ```go // +build integration package integration ``` -------------------------------- ### Old Release Process (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md The previous method for releasing new versions, involving manual version bumping and tag pushing. This process is still functional but not recommended. ```bash npm version patch git push --follow-tags ``` -------------------------------- ### Execute Kubeasy CLI Tests Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/test/README.md Various commands to run the test suite, including unit tests, integration tests, and coverage report generation. ```bash task test task test:unit task test:integration go test -v ./... task test:coverage ``` -------------------------------- ### Pin GitHub Actions for Security Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/CICD.md Demonstrates the practice of pinning GitHub Actions to specific SHA hashes to prevent supply chain attacks. ```yaml uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 ``` -------------------------------- ### Kubernetes Resource Cleanup Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Go functions for cleaning up challenge-related resources in Kubernetes, including deleting namespaces and restoring the kubectl context. ```go // Cleans up challenge resources func CleanupChallenge(ctx context.Context, clientset kubernetes.Interface, slug string) { // Deletes namespace and restores kubectl context // ... implementation ... } ``` -------------------------------- ### Optimize GitHub Actions with Caching Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Configures caching for Go modules and npm dependencies in GitHub Actions to reduce build times. These snippets should be included in the workflow YAML files. ```yaml - name: Set up Go uses: actions/setup-go@v6 with: go-version: "1.25.4" cache: true ``` ```yaml - name: Setup Node.js uses: actions/setup-node@v6 with: cache: "npm" ``` -------------------------------- ### Rollback Release Commands (Bash) Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md Provides commands for reverting to the old release process using npm and git if issues arise with the new automated system. This is part of the rollback plan. ```bash npm version git push --follow-tags ``` -------------------------------- ### Migrate Metrics to Status Configuration Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md Demonstrates the transition from the deprecated metrics type to the status type by removing the status prefix from field paths. ```yaml type: status spec: target: kind: Deployment name: web-app checks: - field: readyReplicas operator: ">=" value: 3 - field: availableReplicas operator: "==" value: 3 ``` -------------------------------- ### Wait for R2 Binary Availability in CI Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/BUILD_IMPROVEMENTS.md A shell script implementation for GitHub Actions to poll a remote URL until the binary is available, ensuring the npm publish process does not fail due to missing assets. ```bash publish-npm: needs: [build] steps: - name: Wait for R2 binaries run: | VERSION="${GITHUB_REF#refs/tags/v}" BINARY_URL="https://download.kubeasy.dev/kubeasy-cli/v${VERSION}/kubeasy-cli_v${VERSION}_linux_amd64.tar.gz" for i in {1..60}; do HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$BINARY_URL") if [ "$HTTP_CODE" = "200" ]; then exit 0 fi sleep 5 done exit 1 ``` -------------------------------- ### Kubernetes Challenge Deployment Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md Go code responsible for deploying challenges to Kubernetes clusters by pulling OCI artifacts and applying manifests. It waits for the deployment to become ready. ```go // Deploys challenges via OCI artifacts from ghcr.io func DeployChallenge(ctx context.Context, clientset kubernetes.Interface, dynamicClient dynamic.Interface, slug string) { // Pulls OCI artifact, applies manifests, waits for ready // ... implementation ... } ``` -------------------------------- ### Adding a New Validation Type in Go Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/CLAUDE.md This outlines the necessary steps to integrate a new validation type into the Kubeasy CLI. It involves defining new types, updating the loader and executor logic, and creating dedicated executor packages and tests. The process ensures seamless integration with the existing validation framework and automatic schema generation. ```go package vtypes type XxxValidationType = "xxx" type XxxSpec struct { // ... fields for the new validation spec } type XxxCheck struct { // ... optional fields for the new validation check } var RegisteredTypes = map[string]any{ // ... other types TypeXxx: XxxSpec{}, // Add entry for the new type } ``` ```go package validation import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/validation/executors/xxx" "github.com/kubeasy-dev/kubeasy-cli/internal/validation/vtypes" "github.com/kubeasy-dev/kubeasy-cli/pkg/shared" ) func Execute(ctx context.Context, spec vtypes.ValidationSpec, deps shared.Deps) (bool, string, error) { switch spec.Type { // ... other cases case vtypes.TypeXxx: return xxx.Execute(ctx, spec.XxxSpec, deps) default: return false, "Unknown validation type", nil } } ``` ```go package xxx import ( "context" "github.com/kubeasy-dev/kubeasy-cli/internal/validation/vtypes" "github.com/kubeasy-dev/kubeasy-cli/pkg/shared" ) func Execute(ctx context.Context, spec vtypes.XxxSpec, deps shared.Deps) (bool, string, error) { // Implementation for the new validation type return true, "Validation successful", nil } ``` -------------------------------- ### Generate Shell Completions for Kubeasy CLI Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Generates shell completion scripts for various shells including bash, zsh, and fish. This helps in autocompleting Kubeasy CLI commands. ```bash kubeasy completion bash > /etc/bash_completion.d/kubeasy ``` ```bash kubeasy completion zsh > ~/.zsh/completion/_kubeasy ``` ```bash kubeasy completion fish > ~/.config/fish/completions/kubeasy.fish ``` -------------------------------- ### Run Challenge Validations Locally with Kubeasy CLI Source: https://context7.com/kubeasy-dev/kubeasy-cli/llms.txt Runs validations locally without submitting to the API. This command is useful for testing challenge configurations and checking the status of validations. ```bash kubeasy dev validate my-challenge # Running 5 validations... # [PASS] deployment-ready # [FAIL] service-reachable: Connection refused to nginx-service:80 # Results: 4/5 passed ``` -------------------------------- ### Validate Pod Readiness Condition Source: https://github.com/kubeasy-dev/kubeasy-cli/blob/main/docs/VALIDATION_EXAMPLES.md Checks if pods matching a label selector are in the Ready state. This is useful for ensuring application instances are available and healthy. ```yaml validations: - key: pod-ready title: "Pod Ready" description: "The application pod must be in Ready state" order: 1 type: condition spec: target: kind: Pod labelSelector: app: my-application checks: - type: Ready status: "True" ```