stack

package
v0.2.0-beta.23 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

Stack - Core Domain Model

Go Reference

The stack package defines the hierarchical domain model at the heart of Kure. It provides the Cluster, Node, Bundle, and Application abstractions used to describe a complete Kubernetes deployment topology.

Overview

Kure models Kubernetes infrastructure as a four-level hierarchy:

Cluster
  └── Node (tree structure)
        └── Bundle (deployment unit)
              └── Application (workload)

Each level maps to a concept in GitOps deployment:

Level Purpose GitOps Mapping
Cluster Target cluster Root directory
Node Organizational grouping (e.g., infrastructure, apps) Subdirectory tree
Bundle Deployment unit with dependencies Flux Kustomization / ArgoCD Application
Application Individual workload or resource set Kubernetes manifests

Key Types

Each Go block on this page, except the three marked as excerpts, is the body of an Example function in example_test.go, which go test runs: it imports this package as stack, github.com/go-kure/kure/pkg/stack/fluxcd for its side effect of registering the "flux" workflow provider, k8s.io/apimachinery/pkg/runtime/schema, and fmt for the line that prints what the example built. The myConfig type the examples use is the one the Optional Validation section declares; its Generate method also needs strconv.

Cluster

The root of the hierarchy, representing a complete cluster configuration. Exported fields remain available for compatibility, while getter and setter methods support consumers that prefer method-based access.

rootNode := &stack.Node{Name: "flux-system"}

cluster := stack.NewCluster("production", rootNode)
cluster.SetGitOps(&stack.GitOpsConfig{
    Type: "flux",
})
fmt.Println(cluster.GetName(), cluster.GetNode().Name, cluster.GetGitOps().Type)

GitOpsConfig.Bootstrap takes a BootstrapConfig: the Flux mode (flux-operator by default, or gotk), the Flux version (in gotk mode, empty or the vendored fluxcd.GotkVersion builds offline; any other value downloads manifests — the named release for vX.Y.Z, the latest release otherwise; in flux-operator mode it is required, as is Registry, and an empty value is an error) and components, and the sync source — SourceKind, SourceURL, SourceRef and SyncName, the name of the bootstrap source and Kustomization in both modes (empty keeps each mode's names: the operator uses the FluxInstance namespace, gotk the root node's name for the source and the generator's BootstrapName for the Kustomization). For an OCIRepository source, SourceSecretRef, SourceProvider and SourceInsecure give the registry credentials, OIDC provider and plain-HTTP access in both modes, SourceVerify (a SourceVerification) makes it verify the artifact's signature, and SourceSemVer selects its tag by a semver range instead of SourceRef. ImagePullSecret names the Secret the Flux controller images are pulled with, in both modes: the gotk install option, or the FluxInstance distribution's imagePullSecret. It is not a credential for the sync source. In flux-operator mode neither Registry nor ImagePullSecret reaches the flux-operator Deployment in the vendored install bundle, whose image is pulled as upstream ships it. A set Prune reaches the bootstrap Kustomization in both modes, in flux-operator mode as a patch on the operator's sync Kustomization; unset keeps each mode's default, prune: false in gotk mode and the operator's prune: true in flux-operator mode (go-kure/kure#1088). Labels are set on the bootstrap source and Kustomization in both modes with a SourceURL, in flux-operator mode as patches on the operator's sync objects; the keys a Flux controller stamps on those objects are refused in both modes: flux-operator's app.kubernetes.io/managed-by, app.kubernetes.io/instance, app.kubernetes.io/version, app.kubernetes.io/part-of, fluxcd.controlplane.io/name and fluxcd.controlplane.io/namespace, and kustomize-controller's kustomize.toolkit.fluxcd.io/name and kustomize.toolkit.fluxcd.io/namespace (go-kure/kure#1180). See Flux Engine for how each field is emitted.

Node

A tree structure for organizing bundles into logical groups. Nodes can have children (sub-nodes) and a package reference for multi-source deployments.

childNode := &stack.Node{Name: "cert-manager"}
monitoringBundle := &stack.Bundle{Name: "monitoring"}

node := &stack.Node{
    Name:     "infrastructure",
    Children: []*stack.Node{childNode},
    Bundle:   monitoringBundle,
}
fmt.Println(node.Name, node.Children[0].Name, node.Bundle.Name)

A node whose directory renders no bundle (a group of nodes, say) is applied by a Flux Kustomization of its own under the layout rule FluxPlacement: FluxIntegratedPerLayout. KustomizationName names it, instead of the name derived from the node's path, and DependsOn (nodes) and NamedDependsOn (Kustomization names) order it. On any other node, under another placement and under the ArgoCD workflow the three fields are refused rather than ignored. See Flux Engine.

Bundle

A deployment unit corresponding to a single GitOps resource (e.g., a Flux Kustomization). Bundles support dependency ordering via DependsOn (pointer-based) or NamedDependsOn (name-based, for cross-scope references).

The generated resource is named after the bundle. KustomizationName gives it another name without renaming the bundle or moving its directory; UnitName() returns the name in effect. Under the ArgoCD workflow the same value names the Application. A NamedDependsOn entry names such a resource, so it reaches a bundle that sets KustomizationName by that value.

Bundle.Generate returns its applications' objects with the bundle's Labels and Annotations added; an object's own value for a key wins. Every annotation the object carries stays as written, also on an unstructured object whose value is no string (a YAML boolean or number): only the missing keys are added. Where the bundle sets labels, each object is given a new labels map; where it sets annotations, each object that lacks one of them is given a new annotations map, and one that carries them all keeps its own. A map its config also uses elsewhere (a Deployment's selector or pod template labels) is not written, and a new map is shared with neither the bundle nor another object. A nil entry, or one holding no object (a nil client.Object, or a nil pointer of an object type such as (*corev1.ConfigMap)(nil)), is returned as it is and gets nothing.

A nil DependsOn entry is refused by Bundle.Validate, with the bundle's path (an umbrella descendant's from the bundle that was validated: platform/infra/db) and the entry's index; the Flux generator refuses it the same way for a bundle it is handed unvalidated (GenerateForBundle).

A DependsOn entry need not be the cluster's own bundle: another Bundle value with the same Name is a copy of it, and a cluster resolves it by Name to that bundle, so the dependency is on that bundle's Kustomization. Leave KustomizationName empty on a copy, or set the name of the bundle's Kustomization (its UnitName(): the bundle's KustomizationName, or its Name when it sets none). ValidateCluster refuses, before it validates the bundles one by one:

  • a copy that sets a KustomizationName other than that name, naming both;
  • a copy of a bundle whose Kustomization name is also in the dependant's NamedDependsOn: one dependency in both lists.

Bundle.Validate sees one bundle and no cluster, so it compares a DependsOn entry with NamedDependsOn on the name that entry carries itself. One valid input is refused for that reason: a name-only copy of a bundle that sets KustomizationName, beside a NamedDependsOn entry equal to the bundle's Name (which then means another Kustomization), is reported as one dependency in both lists. Set the bundle's KustomizationName on the copy to say which one is meant.

A bundle's directory is named after the bundle as well. DirName gives it another name (00-infra for the bundle shop-infra, say), and the path the generated resource applies follows it; the resource's name does not. The rule is one: wherever a bundle's name becomes a directory, DirName names it, or else Name. That is the case for an umbrella child, for a node's bundle under the layout rule BundleGrouping: GroupByName, and for the root node's bundle under GroupFlat, which has a directory inside the root node's. Under GroupFlat below the root a node's bundle is rendered in its node's directory and DirName has no effect on it. When a flat NodeGrouping merges several bundles into the root node, the directory they share takes the first merged bundle's DirName, or its Name; a DirName on a later one has no effect.

A DirName must be one path segment (ValidateDirectoryName): not . or .., and without /, \ or a NUL byte. Bundle.Validate checks it on the bundle and on every umbrella child, whether or not the layout rules give the bundle a directory. It is no object name, so it need not be a DNS-1123 subdomain: 00_Infra is valid.

NewBundle keeps a copy of the labels map it is given (a nil map stays nil), so editing that map after the call leaves the bundle as it was built. It validates the bundle it builds; fields set afterwards are checked by Bundle.Validate:

apps := []*stack.Application{
    stack.NewApplication("prometheus", "monitoring", &myConfig{Port: 9090}),
}
labels := map[string]string{"team": "platform"}
certManagerBundle := &stack.Bundle{Name: "cert-manager"}

bundle, err := stack.NewBundle("monitoring", apps, labels)
if err != nil {
    panic(err)
}
// Pointer-based — when you hold the bundle object:
bundle.DependsOn = []*stack.Bundle{certManagerBundle}
// Name-based — when you only know the name (e.g. a hook-phase bundle):
bundle.NamedDependsOn = []string{"cert-manager-pre-install"}
bundle.Interval = "10m"

if err := bundle.Validate(); err != nil {
    panic(err)
}
fmt.Println(bundle.Name, bundle.DependsOn[0].Name, bundle.NamedDependsOn, bundle.Interval)

Interval, Timeout and RetryInterval take Go duration strings ("10m", "1h30m"). Empty means the generator's default interval, or, for Timeout/RetryInterval, that the field is omitted so Flux's own defaults apply; any other value that does not parse ("5 minutes", "5min", "5") is rejected by Bundle.Validate and by the Flux generator, never replaced by the default. The error names the bundle, the field and the value, then the parse error, once. The Flux generator also refuses a duration the Flux API does not take, a negative one or a positive one under a millisecond ("-1s", "1us"), where it writes the bundle's Kustomization; Bundle.Validate accepts those, since the rule is Flux's (see the Flux engine's "Durations").

ServiceAccountName names the service account kustomize-controller impersonates when it applies the bundle: the Flux workflow writes it to spec.serviceAccountName of the bundle's Kustomization and, under FluxPlacement: FluxIntegratedPerLayout, of the Kustomization of each of the bundle's applications that has a directory of its own and of each layout below it. Empty writes nothing, as before, and the controller applies with its own identity, or with the default service account it is started with (--default-service-account), if any. Flux looks the account up in the Kustomization's own namespace, the generator's DefaultNamespace; creating the account and its RBAC is the caller's. An umbrella's value is not passed to its Children: each bundle carries its own. The value must be a DNS-1123 subdomain (see "Service account name" below). The ArgoCD workflow does not read it.

Bundles also support an umbrella pattern via Bundle.Children. When a bundle has non-empty Children, its generated Flux Kustomization automatically gets an entry in spec.healthChecks for each child while Bundle.Wait is unset or false, giving external consumers a single readiness anchor for a group of bundles. A Flux generator with OmitUmbrellaChildHealthChecks set writes none. With Wait unset or false the umbrella then no longer waits for its children; it is Ready once applied and its own HealthChecks, if any, pass (see the Flux engine's "With OmitUmbrellaChildHealthChecks"). spec.wait is left to Bundle.Wait: the generator no longer forces it, because upstream ignores healthChecks when wait is enabled, and with Wait true it writes no entry for the children. Whether wait then covers the children depends on the Flux placement (see the Flux engine's "Umbrella Bundles"). Under the integrated Flux placements the child bundles' Flux Kustomization CRs are rendered into the parent bundle's directory; under FluxSeparate they go to flux-system/ with every other one. Children must be standalone bundles — they cannot simultaneously be attached as the Bundle of any stack.Node.

Bundle.HealthChecks can also be set explicitly to monitor specific resources during reconciliation:

bundle := &stack.Bundle{Name: "web"}

bundle.HealthChecks = []stack.HealthCheck{
    {APIVersion: "apps/v1", Kind: "Deployment", Name: "web", Namespace: "default"},
}
fmt.Println(bundle.HealthChecks[0].Kind, bundle.HealthChecks[0].Name)

When Children is non-empty and Wait is not true, health checks for each child Kustomization are auto-generated and merged with any user-supplied entries. The user-supplied entries are handled as before; dropping the child entries under Wait does not touch them.

Validation: ValidateCluster() runs automatically in all layout entry points (WalkCluster, WalkClusterByPackage) and rejects invalid umbrella configurations (e.g., shared ownership, children that are also node bundles). It also rejects a Node tree containing a cycle, naming the node where the cycle closes.

Names: a bundle name and a node name are checked when the model is validated, and a limit that only one delivery engine has is checked by that engine's workflow when it generates, so a name that could never be applied is refused before anything is written. A name the caller sets is never shortened or rewritten: the caller chooses a valid name. The one name shortened is one kure composes itself, the Flux workflow's default <unit name>-<layout name> for a layout's own Kustomization (pkg/stack/fluxcd README, "Per-layout name rule").

Name Rule Checked by
Bundle, including every umbrella child a DNS-1123 subdomain and a directory name Bundle.Validate
A bundle's KustomizationName, when set a DNS-1123 subdomain Bundle.Validate
The name a bundle's Kustomization gets in the Flux workflow (UnitName()) a Flux Kustomization name the Flux generator, where it builds the Kustomization
Node a directory name, under every layout grouping; an unnamed root is allowed, it adds no path segment ValidateCluster
The name a node's own Kustomization gets in the Flux workflow (its KustomizationName, or the derived <path>-node) a Flux Kustomization name the Flux layout integrator, where it creates the Kustomization
An entry of a node's NamedDependsOn not empty and not repeated; its value is a caller-supplied reference and is not checked, as for a bundle's ValidateCluster
Application a directory name, only where the layout rules give the application a directory layout.WalkCluster
  • Bundle name: a DNS-1123 subdomain, at most 253 characters: lower-case letters, digits, - and ., starting and ending with a letter or digit. my.app is valid; My-App is not. This is what holds for every delivery engine, because the engine applies the bundle with an object named after it (a Flux Kustomization, an ArgoCD Application). A KustomizationName names that object instead of the bundle's name, so it is a DNS-1123 subdomain too; it is no directory name. The bundle's Name is checked the same with or without it.
  • Kustomization name (ValidateKustomizationName): a DNS-1123 subdomain of at most KustomizationNameMaxLength (63) characters. The limit is Flux's, so Bundle.Validate and ValidateCluster do not apply it: the Flux workflow refuses a longer name where it builds the bundle's Kustomization, before anything is written, and the same name validates and renders an Application in the ArgoCD workflow. The name checked is the one the Kustomization gets, UnitName(): the KustomizationName, or the Name without one, so a Name over the limit beside a KustomizationName within it generates. The limit is 63 and not the 253 of an object name because Flux writes the Kustomization's name into a label value on every object it applies. Read in kustomize-controller v1.10.1, the version this module pins: the reconciler hands the name to the apply manager as the owner of the objects (internal/controller/kustomization_controller.go:489), and the manager sets it as the value of the kustomize.toolkit.fluxcd.io/name label (github.com/fluxcd/pkg/ssa v0.83.0, manager.go:66-78).
  • Directory name (ValidateDirectoryName): one path segment. It is not empty, not . or .., and holds neither / nor \ nor a NUL byte. The backslash is refused on every platform, so a name such as ..\outside cannot leave its directory where the backslash is a separator. A NUL byte is refused because a directory with one in its name cannot be created; characters that only some file systems refuse are not checked.
  • Service account name (ValidateServiceAccountName): a DNS-1123 subdomain, the rule Kubernetes sets for a ServiceAccount's name. Bundle.Validate checks a ServiceAccountName on the bundle and on every umbrella child, and the error names the bundle by its path. The Flux generator checks it again where it writes the bundle's Kustomization, for a bundle generated without Validate. Flux's Kustomization does not check the field, so a name no ServiceAccount can have would be admitted there and fail only at reconcile.

A node name is checked whatever the layout rules are, also where flat node grouping absorbs the node into its parent's directory. The name is a segment of the node's path in the model before it is a directory: Node.GetPath and the path map join node names with /, so two unnamed children of one node have the same path, and so do a node named a/b and a node b below a sibling a. A cluster with an unnamed node below the root, or with a separator in a node name, is therefore refused under every grouping.

An error from either rule names where the name sits: a bundle by its path from the bundle that was validated (platform/platform-infra), a node by its path from the root, and ValidateCluster adds the node a refused bundle is attached to (bundle "web" at node "apps/web" failed validation). An umbrella child without a name is refused earlier, by the check on Children, which names its parent and the child's index. Both functions are exported so that code deriving a name from these fields can check the result with the same rule. The Flux generator's refusal of a Kustomization name over 63 characters names the bundle by Bundle.GetPath, which for an umbrella child of a walked cluster holds its umbrella's path (platform/platform-infra), and the field that holds the name (name or kustomizationName). Its refusal of the name of a node's own Kustomization names the node by its path from the root and the field kustomizationName, also where the name was derived and the field is the one to set. Two Flux entry points take a bundle or a node that no cluster validation has seen and apply a rule themselves: the generator checks the whole Kustomization name rule on a bundle it is handed directly (GenerateForBundle), and the bootstrap generator checks the root node's name as a directory name wherever it builds a path from it.

Application

An individual Kubernetes workload. Applications use the ApplicationConfig interface to generate their resources.

prometheusConfig := &myConfig{Port: 9090}

app := stack.NewApplication("prometheus", "monitoring", prometheusConfig)
resources, err := app.Generate()
if err != nil {
    panic(err)
}
fmt.Println(len(resources), (*resources[0]).GetName())
Delivery intent

Application.Delivery states how the delivery engine should treat the application's objects, in engine-neutral terms. Both fields default to off, and an application that sets neither renders exactly as before.

Field Meaning
PruneProtection Keep the application's objects in the cluster when they are removed from the source.
ForceReplace Allow an object to be deleted and recreated when a change touches an immutable field.

The intent covers every object the application emits, the objects a layout augmenter adds to the application's own directory, and the ConfigMaps built from that directory's configMapGenerator entries. Each workflow engine maps it to its own mechanism: the Flux workflow writes per-object annotations (see Flux Engine); the ArgoCD workflow has no mapping yet and refuses an application that sets one. The Flux GenerateFromCluster refuses one too: it returns Kustomizations and Sources and none of the application's objects, so use CreateLayoutWithResources. Bundle.Prune and Bundle.Force stay the bundle-wide switches on the generated Flux Kustomization and are independent of this field.

ApplicationConfig Interface

Implement this interface to define how an application generates its Kubernetes resources:

type ApplicationConfig interface {
    Generate(*Application) ([]*client.Object, error)
}
Optional Validation

ApplicationConfig implementations can optionally implement the Validator interface to validate configuration before resource generation:

type Validator interface {
    Validate() error
}

When present, Application.Generate() calls Validate() automatically before Generate(). If validation fails, generation stops and the error is returned with application context:

type myConfig struct{ Port int }

func (c *myConfig) Validate() error {
    if c.Port <= 0 {
        return errors.New("port must be positive")
    }
    return nil
}

func (c *myConfig) Generate(app *stack.Application) ([]*client.Object, error) {
    // Only called if Validate() passes (or is not implemented)
    cm := kubernetes.CreateConfigMap(app.Name, app.Namespace)
    cm.Data = map[string]string{"port": strconv.Itoa(c.Port)}
    var obj client.Object = cm
    return []*client.Object{&obj}, nil
}

errors is github.com/go-kure/kure/pkg/errors, kubernetes is github.com/go-kure/kure/pkg/kubernetes, and client is sigs.k8s.io/controller-runtime/pkg/client.

Validation errors are wrapped with application name and namespace:

validation failed for application "web" in namespace "prod": port must be positive

Configs that do not implement Validator continue to work without changes.

Generation contract

What Generate returns belongs to the caller from the moment it returns: the slice, every object it points to, and every map, slice and pointer those objects hold. kure writes to the objects. Bundle.Generate adds the bundle's labels and annotations that an object lacks, and the Flux integrator adds an application's delivery annotations (see Flux Engine). A caller that holds the layout may edit them as well. So:

  • Return nothing you keep or have returned before. Build each result fresh, or return a DeepCopy() of a cached one. Do not share a map between objects, or between fields of one object: kure gives an object a new map where it adds labels or annotations, but a caller's edit of a Deployment's labels map in the layout also reaches a selector that shares it.
  • Every call is independent, failed ones included. A walk (layout.WalkCluster, layout.WalkClusterByPackage) calls Generate once for each application it renders. Every workflow entry point that renders applications walks once, and nothing memoizes across calls: validating with one entry point and laying out with another generates twice. A walk in which one call fails returns no layout.
  • To reuse a result you already validated, memoize in the config. Validate and render once, then return a deep copy on each call. The copy is linear in the objects' size, so it pays for itself only where rendering costs more than copying, as with templates, charts and decoded YAML.
  • No concurrency. kure never calls Generate concurrently. Memoizing does not make a config safe for concurrent use, and a config safe for concurrent use need not memoize.
  • Wrappers forward the optional interfaces. kure finds Validator, layout.LayoutAugmenter and layout.LayoutIntentAugmenter by type assertion on the config itself. A wrapper that embeds the ApplicationConfig interface hides all three, silently: no validation, no augmentation, and under flat application grouping no layout of its own. Embed the concrete type, or forward each method.

Application.Generate runs Validate and Generate on every call and never augments a layout; only a walk does. The tests in pkg/stack/layout/generation_contract_test.go (walks) and pkg/stack/generation_contract_test.go (workflow entry points) show the call counts per walk and per entry point, what the augmenter sees and where it is skipped, that a failed walk returns no layout and a later walk uses nothing from it, that one walk's edits stay out of the next for fresh and deep-copying configs but not for a shared cache, and what each wrapper shape keeps. No test shows the concurrency rule: it is a property of kure's code.

To hold a config of your own to this contract, call stacktest.AssertGeneration from its tests (Stack Test Helpers): it fails for anything two calls share or one result reaches twice, and stacktest.InterfacesOf shows what a wrapper hides.

Fluent Builder API

For ergonomic cluster construction, use the fluent builder. Builder methods use copy-on-write semantics — each With* call returns a new builder instance, leaving the original unchanged. Build returns the cluster, or every error the chain collected, joined:

appConfig := &myConfig{Port: 9090}

cluster, err := stack.NewClusterBuilder("production").
    WithNode("infrastructure").
    WithBundle("monitoring").
    WithApplication("prometheus", appConfig).
    End().
    End().
    Build()
if err != nil {
    panic(err)
}
fmt.Println(cluster.Name, cluster.Node.Name, cluster.Node.Bundle.Name)

Workflow System

The package provides a pluggable workflow abstraction for GitOps tool integration:

cluster, err := stack.NewClusterBuilder("production").
    WithNode("infrastructure").
    WithBundle("monitoring").
    WithApplication("prometheus", &myConfig{Port: 9090}).
    End().
    End().
    Build()
if err != nil {
    panic(err)
}

// Create a workflow for your GitOps tool
wf, err := stack.NewWorkflow("flux")
if err != nil {
    panic(err)
}

// Generate GitOps resources from the cluster definition, with the layout
// rules the tree is written with
objects, err := wf.GenerateFromCluster(cluster, layout.DefaultLayoutRules())
if err != nil {
    panic(err)
}
for _, obj := range objects {
    fmt.Println(obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())
}

GenerateFromCluster walks the cluster with the layout rules you pass: every Flux Kustomization spec.path and ArgoCD Application source.path is a directory that walk writes, so pass the rules you write the tree with (layout.DefaultLayoutRules() for the defaults). The rules must be a layout.LayoutRules value; anything else, nil included, is refused. Neither engine returns a list for rules with FluxIntegratedPerLayout (the Flux Kustomizations that apply that tree's child directories exist only in a layout): use CreateLayoutWithResources with the Flux engine for that placement. CreateLayoutWithResources takes the same rules and also returns the layout it walked, with the resources placed in it. GenerateBootstrap(config, rootNode, rules) takes the same rules too, and points Flux at the top directory of the tree a walk with them writes (see Flux Engine).

Supported workflow providers: "flux" / "fluxcd" and "argo" / "argocd". Each is registered by importing its package, and NewWorkflow returns that package's *fluxcd.WorkflowEngine or *argocd.WorkflowEngine; without the import it fails with an error naming the package to import.

Source References

Bundles and nodes can reference different source types for multi-source deployments: a bundle through its SourceRef field, a node through its PackageRef, a schema.GroupVersionKind:

// A bundle's SourceRef names the Flux source its Kustomization reads from;
// with URL set, the generator creates that source as well.
bundle := &stack.Bundle{Name: "apps"}
bundle.SourceRef = &stack.SourceRef{
    Kind:      "OCIRepository",
    Name:      "my-registry",
    Namespace: "flux-system",
    URL:       "oci://registry.example.com/manifests",
    Tag:       "v1.0.0",
}

// A node's PackageRef names the package its subtree is bundled into;
// child nodes without one inherit it.
node := &stack.Node{Name: "apps", Bundle: bundle}
node.SetPackageRef(&schema.GroupVersionKind{
    Group:   "source.toolkit.fluxcd.io",
    Version: "v1",
    Kind:    "OCIRepository",
})
fmt.Println(bundle.SourceRef.URL, node.GetPackageRef().Kind)

Documentation

Overview

Package stack provides the core domain model for defining and generating Kubernetes cluster configurations with GitOps tooling (Flux CD or ArgoCD).

Overview

The stack package models a Kubernetes cluster as a hierarchical tree of nodes, where each node can contain bundles of applications. This structure maps directly to the directory layouts expected by GitOps tools, enabling declarative generation of the complete repository structure needed for Flux Kustomizations or ArgoCD Applications.

Domain Model

The core types form a hierarchical structure:

	Cluster
	  └── Node (tree structure)
	        ├── Bundle
	        │     └── Applications
	        └── Children (nested Nodes)

  - [Cluster]: Top-level configuration including GitOps settings
  - [Node]: Hierarchical structure for organizing deployment units
  - [Bundle]: Collection of applications deployed together
  - [Application]: Individual Kubernetes workload or component

Fluent Builder API

The package provides a fluent builder API for constructing cluster configurations in a type-safe, readable manner:

cluster, err := stack.NewClusterBuilder("production").
	WithGitOps(&stack.GitOpsConfig{Type: "flux"}).
	WithNode("infrastructure").
		WithBundle("monitoring").
			WithApplication("prometheus", prometheusConfig).
			End().
		End().
	Build()

The fluent API uses a copy-on-write pattern where each method returns a new builder instance, allowing safe branching and concurrent construction. Build() returns (*Cluster, error) to surface any validation errors.

Workflow Integration

The Workflow interface abstracts the generation of GitOps-specific resources. Implementations exist for both Flux CD and ArgoCD:

Use the workflow to generate all manifests for a cluster:

// _ "github.com/go-kure/kure/pkg/stack/fluxcd" must be imported to register the provider
wf, err := stack.NewWorkflow("flux")

Layout Generation

The github.com/go-kure/kure/pkg/stack/layout subpackage handles writing generated manifests to disk. Use Workflow.CreateLayoutWithResources to produce a ManifestLayoutResult, then call WriteToDisk to write all files:

ml, _ := wf.CreateLayoutWithResources(cluster, layout.LayoutRules{})
_ = ml.WriteToDisk("./clusters/prod")

The github.com/go-kure/kure/pkg/stack/layout subpackage also exposes lower-level layout primitives following the conventions expected by GitOps tools.

Package References

Nodes can specify a [PackageRef] to indicate that a subtree should be packaged as a separate OCI artifact or kurel package. When undefined, the PackageRef is inherited from the parent node.

Example

Complete example creating a cluster with infrastructure and applications:

// Define the cluster structure
cluster, err := stack.NewClusterBuilder("prod-cluster").
	WithGitOps(&stack.GitOpsConfig{
		Type: "flux",
		Bootstrap: &stack.BootstrapConfig{
			Enabled:     true,
			FluxMode:    "flux-operator",
			FluxVersion: "2.x",            // required in flux-operator mode
			Registry:    "ghcr.io/fluxcd", // required in flux-operator mode
		},
	}).
	WithNode("infrastructure").
		WithBundle("cert-manager").
			WithApplication("cert-manager", certManagerConfig).
			End().
		WithChild("applications").
			WithBundle("web-app").
				WithApplication("frontend", frontendConfig).
				WithApplication("backend", backendConfig).
				End().
			End().
		End().
	Build()

// Generate Flux manifests and write to disk
// (requires: _ "github.com/go-kure/kure/pkg/stack/fluxcd" side-effect import)
wf, _ := stack.NewWorkflow("flux")
ml, _ := wf.CreateLayoutWithResources(cluster, layout.LayoutRules{})
_ = ml.WriteToDisk("./clusters/prod")

Dual Access Pattern (Exported Fields and Getter/Setter Methods)

Several types in this package, notably Cluster and Node, expose their data both as exported struct fields and through getter/setter methods. The methods are intentionally thin wrappers without additional validation, meaning both access paths are functionally equivalent.

This design serves two audiences:

  • Internal and test code benefits from direct field access, which is concise and idiomatic in Go.
  • External library consumers can use getter/setter methods to decouple from the concrete field layout, making it easier to introduce validation or indirection in a future version without breaking callers.

When writing new code inside the kure repository, prefer direct field access. When consuming the stack package as a library, prefer the getter/setter methods. See the Cluster type documentation for details.

Example (ArchitectureValidate)
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/errors"
	"github.com/go-kure/kure/pkg/stack"
)

func main() {
	c := stack.NewCluster("prod", &stack.Node{
		Name:   "apps",
		Bundle: &stack.Bundle{Name: "web", Applications: []*stack.Application{nil}},
	})

	check := func(c *stack.Cluster) error {
		// Validation is a call the caller makes, not a side effect of construction.
		if err := stack.ValidateCluster(c); err != nil {
			return errors.Wrap(err, "cluster is not layoutable")
		}
		return nil
	}
	fmt.Println(check(c))
}
Output:
cluster is not layoutable: bundle "web" at node "apps" failed validation: validation failed for Bundle 'web' field 'applications': application at index 0 is nil
Example (DomainModel)
package main

import (
	"fmt"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/kubernetes"
	"github.com/go-kure/kure/pkg/stack"
	"github.com/go-kure/kure/pkg/stack/layout"
)

// workload is the stack.ApplicationConfig the page's applications use: one
// ConfigMap named after the application.
type workload struct{}

func (workload) Generate(app *stack.Application) ([]*client.Object, error) {
	var obj client.Object = kubernetes.CreateConfigMap(app.Name, app.Namespace)
	return []*client.Object{&obj}, nil
}

var (
	certManagerConfig stack.ApplicationConfig = workload{}
	prometheusConfig  stack.ApplicationConfig = workload{}
	frontendConfig    stack.ApplicationConfig = workload{}
	apiConfig         stack.ApplicationConfig = workload{}
)

// printLayout prints the repository path of every directory in the layout.
func printLayout(ml *layout.ManifestLayout) {
	fmt.Println(ml.FullRepoPath())
	for _, child := range ml.Children {
		printLayout(child)
	}
}

func main() {
	cluster := stack.NewCluster("production", &stack.Node{
		Name: "production",
		Children: []*stack.Node{
			{Name: "infrastructure", Children: []*stack.Node{
				{Name: "cert-manager", Bundle: &stack.Bundle{Name: "cert-manager", Applications: []*stack.Application{
					stack.NewApplication("cert-manager", "cert-manager", certManagerConfig),
				}}},
				{Name: "monitoring", Bundle: &stack.Bundle{Name: "monitoring", Applications: []*stack.Application{
					stack.NewApplication("prometheus", "monitoring", prometheusConfig),
				}}},
			}},
			{Name: "applications", Bundle: &stack.Bundle{Name: "web-apps", Applications: []*stack.Application{
				stack.NewApplication("frontend", "web", frontendConfig),
				stack.NewApplication("api", "web", apiConfig),
			}}},
		},
	})

	rules := layout.DefaultLayoutRules()
	rules.BundleGrouping = layout.GroupByName
	rules.ApplicationGrouping = layout.GroupByName
	ml, err := layout.WalkCluster(cluster, rules)
	if err != nil {
		panic(err)
	}
	printLayout(ml)
}
Output:
production
production/infrastructure
production/infrastructure/cert-manager
production/infrastructure/cert-manager/cert-manager
production/infrastructure/cert-manager/cert-manager/cert-manager
production/infrastructure/monitoring
production/infrastructure/monitoring/monitoring
production/infrastructure/monitoring/monitoring/prometheus
production/applications
production/applications/web-apps
production/applications/web-apps/frontend
production/applications/web-apps/api

Index

Examples

Constants

View Source
const (
	// AnnotationFluxPruneKey is the Flux kustomize-controller annotation key
	// used to control pruning behavior on individual resources.
	AnnotationFluxPruneKey = "kustomize.toolkit.fluxcd.io/prune"
	// AnnotationFluxPruneDisabled is the value that prevents a resource from
	// being pruned during Flux garbage collection.
	AnnotationFluxPruneDisabled = "disabled"
	// AnnotationFluxForceKey is the Flux kustomize-controller annotation key
	// that controls, per resource, whether an immutable-field change is
	// applied by deleting and recreating the resource.
	AnnotationFluxForceKey = "kustomize.toolkit.fluxcd.io/force"
	// AnnotationFluxForceEnabled is the value that allows that recreation.
	AnnotationFluxForceEnabled = "enabled"
)
View Source
const KustomizationNameMaxLength = 63

KustomizationNameMaxLength is the longest name ValidateKustomizationName accepts. A Kustomization is a DNS-1123 subdomain, which Kubernetes allows up to 253 characters, but kustomize-controller writes the Kustomization's name into the label kustomize.toolkit.fluxcd.io/name on every object it applies, and a label value is at most 63 characters: a longer name is admitted by the API server and then fails every apply.

Read in kustomize-controller v1.10.1: the reconciler hands the Kustomization's name to the apply manager as the owner of the objects (internal/controller/kustomization_controller.go:489), and the manager writes it as a label value (github.com/fluxcd/pkg/ssa v0.83.0, manager.go:66-78).

Variables

This section is empty.

Functions

func RegisterArgoWorkflow

func RegisterArgoWorkflow(factory func() Workflow)

RegisterArgoWorkflow registers the ArgoCD workflow factory. This is called by the argocd package during init.

func RegisterFluxWorkflow

func RegisterFluxWorkflow(factory func() Workflow)

RegisterFluxWorkflow registers the Flux workflow factory. This is called by the fluxcd package during init.

func ValidateCluster

func ValidateCluster(c *Cluster) error

ValidateCluster performs cluster-level structural validation that cannot be expressed on a single Bundle alone. It is the single validation entry point shared by the resource generator, layout walker, layout integrator, and the v1alpha1 converter round-trip.

It enforces:

  1. The Node tree has no cycle: a Node reached again from one of its own descendants is rejected, naming the node where the cycle closes.
  2. Every Node bundle passes Bundle.Validate (which recursively validates umbrella Children subtrees including cycle detection and the name of each bundle), and every node name passes ValidateDirectoryName, under every layout grouping: the name is a segment of the node's path. A root node without a name is the one exception: it adds no segment. A node's NamedDependsOn holds no empty and no repeated entry, as a bundle's (validateNodeNamedDependsOn).
  3. Disjointness: a bundle pointer appearing inside any umbrella Children subtree must NOT also be attached as the Bundle of any stack.Node.
  4. No umbrella child pointer is shared by two distinct umbrella parents.
  5. Multi-package rejection: if any Node has a PackageRef set and any bundle in the cluster has umbrella Children, the cluster is rejected. Cross-package umbrella semantics are follow-up work.

Before the bundles are validated (1), it checks the DependsOn bundles that are copies of the cluster's bundles, which Bundle.Validate cannot tell from any other bundle (see validateDependencyCopies): a copy that sets another KustomizationName than the bundle it stands for is refused, and so is one that stands for a bundle whose Kustomization is also in NamedDependsOn.

ValidateCluster is safe to call with a nil cluster or a cluster with no root node (it returns nil in both cases).

func ValidateDirectoryName

func ValidateDirectoryName(name string) error

ValidateDirectoryName reports whether name can be the name of one directory in a rendered tree: a single path segment. It refuses an empty name, "." and "..", a name containing a path separator, and a name containing a NUL byte. Both "/" and "\" count on every platform: the tree is joined with path/filepath, which reads "\" as a separator on Windows, so a name such as `..\outside` would otherwise leave the directory it is joined under. A NUL byte is refused because a directory with one in its name cannot be created, so the write would fail after validation had passed. Characters that only some file systems refuse are not checked.

The same rule holds for a node name where no directory is made from it: a node name is a segment of the node's path in the model (Node.GetPath), which joins the names with "/".

func ValidateKustomizationName

func ValidateKustomizationName(name string) error

ValidateKustomizationName reports whether name can be the metadata.name of a Flux Kustomization that kustomize-controller can reconcile: a DNS-1123 subdomain of at most KustomizationNameMaxLength characters. It does not shorten or rewrite name; the caller chooses a valid one. The one name kure shortens is one it composes itself, the Flux workflow's "<unit>-<layout name>" default for a layout's own Kustomization, before it is checked here.

func ValidateServiceAccountName

func ValidateServiceAccountName(name string) error

ValidateServiceAccountName reports whether name can be a bundle's ServiceAccountName: the name of a Kubernetes ServiceAccount, which the API server accepts as a DNS-1123 subdomain. Flux's Kustomization does not check spec.serviceAccountName itself, so a name no ServiceAccount can have is admitted there and fails only when the controller impersonates it.

Types

type Application

type Application struct {
	Name      string
	Namespace string
	Config    ApplicationConfig
	// Delivery states how the delivery engine should treat this application's
	// objects. The zero value asks for nothing.
	Delivery DeliveryIntent
}

Application represents a deployable application with a configuration.

func NewApplication

func NewApplication(name, namespace string, cfg ApplicationConfig) *Application

NewApplication constructs an Application with the provided parameters.

func (*Application) Generate

func (a *Application) Generate() ([]*client.Object, error)

Generate returns the resources for this application. If the Config implements the Validator interface, Validate() is called before Generate(). A validation error stops generation immediately. Both run on every call: nothing is memoized, and no LayoutAugmenter runs (only a walk augments).

Example
package main

import (
	"fmt"
	"strconv"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/errors"
	"github.com/go-kure/kure/pkg/kubernetes"
	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

// myConfig is the ApplicationConfig the README's "Optional Validation"
// section declares; the other examples use it too.
type myConfig struct{ Port int }

func (c *myConfig) Validate() error {
	if c.Port <= 0 {
		return errors.New("port must be positive")
	}
	return nil
}

func (c *myConfig) Generate(app *stack.Application) ([]*client.Object, error) {

	cm := kubernetes.CreateConfigMap(app.Name, app.Namespace)
	cm.Data = map[string]string{"port": strconv.Itoa(c.Port)}
	var obj client.Object = cm
	return []*client.Object{&obj}, nil
}

func main() {
	prometheusConfig := &myConfig{Port: 9090}

	app := stack.NewApplication("prometheus", "monitoring", prometheusConfig)
	resources, err := app.Generate()
	if err != nil {
		panic(err)
	}
	fmt.Println(len(resources), (*resources[0]).GetName())
}
Output:
1 prometheus

func (*Application) SetConfig

func (a *Application) SetConfig(cfg ApplicationConfig)

SetConfig replaces the application configuration.

func (*Application) SetName

func (a *Application) SetName(name string)

SetName updates the application name.

func (*Application) SetNamespace

func (a *Application) SetNamespace(ns string)

SetNamespace updates the target namespace.

type ApplicationConfig

type ApplicationConfig interface {
	Generate(*Application) ([]*client.Object, error)
}

ApplicationConfig describes the behaviour of specific application types.

What Generate returns belongs to the caller from the moment it returns: the slice, every object it points to, and every map, slice and pointer those objects hold. kure writes to the objects (Bundle.Generate adds the bundle's labels and annotations an object lacks; the Flux integrator adds an application's delivery annotations), and a caller that holds the layout may write into any of it. An implementation therefore never returns an object, or anything inside one, that it keeps or has returned before: it builds each result fresh, or returns a deep copy of a cached one.

Every call is independent of the earlier ones, failed ones included. A walk (layout.WalkCluster, layout.WalkClusterByPackage) calls Generate once for each application it renders, every workflow entry point that renders applications walks once, and nothing memoizes across calls. A walk in which one call fails returns no layout. kure never calls Generate concurrently; whether a config memoizes and whether it is safe for concurrent use are separate properties.

The optional interfaces Validator, layout.LayoutAugmenter and layout.LayoutIntentAugmenter are found by type assertion on the config itself. A wrapper that embeds the ApplicationConfig interface hides them, silently; one that embeds the concrete type, or forwards each of them, keeps them.

type BootstrapConfig

type BootstrapConfig struct {
	// Common fields
	Enabled bool `yaml:"enabled"`

	// Flux-specific
	FluxMode string `yaml:"fluxMode,omitempty"` // "flux-operator" (default) or "gotk" (legacy)
	// FluxVersion selects the Flux release. In gotk mode, empty or the vendored
	// fluxcd.GotkVersion builds offline from the bundle kure ships; any other
	// value downloads manifests at generation time: the named release for a
	// "vX.Y.Z" value, and the latest release for anything else ("latest", or a
	// version without its "v"), as upstream flux2 resolves it. In
	// flux-operator mode it is the FluxInstance
	// distribution version, and required: an empty value is an error.
	FluxVersion string   `yaml:"fluxVersion,omitempty"`
	Components  []string `yaml:"components,omitempty"`
	// Registry is the container registry the Flux images are pulled from. In
	// gotk mode empty means the upstream registry. In flux-operator mode it is
	// the FluxInstance distribution registry, and required: an empty value is an
	// error, and no default is filled in. It does not move the flux-operator
	// Deployment's own image; see ImagePullSecret.
	Registry string `yaml:"registry,omitempty"`
	// ImagePullSecret names the Kubernetes Secret used to pull the Flux
	// controller images, in both modes: in gotk mode it is the install
	// option that adds the secret to every controller Deployment, in
	// flux-operator mode the FluxInstance distribution's imagePullSecret.
	// Empty sets none. It is for the controller images only, not a
	// credential for the sync source.
	//
	// In flux-operator mode neither Registry nor ImagePullSecret reaches the
	// flux-operator Deployment in the vendored install bundle: its image is
	// pulled as upstream ships it, from its own registry and with no pull
	// secret.
	ImagePullSecret string `yaml:"imagePullSecret,omitempty"`

	// Source configuration
	SourceKind string `yaml:"sourceKind,omitempty"` // "GitRepository" or "OCIRepository"
	SourceURL  string `yaml:"sourceURL,omitempty"`  // OCI/Git repository URL
	SourceRef  string `yaml:"sourceRef,omitempty"`  // Tag/branch/ref

	// SourceSemVer selects the OCI tag by a semver range, such as ">=1.0.0
	// <2.0.0", instead of the fixed tag SourceRef names: ref.semver on the gotk
	// OCIRepository. A FluxInstance sync takes only a tag, so in flux-operator
	// mode it is a spec.kustomize patch replacing spec.ref on the OCIRepository
	// the operator generates for the sync. It applies to an OCIRepository
	// source only, and only with SourceURL set; it is an error with a
	// GitRepository source, without SourceURL, with a SourceRef (the range and
	// an explicit tag cannot both choose the revision) and when it does not
	// parse as a range. Empty leaves the ref to SourceRef as before.
	SourceSemVer string `yaml:"sourceSemVer,omitempty"`

	// Source access. These options apply to an OCIRepository source only, and
	// only with SourceURL set; any of them with a GitRepository source or
	// without SourceURL is an error. Unset, the source is generated as before.
	//
	// SourceSecretRef names the Secret, of type kubernetes.io/dockerconfigjson,
	// holding the registry credentials for the source: spec.secretRef on the
	// gotk OCIRepository, spec.sync.pullSecret on the FluxInstance. It is not
	// ImagePullSecret, which is for the Flux controller images.
	SourceSecretRef string `yaml:"sourceSecretRef,omitempty"`
	// SourceProvider is the OIDC provider the source authenticates with: one
	// of generic, aws, azure and gcp. spec.provider on the gotk OCIRepository,
	// spec.sync.provider on the FluxInstance.
	SourceProvider string `yaml:"sourceProvider,omitempty"`
	// SourceInsecure lets the source pull from a plain-HTTP registry:
	// spec.insecure on the gotk OCIRepository. A FluxInstance sync has no such
	// field, so in flux-operator mode it is a spec.kustomize patch setting
	// spec.insecure on the OCIRepository the operator generates for the sync.
	SourceInsecure bool `yaml:"sourceInsecure,omitempty"`
	// SourceVerify, when set, makes the source verify the OCI artifact's
	// signature before Flux applies it: spec.verify on the gotk OCIRepository.
	// A FluxInstance sync has no such field, so in flux-operator mode it is a
	// spec.kustomize patch adding spec.verify to the OCIRepository the
	// operator generates for the sync. Its provider must be cosign or
	// notation, and each identity's issuer and subject non-empty Go regular
	// expressions holding no DEL, C1 control or noncharacter U+FFFE or U+FFFF
	// literally (an escape such as \x{85} matches one); anything else is an
	// error.
	SourceVerify *SourceVerification `yaml:"sourceVerify,omitempty"`

	// SyncName names the bootstrap source and Kustomization in both modes: in
	// flux-operator mode the ones the FluxInstance sync creates
	// (spec.sync.name), in gotk mode the OCIRepository or GitRepository and the
	// Kustomization kure emits, whose sourceRef follows. It has no effect
	// without SourceURL, because no source is emitted then in either mode.
	// Empty keeps each mode's names: the operator names both after the
	// FluxInstance's namespace; gotk names the source after the root node and
	// the Kustomization after the generator's BootstrapName. The CRD caps it
	// at 63 characters and makes it immutable once set, so changing it means
	// recreating the FluxInstance; in gotk mode it means new objects under the
	// new name, and the gotk generator refuses a value that is not a valid Flux
	// Kustomization name (ValidateKustomizationName).
	SyncName string `yaml:"syncName,omitempty"`

	// Prune controls garbage collection on the bootstrap Kustomization. Set,
	// it reaches that Kustomization in both modes: spec.prune in gotk mode,
	// a spec.kustomize patch setting spec.prune on the sync Kustomization
	// the operator generates in flux-operator mode (go-kure/kure#1088).
	// Unset keeps each mode's default. In gotk mode that is prune: false: the
	// upstream field is required with no omitempty, so it cannot be left out
	// of the YAML, and an unset input is not a request for destructive
	// garbage collection. In flux-operator mode it is the operator's
	// prune: true.
	Prune *bool `yaml:"prune,omitempty"`

	// Labels are set on the bootstrap source and Kustomization in both modes:
	// metadata.labels on the OCIRepository or GitRepository and the
	// Kustomization kure emits in gotk mode, and in flux-operator mode two
	// spec.kustomize patches adding metadata.labels to the source and the
	// Kustomization the operator generates for the sync. Like SyncName it has
	// no effect without SourceURL, because no source is emitted then in either
	// mode; the gotk Kustomization emitted without one carries no labels.
	// Empty or nil keeps the output as before. The map is copied, not
	// shared.
	//
	// Every key must be a qualified name and every value a label value, as
	// Kubernetes takes them, and the keys a Flux controller stamps on these
	// objects, overwriting a value set here, are refused in both modes:
	//   - app.kubernetes.io/managed-by, app.kubernetes.io/instance,
	//     app.kubernetes.io/version and app.kubernetes.io/part-of, which
	//     flux-operator's LabelTransformer sets on every object it builds
	//     after the FluxInstance patches;
	//   - fluxcd.controlplane.io/name and fluxcd.controlplane.io/namespace,
	//     flux-operator's owner labels on every object it applies;
	//   - kustomize.toolkit.fluxcd.io/name and
	//     kustomize.toolkit.fluxcd.io/namespace, kustomize-controller's owner
	//     labels on every object a Kustomization applies, the gotk source and
	//     Kustomization included when they are written into the tree the
	//     bootstrap Kustomization applies.
	//
	// Anything else is an error, with or without SourceURL.
	Labels map[string]string `yaml:"labels,omitempty"`

	// ArgoCD-specific (mock for now)
	ArgoCDVersion   string `yaml:"argoCDVersion,omitempty"`
	ArgoCDNamespace string `yaml:"argoCDNamespace,omitempty"`
}

BootstrapConfig defines the bootstrap configuration for GitOps tools

type Bundle

type Bundle struct {
	// Name identifies the application set.
	Name string
	// KustomizationName names the Flux Kustomization generated for the
	// bundle, and with it every reference to that Kustomization: dependsOn
	// entries of bundles that depend on this one, and an umbrella's health
	// check on this child. Empty means Name. Under the ArgoCD workflow the
	// same value names the Application and its spec.dependencies entries.
	// Name stays the bundle's identity and, unless DirName is set, its
	// directory; UnitName returns the name in effect. A value set here must
	// be a DNS-1123 subdomain (Validate); the Flux workflow also limits the
	// name in effect to 63 characters (ValidateKustomizationName).
	KustomizationName string
	// DirName names the bundle's directory in the rendered tree, wherever the
	// bundle's name becomes one. Empty means Name. That is the case for an
	// umbrella child, for a node's bundle under the layout rule
	// BundleGrouping GroupByName, and for the root node's bundle under
	// GroupFlat, which has a directory inside the root node's. Under
	// GroupFlat below the root a node's bundle is rendered in its node's
	// directory, which the node names, and DirName has no effect on it. When
	// a flat NodeGrouping merges several bundles into the root node they
	// share one directory there: it takes the first merged bundle's DirName,
	// or its Name without one, and a DirName on a later bundle of that
	// directory has no effect.
	//
	// The path the bundle's Flux Kustomization or ArgoCD Application applies
	// follows the directory; that object's name does not (see
	// KustomizationName), and Name stays the bundle's identity. A value set
	// here must be one path segment (ValidateDirectoryName, checked by
	// Validate): not "." or "..", and without "/", "\" or a NUL byte. It is
	// no object name, so it need not be a DNS-1123 subdomain.
	DirName string
	// ParentPath is the hierarchical path to the parent bundle (e.g., "cluster/infrastructure")
	// Empty for root bundles. This avoids circular references while maintaining hierarchy.
	ParentPath string
	// DependsOn lists other bundles this bundle depends on
	DependsOn []*Bundle
	// NamedDependsOn lists names of kustomizations this bundle depends on, by name.
	// Unlike DependsOn, names need not resolve to in-scope Bundle objects. A
	// name is a Kustomization's: for a bundle that sets KustomizationName it
	// is that value, not the bundle's Name.
	// Both fields are merged into Kustomization.Spec.DependsOn.
	NamedDependsOn []string
	// Children holds bundles whose readiness this bundle aggregates. When
	// non-empty, this bundle acts as an umbrella: with Wait unset or false the
	// Flux engine writes a health check per child, so the umbrella is Ready
	// only when all Children are. With Wait true it writes none, and the
	// umbrella's wait covers the children only where its build applies their
	// Flux Kustomization CRs: under the integrated placements, which render
	// them into this bundle's directory, not under FluxSeparate (pkg/stack/fluxcd
	// README, "Umbrella Bundles"). Children bundles must be
	// standalone — they cannot simultaneously be the Bundle of a stack.Node.
	Children []*Bundle
	// Interval controls how often Flux reconciles the bundle. It must parse as
	// a Go duration (e.g. "10m"); empty means the generator's default.
	// Validate rejects any other value.
	Interval string
	// SourceRef specifies the source for the bundle.
	SourceRef *SourceRef
	// Applications holds the Kubernetes objects that belong to the application.
	Applications []*Application
	// Labels are the labels of what is generated for the bundle. The Flux
	// workflow sets them on the bundle's Kustomization and, under
	// FluxIntegratedPerLayout, on the Kustomization of each application of the
	// bundle that has a directory of its own and of each layout below it; the
	// ArgoCD workflow sets them on the bundle's Application. Generate adds
	// them to the objects of the bundle's applications, an object's own value
	// winning. A tree walked from a cluster is not built with Generate: the
	// walker generates each application on its own, so no object in such a
	// tree gets them.
	Labels map[string]string
	// Annotations are the annotations of what is generated for the bundle: on
	// the same Flux Kustomizations as Labels, and added by Generate to the
	// objects of the bundle's applications, an object's own value winning. The
	// ArgoCD workflow does not read them. As for Labels, no object in a tree
	// walked from a cluster gets them.
	Annotations map[string]string
	// Description provides a human-readable description of the bundle.
	Description string
	// Prune enables garbage collection of resources removed from the bundle.
	Prune *bool
	// Wait causes the Kustomization to wait for resources to become ready.
	Wait *bool
	// Timeout is the maximum duration to wait for resources to be ready (e.g. "5m").
	// It must parse as a Go duration; empty leaves the field unset.
	Timeout string
	// RetryInterval is the interval between retry attempts for failed reconciliations (e.g. "2m").
	// It must parse as a Go duration; empty leaves the field unset.
	RetryInterval string
	// Force causes Flux to re-apply resources even if there are no detected changes.
	Force *bool
	// Suspend disables reconciliation when true. Set to false to resume.
	Suspend *bool
	// HealthChecks lists resources whose health is monitored during reconciliation.
	// When specified, the Kustomization waits for these resources to become ready.
	HealthChecks []HealthCheck
	// Patches lists strategic merge or JSON patches to apply to resources after
	// kustomize build. Each patch targets resources matching its selector.
	Patches []Patch
	// PostBuild configures variable substitution performed after kustomize build.
	PostBuild *PostBuild
	// ServiceAccountName is the service account the Flux workflow has
	// kustomize-controller impersonate when it applies the bundle: it is
	// written to spec.serviceAccountName of the bundle's Kustomization and,
	// under FluxIntegratedPerLayout, of the Kustomization of each application
	// of the bundle that has a directory of its own and of each layout below
	// it. Empty writes nothing, and the controller applies with its own
	// identity, or with the default service account it is started with
	// (--default-service-account), if any. Flux looks the account up in the
	// namespace of the Kustomization, the generator's DefaultNamespace;
	// creating the account and its RBAC is the caller's. An umbrella's value
	// is not passed to its Children: each bundle carries its own. A value
	// set here must be a DNS-1123 subdomain, the rule Kubernetes sets for a
	// service account name (ValidateServiceAccountName, checked by Validate).
	// The ArgoCD workflow does not read it.
	ServiceAccountName string
	// contains filtered or unexported fields
}

Bundle represents a unit of deployment, typically the resources that are reconciled by a single Flux Kustomization.

func NewBundle

func NewBundle(name string, resources []*Application, labels map[string]string) (*Bundle, error)

NewBundle constructs a Bundle with the given name, resources and labels. The labels map is copied (a nil map stays nil), so editing it after the call leaves the bundle as it was built. It returns an error if validation fails.

Example
package main

import (
	"fmt"
	"strconv"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/errors"
	"github.com/go-kure/kure/pkg/kubernetes"
	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

// myConfig is the ApplicationConfig the README's "Optional Validation"
// section declares; the other examples use it too.
type myConfig struct{ Port int }

func (c *myConfig) Validate() error {
	if c.Port <= 0 {
		return errors.New("port must be positive")
	}
	return nil
}

func (c *myConfig) Generate(app *stack.Application) ([]*client.Object, error) {

	cm := kubernetes.CreateConfigMap(app.Name, app.Namespace)
	cm.Data = map[string]string{"port": strconv.Itoa(c.Port)}
	var obj client.Object = cm
	return []*client.Object{&obj}, nil
}

func main() {
	apps := []*stack.Application{
		stack.NewApplication("prometheus", "monitoring", &myConfig{Port: 9090}),
	}
	labels := map[string]string{"team": "platform"}
	certManagerBundle := &stack.Bundle{Name: "cert-manager"}

	bundle, err := stack.NewBundle("monitoring", apps, labels)
	if err != nil {
		panic(err)
	}
	// Pointer-based — when you hold the bundle object:
	bundle.DependsOn = []*stack.Bundle{certManagerBundle}
	// Name-based — when you only know the name (e.g. a hook-phase bundle):
	bundle.NamedDependsOn = []string{"cert-manager-pre-install"}
	bundle.Interval = "10m"

	if err := bundle.Validate(); err != nil {
		panic(err)
	}
	fmt.Println(bundle.Name, bundle.DependsOn[0].Name, bundle.NamedDependsOn, bundle.Interval)
}
Output:
monitoring cert-manager [cert-manager-pre-install] 10m

func (*Bundle) Generate

func (a *Bundle) Generate() ([]*client.Object, error)

Generate returns the objects of every application in the bundle, in order, with the bundle's labels and annotations added to each object; an object's own value for a key wins, and its annotations stay as written, also a non-string value on an unstructured object. Where the bundle sets labels, each object is given a new labels map; where it sets annotations, each object that lacks one of them is given a new annotations map, and one that carries them all keeps its own. The map its config returned is not written, so a map the config also uses elsewhere (a selector, a pod template's labels) keeps its value, and a new map is shared with neither the bundle nor another object. A nil entry, or one holding no object (a nil client.Object, or a nil pointer of an object type such as (*corev1.ConfigMap)(nil)), is returned as it is and gets nothing.

func (*Bundle) GetParent

func (b *Bundle) GetParent() *Bundle

GetParent returns the runtime parent reference (may be nil).

func (*Bundle) GetParentPath

func (b *Bundle) GetParentPath() string

GetParentPath returns the hierarchical path to the parent bundle.

func (*Bundle) GetPath

func (b *Bundle) GetPath() string

GetPath returns the full hierarchical path of this bundle.

func (*Bundle) InitializePathMap

func (b *Bundle) InitializePathMap(allBundles []*Bundle)

InitializePathMap builds the runtime path lookup map for efficient hierarchy navigation. This should be called on the root bundle after the tree structure is complete.

func (*Bundle) InitializeUmbrella

func (a *Bundle) InitializeUmbrella()

InitializeUmbrella walks the umbrella Children subtree and sets each child's runtime parent pointer (via SetParent) so that code can walk upward from any child (GetParent). Idempotent and safe to call multiple times.

func (*Bundle) IsUmbrella

func (a *Bundle) IsUmbrella() bool

IsUmbrella reports whether the bundle acts as an umbrella (has Children that contribute their Flux Kustomizations into this bundle's directory).

func (*Bundle) SetParent

func (b *Bundle) SetParent(parent *Bundle)

SetParent sets the parent bundle and updates the ParentPath accordingly. This method maintains both the serializable path and runtime reference.

func (*Bundle) UnitName

func (a *Bundle) UnitName() string

UnitName returns the name of the reconciliation unit generated for the bundle, the object the delivery engine applies it with: a Flux Kustomization, or an ArgoCD Application. It is KustomizationName when that is set and Name otherwise. Bundles a layout grouping merges into one directory share one unit, named after the first of them; the layout's origin index resolves that (layout.OriginIndex.UnitName).

func (*Bundle) Validate

func (a *Bundle) Validate() error

Validate performs basic sanity checks on the Bundle. When the bundle has umbrella Children, Validate recursively walks the child subtree checking for cycles, duplicate names, and DependsOn contradictions.

type BundleBuilder

type BundleBuilder interface {
	WithApplication(name string, appConfig ApplicationConfig) BundleBuilder
	WithDependency(bundle *Bundle) BundleBuilder
	WithSourceRef(sourceRef *SourceRef) BundleBuilder
	End() NodeBuilder
	Build() (*Cluster, error)
}

BundleBuilder provides fluent interface for building Bundle configurations.

type Cluster

type Cluster struct {
	Name   string        `yaml:"name"`
	Node   *Node         `yaml:"node,omitempty"`
	GitOps *GitOpsConfig `yaml:"gitops,omitempty"`
}

Cluster describes a cluster configuration. A cluster configuration is a set of configurations that are packaged in one or more package units.

Dual Access Pattern

Cluster exposes its fields (Name, Node, GitOps) as exported struct fields and also provides getter/setter methods (GetName/SetName, GetNode/SetNode, GetGitOps/SetGitOps). The getters and setters are thin wrappers that do not add validation; both access paths read and write the same underlying fields.

This dual access pattern exists intentionally:

  • Exported fields allow direct, concise access that is idiomatic in Go, particularly useful in tests, internal code, and YAML serialization/deserialization (struct tags operate on exported fields).
  • Getter/setter methods provide an encapsulated API surface for library consumers who may prefer method-based access or who want to program against a future interface without depending on concrete field layout.

Guidance for New Code

Within the kure codebase (tests, internal packages, CLI commands), prefer direct field access for brevity:

c.Name = "prod"
fmt.Println(c.Node)

When writing code that consumes the stack package as an external library, prefer the getter/setter methods so that any future validation or indirection can be introduced without breaking callers:

c.SetName("prod")
node := c.GetNode()
Example
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/stack"
)

func main() {
	cluster := &stack.Cluster{
		Name: "prod",
		Node: &stack.Node{Name: "apps"},
	}
	fmt.Println(cluster.Name, cluster.Node.Name)
}
Output:
prod apps

func NewCluster

func NewCluster(name string, tree *Node) *Cluster

NewCluster creates a Cluster with the provided metadata.

Example
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

func main() {
	rootNode := &stack.Node{Name: "flux-system"}

	cluster := stack.NewCluster("production", rootNode)
	cluster.SetGitOps(&stack.GitOpsConfig{
		Type: "flux",
	})
	fmt.Println(cluster.GetName(), cluster.GetNode().Name, cluster.GetGitOps().Type)
}
Output:
production flux-system flux

func (*Cluster) GetGitOps

func (c *Cluster) GetGitOps() *GitOpsConfig

func (*Cluster) GetName

func (c *Cluster) GetName() string

GetName Helper getters.

func (*Cluster) GetNode

func (c *Cluster) GetNode() *Node

func (*Cluster) SetGitOps

func (c *Cluster) SetGitOps(g *GitOpsConfig)

func (*Cluster) SetName

func (c *Cluster) SetName(n string)

SetName Setters for metadata fields.

func (*Cluster) SetNode

func (c *Cluster) SetNode(t *Node)

type ClusterBuilder

type ClusterBuilder interface {
	WithNode(name string) NodeBuilder
	WithGitOps(gitops *GitOpsConfig) ClusterBuilder
	Build() (*Cluster, error)
}

ClusterBuilder provides fluent interface for building Cluster configurations.

func NewClusterBuilder

func NewClusterBuilder(name string) ClusterBuilder

NewClusterBuilder creates a new fluent cluster builder.

Example
package main

import (
	"fmt"
	"strconv"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/errors"
	"github.com/go-kure/kure/pkg/kubernetes"
	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

// myConfig is the ApplicationConfig the README's "Optional Validation"
// section declares; the other examples use it too.
type myConfig struct{ Port int }

func (c *myConfig) Validate() error {
	if c.Port <= 0 {
		return errors.New("port must be positive")
	}
	return nil
}

func (c *myConfig) Generate(app *stack.Application) ([]*client.Object, error) {

	cm := kubernetes.CreateConfigMap(app.Name, app.Namespace)
	cm.Data = map[string]string{"port": strconv.Itoa(c.Port)}
	var obj client.Object = cm
	return []*client.Object{&obj}, nil
}

func main() {
	appConfig := &myConfig{Port: 9090}

	cluster, err := stack.NewClusterBuilder("production").
		WithNode("infrastructure").
		WithBundle("monitoring").
		WithApplication("prometheus", appConfig).
		End().
		End().
		Build()
	if err != nil {
		panic(err)
	}
	fmt.Println(cluster.Name, cluster.Node.Name, cluster.Node.Bundle.Name)
}
Output:
production infrastructure monitoring

type DeliveryIntent

type DeliveryIntent struct {
	// PruneProtection keeps the application's objects in the cluster when
	// they are removed from the source.
	PruneProtection bool
	// ForceReplace allows the application's objects to be deleted and
	// recreated when a change touches an immutable field.
	ForceReplace bool
}

DeliveryIntent is what an application asks of the engine that delivers its objects, stated without naming the engine. The workflow that renders the application maps it its own way: the Flux workflow sets Flux's per-object annotations (see the fluxcd package); a workflow with no mapping refuses a set intent rather than dropping it, and so does the Flux workflow's GenerateFromCluster, which walks the cluster itself and returns none of the application's objects.

func (DeliveryIntent) IsZero

func (d DeliveryIntent) IsZero() bool

IsZero reports whether the intent asks for nothing.

type GitOpsConfig

type GitOpsConfig struct {
	Type      string           `yaml:"type"` // "flux" or "argocd"
	Bootstrap *BootstrapConfig `yaml:"bootstrap,omitempty"`
}

GitOpsConfig defines the GitOps tool configuration for the cluster

type HealthCheck

type HealthCheck struct {
	// APIVersion of the resource (e.g. "apps/v1", "helm.toolkit.fluxcd.io/v2").
	APIVersion string
	// Kind of the resource (e.g. "Deployment", "HelmRelease").
	Kind string
	// Name of the resource.
	Name string
	// Namespace of the resource. When empty, defaults to the Kustomization namespace.
	Namespace string
}

HealthCheck defines a resource to be monitored for health during reconciliation.

Example
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

func main() {
	bundle := &stack.Bundle{Name: "web"}

	bundle.HealthChecks = []stack.HealthCheck{
		{APIVersion: "apps/v1", Kind: "Deployment", Name: "web", Namespace: "default"},
	}
	fmt.Println(bundle.HealthChecks[0].Kind, bundle.HealthChecks[0].Name)
}
Output:
Deployment web

type LayoutRulesProvider

type LayoutRulesProvider interface {
	Validate() error
}

LayoutRulesProvider is the interface for layout configuration passed to GenerateFromCluster, CreateLayoutWithResources and GenerateBootstrap. The concrete implementation is layout.LayoutRules from pkg/stack/layout. Defined here to avoid an import cycle between pkg/stack and pkg/stack/layout.

type ManifestLayoutResult

type ManifestLayoutResult interface {
	WriteToDisk(basePath string) error
	FullRepoPath() string
}

ManifestLayoutResult is the interface for layout results returned by CreateLayoutWithResources. The concrete implementation is *layout.ManifestLayout from pkg/stack/layout. Callers that need the full concrete type should type-assert: ml, ok := result.(*layout.ManifestLayout).

type Node

type Node struct {
	// Name identifies the application set.
	Name string `yaml:"name"`
	// ParentPath is the hierarchical path to the parent node (e.g., "cluster/infrastructure")
	// Empty for root nodes. This avoids circular references while maintaining hierarchy.
	ParentPath string `yaml:"parentPath,omitempty"`
	// Children list child bundles
	Children []*Node `yaml:"children,omitempty"`
	// PackageRef identifies in which package the tree of resources get bundled together
	// If undefined, the PackageRef of the parent is inherited
	PackageRef *schema.GroupVersionKind `yaml:"packageref,omitempty"`
	// Bundle holds the applications that get deployed on this level
	Bundle *Bundle `yaml:"bundle,omitempty"`
	// KustomizationName names the node's own Flux Kustomization. A node has
	// one only under the layout rule FluxPlacement FluxIntegratedPerLayout,
	// and only when its directory renders no bundle: a group of nodes, or a
	// node above its bundle's own directory (BundleGrouping GroupByName).
	// Empty means the derived name, the node's directory path with "/"
	// replaced by "-" and "-node" appended. Set on any other node (one whose
	// directory renders its bundle, one NodeGrouping GroupFlat merges into
	// its parent, the node whose directory is the top of the written tree)
	// or under another placement, the field is refused, not ignored; so are
	// DependsOn and NamedDependsOn. The name in effect, set or derived, must
	// be one Flux can reconcile (ValidateKustomizationName): the Flux
	// workflow refuses any other where it creates the Kustomization and does
	// not shorten a derived name, so one that is too long is fixed by
	// setting this field.
	//
	// The layout walker copies this field and NamedDependsOn onto the node's
	// layout, and the Kustomization is built from the layout. Set them before
	// the walk: a name or an entry the node has and its layout does not
	// carry is refused, not ignored.
	KustomizationName string `yaml:"kustomizationName,omitempty"`
	// DependsOn lists nodes whose Kustomizations must be ready before this
	// node's is applied. Each is written into spec.dependsOn under the
	// target's Kustomization name in effect: its KustomizationName, or the
	// derived name. A target without a Kustomization of its own is refused.
	DependsOn []*Node `yaml:"-"`
	// NamedDependsOn lists Kustomizations this node's depends on, by name.
	// The names are written into spec.dependsOn as given, after DependsOn.
	// An entry is a caller-supplied reference: it need not belong to a node
	// of this cluster, and its value is not checked. An empty or a repeated
	// entry is refused (ValidateCluster), and so is an entry that names the
	// Kustomization of a node in DependsOn.
	NamedDependsOn []string `yaml:"namedDependsOn,omitempty"`
	// contains filtered or unexported fields
}

Node represents a hierarchic structure holding all deployment bundles each tree has a list of children, which can be a deployment, or a subtree It could match a kubernetes cluster's full configuration, or it could be just a part of that, when parts are e.g. packaged in different OCI artifacts Tree's with a common PackageRef are packaged together

Example
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

func main() {
	childNode := &stack.Node{Name: "cert-manager"}
	monitoringBundle := &stack.Bundle{Name: "monitoring"}

	node := &stack.Node{
		Name:     "infrastructure",
		Children: []*stack.Node{childNode},
		Bundle:   monitoringBundle,
	}
	fmt.Println(node.Name, node.Children[0].Name, node.Bundle.Name)
}
Output:
infrastructure cert-manager monitoring

func (*Node) GetBundle

func (n *Node) GetBundle() *Bundle

func (*Node) GetChildren

func (n *Node) GetChildren() []*Node

func (*Node) GetName

func (n *Node) GetName() string

func (*Node) GetPackageRef

func (n *Node) GetPackageRef() *schema.GroupVersionKind

func (*Node) GetParent

func (n *Node) GetParent() *Node

func (*Node) GetParentPath

func (n *Node) GetParentPath() string

func (*Node) GetPath

func (n *Node) GetPath() string

GetPath returns the full hierarchical path of this node.

func (*Node) InitializePathMap

func (n *Node) InitializePathMap()

InitializePathMap builds the runtime path lookup map for efficient hierarchy navigation. This should be called on the root node after the tree structure is complete.

func (*Node) SetBundle

func (n *Node) SetBundle(bundle *Bundle)

func (*Node) SetChildren

func (n *Node) SetChildren(children []*Node)

func (*Node) SetName

func (n *Node) SetName(name string)

func (*Node) SetPackageRef

func (n *Node) SetPackageRef(ref *schema.GroupVersionKind)

func (*Node) SetParent

func (n *Node) SetParent(parent *Node)

SetParent sets the parent node and updates the ParentPath accordingly. This method maintains both the serializable path and runtime reference.

func (*Node) SetParentPath

func (n *Node) SetParentPath(path string)

type NodeBuilder

type NodeBuilder interface {
	WithChild(name string) NodeBuilder
	WithBundle(name string) BundleBuilder
	WithPackageRef(ref *schema.GroupVersionKind) NodeBuilder
	End() ClusterBuilder
	Build() (*Cluster, error)
}

NodeBuilder provides fluent interface for building Node configurations.

type OIDCIdentityMatch

type OIDCIdentityMatch struct {
	Issuer  string `yaml:"issuer"`
	Subject string `yaml:"subject"`
}

OIDCIdentityMatch matches a keyless cosign signature's certificate: Issuer and Subject are Go regular expressions, both required. A signature is verified when any one match in the list holds.

type Patch

type Patch struct {
	// Patch is the patch content in strategic merge patch or JSON patch format.
	Patch string
	// Target selects which resources the patch applies to.
	// When nil the patch applies to all resources.
	Target *PatchSelector
}

Patch defines a strategic merge or JSON patch applied to resources after kustomize build.

type PatchSelector

type PatchSelector struct {
	// Group of the target resource (e.g. "apps").
	Group string
	// Version of the target resource (e.g. "v1").
	Version string
	// Kind of the target resource (e.g. "Deployment").
	Kind string
	// Name of the target resource.
	Name string
	// Namespace of the target resource.
	Namespace string
	// LabelSelector is a label selector expression.
	LabelSelector string
	// AnnotationSelector is an annotation selector expression.
	AnnotationSelector string
}

PatchSelector selects Kubernetes resources by GVK and metadata filters.

type PostBuild

type PostBuild struct {
	// Substitute contains inline key-value substitution variables.
	// Values are substituted for ${VAR} occurrences in manifests.
	Substitute map[string]string
	// SubstituteFrom lists ConfigMaps and Secrets whose data is merged into
	// the substitution variables.
	SubstituteFrom []SubstituteRef
}

PostBuild configures variable substitution performed after kustomize build.

type SourceRef

type SourceRef struct {
	Kind      string
	Name      string
	Namespace string
	// URL is the repository URL (OCI or Git). When set, the resource generator
	// creates the source CRD in addition to referencing it.
	URL string
	// Tag is the tag or semver reference for OCI sources.
	Tag string
	// Branch is the branch reference for Git sources.
	Branch string
}

SourceRef defines a reference to a Flux source. When Kind, Name and Namespace are set, the Kustomization will reference an existing source. When URL is also set, the resource generator will create the source CRD.

Example
package main

import (
	"fmt"

	"k8s.io/apimachinery/pkg/runtime/schema"

	"github.com/go-kure/kure/pkg/stack"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

func main() {
	// A bundle's SourceRef names the Flux source its Kustomization reads from;
	// with URL set, the generator creates that source as well.
	bundle := &stack.Bundle{Name: "apps"}
	bundle.SourceRef = &stack.SourceRef{
		Kind:      "OCIRepository",
		Name:      "my-registry",
		Namespace: "flux-system",
		URL:       "oci://registry.example.com/manifests",
		Tag:       "v1.0.0",
	}

	// A node's PackageRef names the package its subtree is bundled into;
	// child nodes without one inherit it.
	node := &stack.Node{Name: "apps", Bundle: bundle}
	node.SetPackageRef(&schema.GroupVersionKind{
		Group:   "source.toolkit.fluxcd.io",
		Version: "v1",
		Kind:    "OCIRepository",
	})
	fmt.Println(bundle.SourceRef.URL, node.GetPackageRef().Kind)
}
Output:
oci://registry.example.com/manifests OCIRepository

type SourceVerification

type SourceVerification struct {
	Provider             string              `yaml:"provider,omitempty"`
	SecretRef            string              `yaml:"secretRef,omitempty"`
	MatchOIDCIdentity    []OIDCIdentityMatch `yaml:"matchOIDCIdentity,omitempty"`
	TrustedRootSecretRef string              `yaml:"trustedRootSecretRef,omitempty"`
}

SourceVerification is source-controller's OCIRepositoryVerification in kure's own type, so this package takes no Flux API dependency. Provider is cosign, the default when empty, or notation. SecretRef and TrustedRootSecretRef name Secrets in the source's namespace, holding the trusted public keys and a Sigstore trusted_root.json; empty sets neither. Cosign without SecretRef is keyless and needs at least one MatchOIDCIdentity: with none it would accept every signer.

type SubstituteRef

type SubstituteRef struct {
	// Kind is ConfigMap or Secret.
	Kind string
	// Name of the ConfigMap or Secret.
	Name string
	// Optional allows the reference to be absent without causing an error.
	Optional bool
}

SubstituteRef defines a reference to a ConfigMap or Secret used as a source of PostBuild substitution variables.

type Validator

type Validator interface {
	Validate() error
}

Validator is an optional interface that ApplicationConfig implementations can implement to validate their configuration before generation. If an ApplicationConfig also implements Validator, Application.Generate() calls Validate() automatically before calling Generate().

type Workflow

type Workflow interface {
	// GenerateFromCluster creates GitOps resources from a cluster definition.
	// This is the primary entry point for resource generation.
	// Every path in the resources is a directory a walk with the rules
	// writes, so the rules must be the ones the tree is written with.
	// The rules parameter must be a layout.LayoutRules value.
	GenerateFromCluster(*Cluster, LayoutRulesProvider) ([]client.Object, error)

	// CreateLayoutWithResources creates a new manifest layout that includes
	// both the application manifests and the GitOps resources needed to
	// deploy them. This combines manifest generation with GitOps resource
	// generation in a single operation.
	// The rules parameter must be a layout.LayoutRules value.
	// The returned ManifestLayoutResult is a *layout.ManifestLayout.
	CreateLayoutWithResources(*Cluster, LayoutRulesProvider) (ManifestLayoutResult, error)

	// GenerateBootstrap creates bootstrap resources for initializing the
	// GitOps system itself. This is used to set up the GitOps controller
	// (Flux, ArgoCD, etc.) in the cluster.
	// The rules are the ones the tree is written with: the Flux bootstrap
	// points Flux at the top directory of that tree. For Flux the rules
	// parameter must be a layout.LayoutRules value; the ArgoCD engine reads
	// nothing from it.
	GenerateBootstrap(*BootstrapConfig, *Node, LayoutRulesProvider) ([]client.Object, error)
}

Workflow defines the core interface for GitOps workflow implementations. This interface provides a minimal abstraction for converting stack definitions into GitOps-specific resources (Flux Kustomizations, ArgoCD Applications, etc.).

func NewWorkflow

func NewWorkflow(provider string) (Workflow, error)

NewWorkflow creates a workflow implementation based on the provider type. Supported providers: "flux", "argocd"

Example
package main

import (
	"fmt"
	"strconv"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/go-kure/kure/pkg/errors"
	"github.com/go-kure/kure/pkg/kubernetes"
	"github.com/go-kure/kure/pkg/stack"
	"github.com/go-kure/kure/pkg/stack/layout"

	_ "github.com/go-kure/kure/pkg/stack/fluxcd"
)

// myConfig is the ApplicationConfig the README's "Optional Validation"
// section declares; the other examples use it too.
type myConfig struct{ Port int }

func (c *myConfig) Validate() error {
	if c.Port <= 0 {
		return errors.New("port must be positive")
	}
	return nil
}

func (c *myConfig) Generate(app *stack.Application) ([]*client.Object, error) {

	cm := kubernetes.CreateConfigMap(app.Name, app.Namespace)
	cm.Data = map[string]string{"port": strconv.Itoa(c.Port)}
	var obj client.Object = cm
	return []*client.Object{&obj}, nil
}

func main() {
	cluster, err := stack.NewClusterBuilder("production").
		WithNode("infrastructure").
		WithBundle("monitoring").
		WithApplication("prometheus", &myConfig{Port: 9090}).
		End().
		End().
		Build()
	if err != nil {
		panic(err)
	}

	// Create a workflow for your GitOps tool
	wf, err := stack.NewWorkflow("flux")
	if err != nil {
		panic(err)
	}

	// Generate GitOps resources from the cluster definition, with the layout
	// rules the tree is written with
	objects, err := wf.GenerateFromCluster(cluster, layout.DefaultLayoutRules())
	if err != nil {
		panic(err)
	}
	for _, obj := range objects {
		fmt.Println(obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())
	}
}
Output:
Kustomization monitoring

Directories

Path Synopsis
Package helm provides client-side Helm chart rendering from OCI registries and HTTP Helm repositories.
Package helm provides client-side Helm chart rendering from OCI registries and HTTP Helm repositories.
Package layout provides utilities for generating cluster directory layouts and for writing Kubernetes and Flux manifests to disk.
Package layout provides utilities for generating cluster directory layouts and for writing Kubernetes and Flux manifests to disk.
Package stacktest checks an ApplicationConfig against the generation contract (stack.ApplicationConfig, pkg/stack README § Generation contract) from the config author's own tests.
Package stacktest checks an ApplicationConfig against the generation contract (stack.ApplicationConfig, pkg/stack README § Generation contract) from the config author's own tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL