Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install app-sdk-concepts@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin app-sdk-concepts v1.0.0 follows the Agent Plugins spec.
gh skills-hub install app-sdk-concepts Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/app-sdk-concepts/ Extract the ZIP to .github/skills/ in your repo. The folder name must match app-sdk-concepts for Copilot to auto-discover it.
Skill Files (7)
SKILL.md 4.3 KB
---
name: app-sdk-concepts
license: Apache-2.0
description: Use when starting any grafana-app-sdk work — scaffolding a Grafana app, initializing a Grafana App Platform app, picking a deployment mode (standalone operator / grafana/apps / frontend-only), wiring app-specific config, or onboarding to the SDK. Covers `grafana-app-sdk` CLI install, `project init` per deployment mode, project layout, the schema-centric workflow (CUE kinds → generated code → reconciler/admission logic), and `SpecificConfig` for env-driven app configuration. Use even if the user just says "make a new app", "Grafana app platform", "kinds and watchers", "operator scaffold", or asks about `apps/` inside the Grafana repo, without naming the SDK explicitly.
---
# Grafana App SDK Concepts
The grafana-app-sdk is a CLI + Go library for building schema-centric apps on the Grafana App Platform. Apps define resources via CUE schemas ("kinds"), generate Go + TypeScript code, and implement business logic via admission control and reconcilers.
## Prerequisites
```bash
go install github.com/grafana/grafana-app-sdk/cmd/grafana-app-sdk@latest
grafana-app-sdk version # verify
```
## Common Workflows
### Scaffold a standalone operator app
```bash
# 1. Init the project (use the Go module path)
grafana-app-sdk project init github.com/example/my-app
# 2. Add operator scaffolding — ASK THE USER FIRST.
# They may prefer to write app.App by hand.
grafana-app-sdk project component add operator
# 3. Verify scaffolded layout
ls pkg/app pkg/watchers cmd/operator
# Expected: app.go, watchers/<kind>.go, main.go
```
Common failure: forgetting `go install` updates the binary — verify with `grafana-app-sdk version` before init.
### Scaffold a grafana/apps-style app (inside `grafana/grafana`)
Only available inside the Grafana repo (or fork) — the init command detects `apps/` and `pkg/registry/apps/` at the repo root.
```bash
mkdir -p apps/my-app && cd apps/my-app
grafana-app-sdk project init github.com/grafana/grafana/apps/my-app
# Keep ONLY: kinds/ pkg/ go.mod go.sum — delete everything else.
cp apps/example/Makefile apps/my-app/Makefile
cp apps/example/kinds/config.cue apps/my-app/kinds/config.cue # overwrite
go work use ./apps/my-app
```
Then register the app inside Grafana (`pkg/registry/apps/apps.go` + `register.go`). Full walkthrough in [references/deployment-modes.md](references/deployment-modes.md#grafanaapps).
### End-to-end development loop
```
1. project init → module, Makefile, kinds/
2. project kind add MyKind → CUE kind scaffold
3. Edit kinds/*.cue → schemas, validation, versions
4. grafana-app-sdk generate → Go types, clients, TS types, AppManifest, CRDs
5. Implement logic → fill in reconciler / admission stubs
6. (optional) project component add frontend
```
Always rerun `generate` after every CUE change — generated code is the API your reconciler sees.
## Deployment modes (one-line table)
| Mode | When to pick | Where it runs |
|------|--------------|---------------|
| Standalone operator | Outside Grafana repo, want your own binary | Kubernetes operator with its own webhook server |
| grafana/apps | Inside `github.com/grafana/grafana` (or fork) | In-process inside Grafana's API server |
| Frontend-only | UI-only app, no Go logic needed | No backend — TS types only |
Full per-mode init, runtime, and wiring detail in [references/deployment-modes.md](references/deployment-modes.md).
## References
- [`references/deployment-modes.md`](references/deployment-modes.md) — per-mode init, runtime semantics, grafana/apps registration walkthrough
- [`references/project-structure.md`](references/project-structure.md) — standalone project layout, what's hand-edited vs generated
- [`references/cli-reference.md`](references/cli-reference.md) — every `grafana-app-sdk` subcommand with flags
- [`references/specific-config.md`](references/specific-config.md) — `app.Config.SpecificConfig` pattern for feature-flag-driven app config
- [`references/local-development.md`](references/local-development.md) — Tilt + k3d local dev loop
- [`references/local-config.md`](references/local-config.md) — `local/config.yaml` reference
## Resources
- [grafana-app-sdk repo](https://github.com/grafana/grafana-app-sdk)
- [App Platform docs](https://grafana.com/docs/grafana/latest/developers/plugins/app-platform/)
cli-reference.md 8.5 KB
# grafana-app-sdk CLI Reference
## Installation
```bash
# Latest version
go install github.com/grafana/grafana-app-sdk/cmd/grafana-app-sdk@latest
# Specific version
go install github.com/grafana/grafana-app-sdk/cmd/grafana-app-sdk@v0.x.y
# Verify
grafana-app-sdk version
```
## Project Commands
### `project init`
Initialize a new app project.
```bash
grafana-app-sdk project init <module-path>
```
**Arguments:**
- `<module-path>` — Go module path (required), e.g. `github.com/example/my-app`
**What it creates:**
- `kinds/` — empty kinds directory with an initialized `cue.mod`
- `pkg/` — Go package skeleton
- `go.mod` / `go.sum` — Go module files
- `Makefile` — build targets including `generate`
- `local/` — local development config
---
### `project kind add`
Add a new kind scaffold to the `kinds/` directory.
```bash
grafana-app-sdk project kind add <KindName> [flags]
```
**Arguments:**
- `<KindName>` — PascalCase kind name (required), e.g. `IssueTracker`
**Flags:**
| Flag | Description |
|------|-------------|
| `--overwrite` | Overwrite existing kind files (use when re-scaffolding) |
**What it creates:**
- `kinds/<kindname>.cue` — common kind metadata
- `kinds/<kindname>_<version>.cue` — <version> schema scaffold with comments
**Notes:**
- Always use `--overwrite` to regenerate when the scaffold changes in newer SDK versions
- The generated file is heavily commented — read the comments carefully
- It will always generate only a single version, the `preferredVersion` in `manifest.cue`. To add additional versions, see the `cue-kind-definition` skill
---
### `project component add`
Add a component scaffold to an existing project.
```bash
grafana-app-sdk project component add <component>
```
**Components:**
| Component | Description |
|-----------|-------------|
| `operator` | Adds operator (standalone binary) scaffolding: reconciler stubs, admission handler stubs, `cmd/operator/main.go` |
| `frontend` | Scaffolds a Grafana plugin frontend using `create-plugin` (requires `yarn`) |
**`operator` — what it creates:**
```
cmd/
└── operator/
└── main.go # operator entrypoint
pkg/
├── app/
│ └── app.go # app.App implementation stub with TODOs
└── watchers/
└── watcher_<kind>.go # <kind> watcher with stubbed methods
```
**`frontend` — what it creates:**
```
plugin/
├── src/
│ ├── module.ts
│ └── pages/
├── package.json
└── plugin.json
```
---
## Generate Command
### `generate`
Generate Go types, TypeScript types, AppManifest, and CRD files from CUE kind definitions.
```bash
grafana-app-sdk generate [flags]
```
**Flags:**
| Flag | Description |
|------|-------------|
| `--source` | Path to CUE definitions (default: `kinds/`) |
| `--config` | The CUE selector of the config object (see `CUE Config Object` section) |
**What it generates:**
| Output | Location | Controlled by |
|--------|----------|---------------|
| Go type structs | `pkg/generated/<group>/<version>/types_gen.go` | `codegen.go.enabled` |
| Go client | `pkg/generated/<group>/<version>/zz_generated_*.go` | `codegen.go.enabled` |
| TypeScript types | configured output dir | `codegen.ts.enabled` |
| AppManifest (Go) | `pkg/app/appmanifest_gen.go` | always |
| AppManifest (JSON) | `appmanifest.json` | always |
| CRD (JSON or YAML) | `config/crd/` | CUE config output setting |
**⚠ Generated files must not be edited manually** — they are overwritten on every generate run.
---
## YAML Bundle Command
### `generate yaml-bundle`
Generate a Kubernetes YAML bundle for deployment.
```bash
grafana-app-sdk generate yaml-bundle [flags]
```
Produces CRDs, webhook configurations, and RBAC manifests ready for `kubectl apply`.
---
## Local Development
### `local`
Commands for running the app locally with a mocked API server.
```bash
# Start the local development environment
grafana-app-sdk local/up
```
Starts a local Kubernetes-compatible API server for development without a full cluster.
---
## Common Makefile Targets
Projects generated by `project init` include a Makefile with these targets:
| Target | Description |
|--------|-------------|
| `make generate` | Run `grafana-app-sdk generate` |
| `make build` | Build the operator binary and/or frontend plugin |
| `make test` | Run tests |
| `make lint` | Run Go linter |
| `make deps` | Vendor in any missing go dependencies |
| `make local/up` | Create a local k3d development environment with Tilt |
| `make local/push_operator` | Pust the built operator image to the local development enviroment k3d cluster |
| `make local/deploy_plugin` | Deploy the latest built plugin to the local development environment's grafana |
| `make local/down` | Take down the Tilt-deployed resources |
| `make local/clean` | Delete the local development environment k3d cluster |
---
## CUE Config Object
Control generation behavior via a CUE config object in your kinds. This is typically in the top-level kinds file:
```cue
// Codegen output configuration
config: {
codegen: {
// goModule allows explicitly setting the module path.
// If empty the module path is read from go.mod
// Default: ""
goModule: ""
// goModGenPath anchors generated Go output relative to the module root, instead of execution directory
// Default: ""
goModGenPath: ""
// goGenPath sets the output directory for generated Go types.
// Default: "pkg/generated/"
goGenPath: "pkg/generated/"
// tsGenPath sets the output directory for generated TypeScript types
// Default: "plugin/src/generated/"
tsGenPath: "plugin/src/generated/"
// enableK8sPostProcessing runs the Kubernetes code generators after writing files.
// This option is unnecessary when using the k8s.apiserver's DefaultAppInstaller
// Default: false
enableK8sPostProcessing: false
// enableOperatorStatusGeneration toggles standard status information to be joined onto kinds' schema's status:
// {
// #OperatorState: {
// // lastEvaluation is the ResourceVersion last evaluated
// lastEvaluation: string
// // state describes the state of the lastEvaluation.
// // It is limited to three possible states for machine evaluation.
// state: "success" | "in_progress" | "failed"
// // descriptiveState is an optional more descriptive state field which has no requirements on format
// descriptiveState?: string
// // details contains any extra information that is operator-specific
// details?: {
// [string]: _
// }
// }
// // operatorStates is a map of operator ID to operator state evaluations.
// // Any operator which consumes this kind SHOULD add its state evaluation information to this field.
// operatorStates?: {
// [string]: #OperatorState
// }
// // additionalFields is reserved for future use
// additionalFields?: {
// [string]: _
// }
// }
// Default: true
enableOperatorStatusGeneration: true
}
definitions: {
// genManifest controls whether manifest files are written
// Default: true
genManifest: true
// genCRDs controls whether CRD files are written
// Default: true
genCRDs: true
// path sets where definition files are written
// Default: "definitions"
path: "definitions"
// encoding determines JSON or YAML serialization of CRDs and manifest, allowed values are "json" and "yaml"
// Default: "json"
encoding: "json"
// manifestVersion lets you pin the manifest schema format (legacy v1alpha1 vs default v1alpha2).
// The v1alpha1 manifest uses CRD-compatible schemas for kinds, the v1alpha2 version contains more information but requires transformation to make kind schemas CRD-compatible.
// Default: "v1alpha2"
manifestVersion: "v1alpha2"
}
}
```
---
## Troubleshooting
### `grafana-app-sdk: command not found`
The Go `bin` directory is not in `PATH`. Add it:
```bash
export PATH="$PATH:$(go env GOPATH)/bin"
```
### `generate` fails with CUE errors
CUE is strict about types and constraints. Common causes:
- Undefined field reference
- Type mismatch (`string` where `int` expected)
- Missing import (such as `time` for `time.Time`)
Run `cue vet ./kinds/...` to get more detailed error output.
### `generate` produces no TypeScript output
Check that `codegen.ts.enabled: true` is set in the kind's CUE file and that an output path is configured.
### `go mod tidy` needed after generate
After running `generate`, newly generated Go files may import packages not yet in `go.sum`. Run:
```bash
go mod tidy
```
deployment-modes.md 5.3 KB
# Deployment Mode Reference
## Standalone Operator
The app runs as a standalone Kubernetes operator binary with its own webhook server.
### Init steps
```bash
grafana-app-sdk project init github.com/example/my-app
grafana-app-sdk project component add operator # adds operator stubs (confirm with user first)
```
### Project structure after init + operator scaffold
```
my-app/
├── kinds/
├── pkg/
│ ├── generated/ # generated — do not edit
│ └── app/
│ └── app.go # implement app.App interface here
├── cmd/
│ └── operator/
│ └── main.go # operator entrypoint
├── go.mod
└── Makefile
```
### Runtime
- Runs as a Kubernetes operator
- Stands up its own admission webhook server
- Kubernetes routes admission requests to the webhook server via `ValidatingWebhookConfiguration` / `MutatingWebhookConfiguration`
- Reconcilers watch the Kubernetes API for resource changes
### Deployment
- Build a container image (`make build`)
- Deploy to Kubernetes with generated CRDs and webhook config
---
## grafana/apps
The app is a submodule inside the `github.com/grafana/grafana` repository's `apps/` directory.
**Only available inside the Grafana repo or a fork.** The repo is identified by the presence of `apps/` and `pkg/registry/apps/` at the git root. When inside the Grafana repo, this is the only available deployment mode.
The `grafana-app-sdk:init` command prompts for the app directory name (e.g. `myapp`) and derives the module path automatically as `github.com/grafana/grafana/apps/<app-name>` (adjusted for fork module names).
### Init steps
```bash
# From the grafana repo root — create and enter the app subdirectory
mkdir -p apps/my-app
cd apps/my-app
grafana-app-sdk project init github.com/grafana/grafana/apps/my-app
# Delete everything except:
# kinds/ pkg/ go.mod go.sum
rm -rf cmd/ config/ ... # remove generated dirs not needed
# Copy Makefile from example (run from repo root)
cp apps/example/Makefile apps/my-app/Makefile
```
### Wiring into Grafana
**1. Create `pkg/registry/apps/my-app/register.go`:**
```go
package myapp
import (
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana/apps/my-app/pkg/apis/manifestdata"
appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/setting"
)
var (
_ appsdkapiserver.AppInstaller = (*AppInstaller)(nil)
)
type AppInstaller struct {
appsdkapiserver.AppInstaller
cfg *setting.Cfg
}
// Uncomment to add an authorizer for the app
// func (e AppInstaller) GetAuthorizer() authorizer.Authorizer {
// return nil
// }
func RegisterAppInstaller(
cfg *setting.Cfg,
features featuremgmt.FeatureToggles,
) (*AppInstaller, error) {
installer := &AppInstaller{
cfg: cfg,
}
// specificConfig is any app-specific config, it should be a type defined in the myapp package
var specificConfig any
// Provider is the app provider, which contains the AppManifest, app-specific-config, and the New function for the app
provider := simple.NewAppProvider(manifestdata.LocalManifest(), specificConfig, exampleapp.New)
// appConfig is used alongside the provider for registrion.
// Most of the data is redunant, this may be more optimized in the future.
appConfig := app.Config{
KubeConfig: restclient.Config{}, // this will be overridden by the installer's InitializeApp method
ManifestData: *manifestdata.LocalManifest().ManifestData,
SpecificConfig: specificConfig,
}
// NewDefaultInstaller gets us the installer we need to underly the AppInstaller type.
// It does all the hard work of installing our app to the grafana API server
i, err := appsdkapiserver.NewDefaultAppInstaller(provider, appConfig, manifestdata.NewGoTypeAssociator())
if err != nil {
return nil, err
}
installer.AppInstaller = i
return installer, nil
}
```
**2. Add to `pkg/registry/apps/apps.go`:**
```go
func ProvideAppInstallers(...) []app.Installer {
return []app.Installer{
// ... existing apps ...
myapp.RegisterAppInstaller(),
}
}
```
**3. Add to the WireSet in `pkg/registry/apps/wireset.go`**
```go
var WireSet = wire.NewSet(
// ... existing apps ...
myapp.RegisterAppInstaller,
)
```
### Runtime
- App is embedded in Grafana's API server
- Admission handlers are auto-registered as Kubernetes in-process plugins — no separate webhook server
- Reconcilers run inside the Grafana process
### Enable in development
Add to `conf/custom.ini`:
```ini
[feature_toggles]
grafanaAPIServer = true
[grafana-apiserver]
enabled = true
```
Reference: `github.com/grafana/grafana/apps/example/README.md`
---
## Frontend-Only
No backend code. The app has kind definitions and generated TypeScript types, but no Go reconcilers or admission handlers.
### Init steps
```bash
grafana-app-sdk project init github.com/example/my-app
# No operator or backend component — skip those steps
grafana-app-sdk project component add frontend # optional: scaffold the frontend plugin
```
### Use case
- Apps that only need to read/write resources via the Kubernetes API from the frontend
- Dashboards, configuration UIs, or read-only viewers
- The Kubernetes API server handles storage; the app provides no custom admission logic
### Code generation
Typically only `frontend.enabled: true` in kind codegen config. Go backend types can be disabled to avoid generating unused code.
local-config.md 4.2 KB
# Local Development Configuration
The local development configuration when using `grafana-app-sdk project local generate` (or `make local/up` in the generated Makefile) can be configured via `local/config.yaml`. A full example of this configuration file with comments looks like:
```yaml
# Port used to bind services to localhost, for example, grafana will be available at http://grafana.k3d.localhost:9999
port: 9999
# Port used for the kubernetes APIServer on localhost
kubePort: 8556
# Pre-configured datasources to install on grafana. For custom-configuration datasources, use `datasourceConfigs`
datasources:
- cortex
- tempo
- loki
# Plugin JSON data, as key/value pairs
pluginJson:
foo: bar
# Plugin Secure JSON data. By default, the `kubeconfig` and `kubenamespace` values will be added in the generated YAML.
# You can overwrite those values by specifying them here instead.
pluginSecureJson:
baz: foo
# Standalone operator docker image. Leave this empty to not deploy an operator
operatorImage: "myapp:latest"
# Governs whether the local setup generates kubernetes manifests for varying kinds of webhooks attached to your operator and each CRD
webhooks:
# The port the operator exposes an HTTPS server with the webhook endpoint(s) on
port: 8443
# Non-standard or additional datasources you want to automatically include in grafana's provisioned list
# The actual datasources need to be set up manually (arbitrary kubernetes yamls can be added to the local setup via the 'additional' folder),
# but you can predefine the connection details so they'll be added to the local grafana.
datasourceConfigs:
# Here is an example cortex config
# - access: proxy
# editable: false
# name: "my-cortex-datasource"
# type: prometheus
# uid: "my-cortex-datasource"
# url: "http://cortex.default.svc.cluster.local:9009/api/prom"
# Here is an example with jsonData (e.g., for BigQuery)
# - access: proxy
# editable: true
# name: "BigQuery"
# type: grafana-bigquery-datasource
# uid: "my-bigquery-datasource"
# jsonData:
# authenticationType: gce
# defaultProject: my-project
#
# Toggle the generating of the grafana deployments, if you want to control these elsewhere
generateGrafanaDeployment: true
# which grafana image to use
grafanaImage: grafana/grafana-enterprise:12.0.0
# Install plugins from other sources (URLS). See https://grafana.com/docs/grafana/latest/setup-grafana/configure-docker/#install-plugins-from-other-sources
grafanaInstallPlugins: ""
# You can mount additional volumes from the local disk (aside from the already-mounted ./local/mounted-files) by specifying them here
# These volumes are mounted into the k3d node. To also mount them into the Grafana container, use grafanaVolumeMounts.
additionalVolumeMounts:
# - sourcePath: "./local/other" # Paths starting with a ./ or no leading slash are relative to the project root. Start with / for an absolute path
# mountPath: "/tmp/k3d/other" # The destination volume path. Best practice is to use /tmp/k3d as the starting point. The default volume mount for ./local/mounted-files is /tmp/k3d/mounted-files
# Additional environment variables to add to the Grafana container
grafanaEnvVars:
# - name: "GOOGLE_APPLICATION_CREDENTIALS"
# value: "/gcloud/application_default_credentials.json"
# Additional volume mounts to add to the Grafana container
# The hostPath should reference a path from additionalVolumeMounts (the k3d node mount path)
grafanaVolumeMounts:
# - name: "gcloud-credentials"
# mountPath: "/gcloud"
# hostPath: "/tmp/k3d/gcloud"
# Example: Full BigQuery setup with gcloud credentials
# additionalVolumeMounts:
# - sourcePath: "~/.config/gcloud" # ~ is expanded to home directory
# mountPath: "/tmp/k3d/gcloud"
# grafanaEnvVars:
# - name: "GOOGLE_APPLICATION_CREDENTIALS"
# value: "/gcloud/application_default_credentials.json"
# grafanaVolumeMounts:
# - name: "gcloud-credentials"
# mountPath: "/gcloud"
# hostPath: "/tmp/k3d/gcloud"
# datasourceConfigs:
# - access: proxy
# editable: true
# name: "BigQuery"
# type: grafana-bigquery-datasource
# uid: "my-bigquery-datasource"
# jsonData:
# authenticationType: gce
# defaultProject: my-project
# grafanaInstallPlugins: "grafana-bigquery-datasource"
``` local-development.md 6.5 KB
# Local Development Guide
## Standalone Operator Mode
### Standard Way from Generated Files
The grafana-app-sdk generates a standard way of running a kubernetes cluster locally with grafana, datasources, and app setup using k3d and tilt.
#### Prerequisites
* [k3d](https://k3d.io/stable/)
* [tilt](https://tilt.dev/)
#### Create Cluster
The generated Makefile has the target `make local/up` to create the cluster and apply everything. This runs:
* `grafana-app-sdk project local generate` - generates a k3d config (`./local/generated/k3d-config.json`) to mount the host volume `./local/mounted-files` and a YAML bundle in `./local/generated/dev-bundle.yaml`.
* `./local/scripts/cluster.sh create "local/generated/k3d-config.json"` to create the cluster
* `tilt up` in the `local` directory to stand up all resources.
`local/Tiltfile` is generated by `project init` and will scrape all YAML in `local/generated`, and then all YAML in `local/additional` (which overwrites anything declared in `local/generated`).
#### Push Operator Image
The operator image must be built with `make build` and then pushed to the local cluster with `make local/push_operator`
#### Deploy Plugin
The plugin for the app can be pushed to the local grafana deployment with `make local/deploy_plugin`. The plugin must have been built already (`make build`). By default, the grafana deployment loads the plugin from `local/mounted-files/plugin/dist`.
#### Configuration
The local setup can be configured with the file `local/config.yaml` (generated by `project init`).
See `local-config.md` for a full reference of all available configuration options.
#### Testing with kubectl
Once CRDs are applied and the operator is running, create test resources directly:
```bash
# Create a resource
kubectl apply -f - <<EOF
apiVersion: my-app.grafana.app/v1alpha1
kind: MyKind
metadata:
name: test-resource
namespace: default
spec:
title: "Test"
description: "A test resource"
EOF
# Watch the resource status update as the reconciler runs
kubectl get mykind test-resource -w
# See full status
kubectl describe mykind test-resource
# Delete it
kubectl delete mykind test-resource
```
#### Debug Logging
By default, the generated operator code uses debug-level logging when it instantiates the global default logger:
```go
// main.go
func main() {
// Configure the default logger to use slog
logging.DefaultLogger = logging.NewSLogLogger(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
// ... rest of code
}
```
An app author may change this to read from a config file or CLI, in order to find our, either ask the user or read `cmd/operator/main.go` to see how the logging is configured.
### Alternative Local Dev Methods
#### Prerequisites
A local Kubernetes cluster is required. The easiest options:
```bash
# Option A: kind (Kubernetes in Docker)
brew install kind
kind create cluster --name dev
# Option B: minikube
brew install minikube
minikube start
# Confirm kubectl is pointing at the local cluster
kubectl config current-context
kubectl get nodes
```
#### Apply CRDs
Before running the operator, apply the generated CRDs to the cluster:
```bash
# Apply all generated CRD files
kubectl apply -f definitions/
```
> `kubectl apply -f definitions/` will also attempt to apply the `<app>-manifest.(json|yaml)` file, which is not a valid Kubernetes resource and will produce an error. This error can be safely ignored — the CRD files will still be applied successfully.
Run this again after every `grafana-app-sdk generate` if schema fields changed.
#### Run the Operator Locally
Build and run the operator binary against the local cluster:
```bash
# Run directly with go run
go run ./cmd/operator/... --kubeconfig="$HOME/.kube/config"
# Or build first then run
make build
./bin/operator --kubeconfig="$HOME/.kube/config"
```
The operator uses the standard kubeconfig by default — it will connect to whatever cluster `kubectl` points to.
---
## grafana/apps Mode
For grafana/apps, local development means running the full Grafana binary with your app registered.
### Build and Run Grafana
From the Grafana repo root:
```bash
# Build the backend (includes your app)
make build-go
# Run Grafana with your app registered
./bin/grafana server
# Or use the dev mode that watches for changes
make run
```
Your app is automatically included in the binary because it's registered in `pkg/registry/apps/apps.go`.
### Testing with Grafana UI
1. Navigate to `http://localhost:3000`
2. Use the Grafana API or UI to create resources of your kind
3. Watch server logs for reconciler/admission output
### API Access
Your kind is accessible via the Grafana API at:
```
GET/POST /apis/<group>/<version>/namespaces/<namespace>/<plural>
```
For example:
```bash
# List resources
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:3000/apis/my-app.grafana.app/v1alpha1/namespaces/default/mykinds
# Create a resource
curl -X POST \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"apiVersion":"my-app.grafana.app/v1alpha1","kind":"MyKind","metadata":{"name":"test"},"spec":{"title":"Test"}}' \
http://localhost:3000/apis/my-app.grafana.app/v1alpha1/namespaces/default/mykinds
```
---
## Common Development Patterns
### Watching Reconciler Behavior
Run the operator with debug logging and watch what happens when resources change:
```bash
# Terminal 1: Run operator
go run ./cmd/operator/...
# Terminal 2: Create a resource and watch it
kubectl apply -f my-resource.yaml && kubectl get mykind -w
```
### Forcing a Re-reconcile
The operator reconciles on changes. To force a re-reconcile without editing the resource:
```bash
# Touch the resource with a no-op annotation change
kubectl annotate mykind my-resource grafana.com/force-reconcile="$(date)" --overwrite
```
### Checking Admission Webhooks
For standalone mode, the operator runs its own webhook server. Test admission by creating/updating resources and checking for validation errors:
```bash
# Invalid resource (should be rejected)
kubectl apply -f invalid-resource.yaml
# Output should include the admission error message
# Check webhook logs in the operator output
```
### Resetting State
To start fresh during development:
```bash
# Delete all resources of a kind
kubectl delete mykind --all -n default
# Delete and re-apply CRDs (loses all data)
kubectl delete -f definitions/
kubectl apply -f definitions/
```
> Both commands will produce an error for the `<app>-manifest.(json|yaml)` file, which is not a valid Kubernetes resource. These errors can be safely ignored.
project-structure.md 1.4 KB
# Project layout (standalone operator mode)
```
my-app/
├── cmd/
│ └── operator/ # Build target — `main` package
├── kinds/ # CUE kind definitions (source of truth)
│ ├── manifest.cue # App-level manifest + version declarations
│ ├── mykind.cue # Kind metadata for MyKind
│ └── mykind_v1alpha1.cue # Version schema for MyKind v1alpha1
├── pkg/
│ ├── generated/ # Generated Go code — DO NOT edit manually
│ ├── watchers/ # Watcher stubs from `project component add operator`
│ └── app/
│ └── app.go # Entry point — implement `app.App` interface here
├── definitions/ # Generated CRD + manifest files — DO NOT edit manually
├── local/
│ ├── additional/ # Extra YAML manifests for local deployment
│ ├── generated/ # Generated local-deploy manifests (don't commit)
│ ├── mounted-files/ # Mounted into the k3d cluster (don't commit)
│ ├── scripts/ # Generated scripts (don't commit)
│ ├── Tiltfile # Tiltfile for local stack
│ └── config.yaml # Local setup config
├── go.mod
└── Makefile
```
## What you edit vs what's generated
| Edit by hand | Regenerate from CUE |
|---|---|
| `kinds/*.cue` | `pkg/generated/**` |
| `pkg/app/app.go`, `pkg/watchers/*.go` | `definitions/*` |
| `cmd/operator/main.go` (rarely) | TypeScript types (frontend) |
Rerun `grafana-app-sdk generate` after every kind change.
specific-config.md 0.9 KB
# App-specific configuration (`SpecificConfig`)
Apps pass structured configuration through `app.Config.SpecificConfig`. This is how the registration layer (`register.go`) passes feature flags or runtime settings into `New`.
```go
// pkg/app/config.go
type AppSpecificConfig struct {
EnableReconciler bool
SomeFeatureFlag bool
}
// pkg/app/app.go — read it in New()
func New(cfg app.Config) (app.App, error) {
appCfg, _ := cfg.SpecificConfig.(*AppSpecificConfig)
if appCfg != nil && appCfg.EnableReconciler {
// wire up reconciler
}
// ...
}
// pkg/registry/apps/<name>/register.go — populate from Grafana config
specificConfig := &app.AppSpecificConfig{
EnableReconciler: features.IsEnabled(featuremgmt.FlagMyAppReconciler),
}
provider := simple.NewAppProvider(manifestdata.LocalManifest(), specificConfig, app.New)
```
Use `SpecificConfig` for anything that varies by environment or feature flag — never hardcode it in `New`.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE