fluxcd

package
v0.2.0-rc.2 Latest Latest
Warning

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

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

README

Flux Engine - FluxCD Workflow Implementation

Go Reference

The fluxcd package implements the stack.Workflow interface for FluxCD, providing complete Flux resource generation from domain model definitions.

Overview

The Flux engine transforms Kure's hierarchical domain model (Cluster, Node, Bundle, Application) into FluxCD resources (Kustomizations, source references) organized in a GitOps-ready directory structure.

The engine is composed of three specialized components:

Component Responsibility
ResourceGenerator Generates Flux resources from domain objects
LayoutIntegrator Integrates resources into directory structures
BootstrapGenerator Creates Flux bootstrap manifests

Start with Quick Start and Engine Construction below, then read the page for the task in front of you:

If you need Read
The Flux objects a cluster produces Resource Generation, below
How Kustomizations are named and where their paths point Flux Names and Paths
Where the files land and how Kustomizations point at them Flux Layout Integration, Flux Umbrella Bundles, Flux Non-Bundle Child Layout CRs
To install Flux itself Flux Bootstrap Generation
The settings and defaults the engine takes Flux Defaults, Configuration and Service account, below
What the engine refuses Validation, below

This page used to hold all of these. A link to a section that moved opens this page. The table above names the page that holds it.

Quick Start

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

Every other Go block on this page, except the one marked as an excerpt of the generator's own source, is the body of an Example function in example_test.go, which go test runs: it imports this package as fluxcd, github.com/go-kure/kure/pkg/stack as stack, github.com/go-kure/kure/pkg/stack/layout as layout, kustv1 (github.com/fluxcd/kustomize-controller/api/v1), os, and fmt for the lines that print what the example built. Two helpers are declared in the same file: exampleCluster() builds cluster prod, whose root node apps holds one bundle web with one application, which emits a ConfigMap through github.com/go-kure/kure/pkg/kubernetes and sigs.k8s.io/controller-runtime/pkg/client; printFiles(dir) prints every file below dir.

cluster := exampleCluster()

// Create engine with defaults. Placement is set on the LayoutRules passed
// to the layout call, not on the engine — see the Layout Integration page.
engine := fluxcd.Engine()

// Generate all Flux resources for a cluster: each spec.path is a directory
// a walk with the rules you pass writes
objects, err := engine.GenerateFromCluster(cluster, layout.DefaultLayoutRules())
if err != nil {
    panic(err)
}
for _, obj := range objects {
    fmt.Println(obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())
}

Engine Construction

// Default engine
engine := fluxcd.Engine()

// The same, built from its components
built := fluxcd.NewWorkflowEngine()
fmt.Println(engine.GetName() == built.GetName(), built.SupportedBootstrapModes())

The engine has no path mode: every Kustomization spec.path is a layout directory (see Kustomization paths).

Placement (FluxIntegratedPerLayout vs FluxSeparate) is configured per call on layout.LayoutRules.FluxPlacement. FluxUnset is normalized to FluxSeparate by LayoutIntegrator.CreateLayoutWithResources — matching layout.DefaultLayoutRules() and the walker. The call's placement is the tree's: IntegrateWithLayout sets it on every layout it integrates, whatever placement the tree was walked with. A tree that already holds Flux Kustomizations an earlier integration or the caller placed keeps the placement they were made for (another is refused; Kustomizations an application emits, and ones kustomize drops as local-config, do not count), and a refused call leaves the tree exactly as it was. See Layout Integration.

Resource Generation

Generate Flux resources from a cluster, from a layout walked from it, or for one bundle:

cluster := exampleCluster()
engine := fluxcd.Engine()
rules := layout.DefaultLayoutRules()
bundle := cluster.Node.Bundle

// From an entire cluster: walks it with the rules you write the tree with
objects, err := engine.GenerateFromCluster(cluster, rules)
if err != nil {
    panic(err)
}
fmt.Println(objects[0].GetName(), objects[0].(*kustv1.Kustomization).Spec.Path)

// From a layout you walked (and will write) yourself
ml, err := layout.WalkCluster(cluster, rules)
if err != nil {
    panic(err)
}
objects, err = engine.ResourceGen.GenerateFromLayout(ml, cluster)
if err != nil {
    panic(err)
}
fmt.Println(objects[0].GetName(), objects[0].(*kustv1.Kustomization).Spec.Path)

// For one bundle, at a path you supply
objects, err = engine.ResourceGen.GenerateForBundle(bundle, "clusters/prod/apps/web")
if err != nil {
    panic(err)
}
fmt.Println(objects[0].GetName(), objects[0].(*kustv1.Kustomization).Spec.Path)

Each directory that renders bundles produces one Flux Kustomization resource (see One Kustomization per directory) with:

  • metadata.name from the bundle (see Kustomization names)
  • spec.path = that directory
  • Source reference from Bundle.SourceRef (and a Source when it has a URL)
  • Dependency ordering from Bundle.DependsOn and Bundle.NamedDependsOn
  • Interval and pruning configuration
  • metadata.labels and metadata.annotations from Bundle.Labels and Bundle.Annotations

A Kustomization holds copies of the bundle's label and annotation maps, never the maps themselves, whichever entry point builds it (GenerateFromCluster, GenerateFromLayout, GenerateForBundle, CreateLayoutWithResources, IntegrateWithLayout): editing a Kustomization kure returns leaves the bundle, and so what later generations from it produce, as it was. An application's own objects are passed through without copying (a delivery intent that adds annotations gives the object a new annotations map, see Delivery intent): an edit of one reaches whatever the config shares it with, so a config that builds every object, map and pointer per call keeps its next call unchanged.

GenerateFromCluster walks the cluster itself, so it renders every application and runs every LayoutAugmenter: their errors surface there. It walks with the layout.LayoutRules it is given, so its paths are the directories WalkCluster writes under those rules: pass the rules you write the tree with. Under layout.DefaultLayoutRules() that is the root node at <root>, its bundle at <root>/<bundle> (the bundle's DirName, or its Name without one) and its children at <root>/<child>, which is also what the bootstrap sync path ./<root> expects; with ClusterName: "." and an unnamed root node it is the root of the tree, not cluster. The objects come back as a list and are placed nowhere, and the list is the same under FluxSeparate and FluxIntegratedPerBundle. Rules with FluxIntegratedPerLayout are refused: a tree written with that placement lists no directory child in its parent's kustomization.yaml, and the Kustomizations that apply those children (application, augmenter and bundle-less node directories) exist only where the integrator places them, so the list would leave them applied by nothing. Use CreateLayoutWithResources with those rules instead. A cluster in which an application sets a delivery intent is refused as well, after the walk and so after the placement refusal and any walk error: the list holds none of the application's objects, so the intent could not reach the output. On WorkflowEngine (the stack.Workflow interface) the rules arrive as a stack.LayoutRulesProvider and must be a layout.LayoutRules value: anything else, nil included, is refused, never replaced by the defaults.

GenerateFromLayout takes a layout the caller walked, and refuses it when any layout of the tree carries FluxIntegratedPerLayout, for the same reason: the list holds the Kustomizations of the bundle directories only, and the ones that apply the other child directories are placed by the integrator alone. The error names the placement and the first layout, in pre-order, that carries it; use CreateLayoutWithResources or IntegrateWithLayout instead. Each layout has its own FluxPlacement and the writers decide per parent, so a tree with placements set by hand is refused for one such layout below a root that carries another. The placement decides, not the tree's shape: a per-layout tree with no such child directory is refused although its list would be complete, as GenerateFromCluster refuses the rules whatever the cluster holds. A tree the integrator already placed per layout is refused as well: it holds every Kustomization it needs. The integrator's own use of GenerateFromLayout, under FluxSeparate, is not affected: it sets its placement on every layout of the tree first.

Configuration

Kustomization Mode

Controls how kustomization.yaml files reference resources:

  • KustomizationExplicit - Lists all manifest files explicitly
  • KustomizationRecursive - Writes no kustomization.yaml; the Flux Kustomization that builds the directory generates one from every .yaml and .yml file below it. The integrator marks every directory a Kustomization it generated builds (SetFluxBuild), and the writers refuse a marked Recursive directory that holds no file (a bundle with no applications, say), since the Kustomization would name an empty directory, which a Git tree drops, and one whose build would differ from the Explicit mode's: another generated target below it that no kustomization.yaml shields, or a YAML extra file in its build. See "Kustomization Generation" in the layout package README.

The marks also tell the writers what Flux applies. In a tree the integrator generated a Kustomization for, the writers refuse a directory its parent's kustomization.yaml does not list and no Kustomization builds (an umbrella child, a directory that renders bundles, a directory child of a FluxIntegratedPerLayout parent): nothing would apply it. A tree the integrator built always passes, since every such directory is the spec.path of a Kustomization it generated, or of one already in the tree that it kept in place of its own (typed, unstructured or inside a List), and it marks the directory for either. One changed afterwards, or one you place Kustomizations in yourself, needs SetFluxBuild on each directory a Kustomization of yours builds. The writers also refuse two Flux Kustomizations of one namespace and name anywhere in a tree, whether or not the integrator ran. See "Layout paths" in the layout package README.

Flux Placement

Controls where Flux Kustomization resources are placed:

  • FluxSeparate - Flux resources collected in a separate flux-system/ directory inside the root layout's own directory (where the root's kustomization.yaml references it); children referenced as directories, except those that render bundles, which their own CRs apply. WriteToDisk and WriteToTar name its files by LayoutRules.FileNaming, like the rest of the tree: flux-system-kustomization-<name>.yaml by default, kustomization-<name>.yaml with FileNamingKindName (go-kure/kure#976; before, always the default pattern). Rules passed to IntegrateWithLayout that leave FileNaming unset take the root layout's. The directory must be free: a root node's bundle or a child node rendered to it (named flux-system in whatever case, or a name that resolves to it such as ./flux-system; ManifestLayout.SameDirectory in the layout package) is refused, naming the bundle or node. Rename it (for a bundle, its directory: its DirName, or its Name without one), or use an integrated placement. Since go-kure/kure#979 the root node's bundle has a directory named after it there; before, such a bundle was written into the root node's directory.
  • FluxIntegratedPerLayout - a Flux Kustomization CR for every layout that renders bundles (bundles a GroupFlat merge puts in one directory share one CR, named after the first) and for every child layout that is not an umbrella child, not AppFileSingle and renders no bundle (augmenter-added child layouts included), hosted in its parent layout (the top of the tree layout.WalkCluster returns renders no bundle and gets no CR, go-kure/kure#979); the parent's kustomization.yaml lists those CR files as its own resources and references no child directory. Not literally every layout: a layout whose CR name another generated CR already uses, such as the application web of the bundle platform beside a bundle named platform-web, is refused instead (see Non-Bundle Child Layout CRs). A Kustomization already in the tree with that name, in the namespace of the generated CRs, is kept in place of a generated one when it sits in the layout that would host it and has the same spec.path and Source, without spec.kubeConfig, and is refused otherwise; where the layout's Source cannot be resolved, the Source is not compared, but one with spec.kubeConfig is still not kept. Finest granularity.
  • FluxIntegratedPerBundle - Flux Kustomization CRs at bundle boundaries only, each hosted in its parent layout; a bundle's interior (application and augmenter-added child layouts) is a single kustomize build, with those children referenced as directories. A child that renders bundles is not referenced: its own CR applies it. Coarser: Flux reconciles per bundle, kustomize handles the interior.

External augmenters may add child layouts that are not represented in the bundle model; integrated placement discovers those layouts and emits the required Flux resources.

Service account

Bundle.ServiceAccountName names the service account kustomize-controller impersonates when it applies the bundle (go-kure/kure#1034). Unset, no Kustomization carries spec.serviceAccountName and the output is what it was before the field existed; the controller then applies with its own identity, or with the default service account it is started with (--default-service-account), if any.

Kustomization spec.serviceAccountName
a bundle's, in every placement the bundle's own ServiceAccountName
an umbrella child's the child's own; the umbrella's is not passed down
one that bundles a GroupFlat merge share the one value every merged bundle sets; two values are refused, naming the field and both bundles
a per-layout one, under FluxIntegratedPerLayout that of the bundle holding the layout's application; no layout field (see Per-layout settings)
a node's, under FluxIntegratedPerLayout none: a node Kustomization inherits no settings

Flux looks the account up in the Kustomization's own namespace, the generator's DefaultNamespace, for every Kustomization kure generates. Creating the account and its RBAC is the caller's; kure writes the name only. Under the integrated placements a bundle's directory holds the CRs of its umbrella children and, under FluxIntegratedPerLayout, of its application layouts, so a bundle's account applies those Kustomization objects and needs the RBAC for them. Each of those Kustomizations then applies its own build under its own account: an umbrella child without one is applied as an unset one is, whatever its umbrella sets, so give each bundle that needs an account its own.

The name must be a DNS-1123 subdomain, the rule Kubernetes sets for a ServiceAccount's name (stack.ValidateServiceAccountName). Bundle.Validate refuses another, and so does the generator where it writes the bundle's Kustomization, for a bundle generated without Validate; the error names the bundle by its path and the field serviceAccountName. Flux does not check the field itself, so such a name would be admitted and fail at reconcile.

Flux-operator's multi-tenant lockdown (a default service account for every Kustomization) is a cluster setting outside kure.

Validation

All cluster-level entry points (GenerateFromCluster, CreateLayoutWithResources) call stack.ValidateCluster before walking the tree, and every generation from a layout runs layout.IndexOrigins (see Kustomization paths). Invalid umbrella configurations — such as a bundle referenced both by a Node and by another bundle's Children, shared umbrella ownership, or multi-package umbrellas — fail fast with a validation error rather than producing malformed output.

The layout rules are validated by the walk (layout.LayoutRules.Validate, see the layout package's "LayoutRules Configuration"): CreateLayoutWithResources and GenerateFromCluster do not check them on their own, and an unknown option value or a ClusterName with a .. path segment fails there with an error naming the field, also when the cluster is nil or has no root node (GenerateFromCluster walks that cluster too, after its placement refusal, and returns nothing only when the rules are valid). IntegrateWithLayout is handed a tree it did not walk and reads the placement and the file naming from the rules, so it runs the same check first, before it looks at the tree; it has no placement check of its own. An unknown placement is reported like any other unknown rule value, naming the field FluxPlacement.

CreateLayoutWithResources additionally calls validateSourceRefsForFluxIntegrated for both inline placements (FluxIntegratedPerLayout and FluxIntegratedPerBundle) — both emit bundle/node CRs that carry a spec.sourceRef. (After normalization FluxUnset becomes FluxSeparate, which skips this gate.) This checks that every bundle reachable from the cluster node tree — node bundles and umbrella child bundles recursively — has a complete SourceRef with both Kind and Name set. A nil, zero-value, or partially-populated SourceRef is rejected before layout walking begins, and the error names the placement in use (FluxIntegratedPerLayout mode requires a SourceRef … or FluxIntegratedPerBundle mode requires a SourceRef …). The integrator also enforces this at CR-creation time as defense in depth. FluxSeparate and non-Flux paths are unaffected.

Durations

Every duration this package writes into an object it generates is held to the pattern the Flux API holds that field to, ^([0-9]+(\.[0-9]+)?(ms|s|m|h))+$, where the object is created. The pattern is the same on a Kustomization's spec.interval, spec.timeout and spec.retryInterval (kustomize-controller v1.10.1), on the spec.interval of a GitRepository and an OCIRepository (source-controller v1.10.1) and on a FluxInstance's spec.sync.interval (flux-operator v0.62.1):

Generated object Durations checked
a bundle's Kustomization Bundle.Interval, Timeout and RetryInterval; ResourceGenerator.DefaultInterval when the bundle sets no interval
a per-layout Kustomization the Interval, Timeout and RetryInterval in effect, the layout's own or the bundle's it inherits; ResourceGenerator.DefaultInterval when neither sets an interval
the bootstrap Kustomization (gotk mode) BootstrapGenerator.DefaultInterval
a GitRepository or OCIRepository, derived from a SourceRef with a URL or generated by the bootstrap the generator's DefaultInterval
the FluxInstance sync (flux-operator mode, with a SourceURL) BootstrapGenerator.DefaultInterval

A stack.SourceRef has no duration of its own, so a bundle's durations reach its Kustomization and no source. A DefaultInterval is checked only where an object takes it: a generator whose interval nothing generated carries is not refused for it.

The check is made on the form the value is written in, not the one it was authored in. A duration is written as Go prints it, so "90s" is written 1m30s and "1us" is written 1µs. Go's time.ParseDuration takes more than Flux does, a sign and the units ns and us, so two kinds of value parse and are refused here, because the API server would refuse the object: a negative duration ("-1s") and a positive one under a millisecond ("1us", "500ns"). Zero is written 0s and is taken. A day is no unit of a Go duration, so "1d" is refused as a value that does not parse, as it was before.

The error names the bundle by its path (Bundle 'shop/infra' for an umbrella child) or the layout by its directory, then the field, the value as authored and the form it is written in, and what Flux takes; for a value a layout inherits it names the bundle as well, and for a generator's default the generator and DefaultInterval:

retryInterval "-2m" is written as "-2m0s", which the Flux API does not take: it takes digits with a unit of ms, s, m or h, so no negative duration and no positive one under a millisecond

A layout's inherited timeout or retry interval is first written into the Kustomization of the bundle it comes from, which is created before those of the layouts below it, so a tree is refused there, naming the bundle.

Bundle.Validate and stack.ValidateCluster are unchanged and accept these values: the rule is Flux's, and another workflow generates from a bundle that carries one as before.

Documentation

Overview

Package fluxcd implements the stack.Workflow interface for Flux. It turns the domain model (Cluster, Node, Bundle, Application) into Flux resources: Kustomizations and their source references, placed into the directories a layout writes, and the manifests that bootstrap Flux.

Importing the package for its side effect registers the "flux" workflow with the stack package:

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

Engine returns a WorkflowEngine with the defaults docs/defaults.md lists. The engine has three parts: the resource generator, the layout integrator and the bootstrap generator. The package README names the page that documents each of them, the names and paths the generated Kustomizations get, and the checks that refuse a cluster the engine cannot render.

Example (BuilderContractDefaults)
package main

import (
	"fmt"

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

func main() {
	// declared in pkg/stack/fluxcd/defaults.go
	fmt.Println(fluxcd.DefaultInterval)   // 60 * time.Minute
	fmt.Println(fluxcd.DefaultNamespace)  // "flux-system"
	fmt.Println(fluxcd.DefaultSourceKind) // "OCIRepository"
}
Output:
1h0m0s
flux-system
OCIRepository
Example (FluxWorkflowBootstrapNamespace)
package main

import (
	"fmt"

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

func main() {
	engine := fluxcd.Engine()
	rootNode := &stack.Node{Name: "production"}
	bootstrapConfig := &stack.BootstrapConfig{
		Enabled:     true,
		FluxVersion: "v2.8.2",
		Registry:    "ghcr.io/fluxcd",
	}

	engine.GetBootstrapGenerator().DefaultNamespace = "custom-flux" // default: "flux-system"

	objects, err := engine.GenerateBootstrap(bootstrapConfig, rootNode, layout.LayoutRules{})
	if err != nil {
		panic(err)
	}
	for _, obj := range objects {
		switch obj.GetObjectKind().GroupVersionKind().Kind {
		case "FluxInstance":
			fmt.Println("FluxInstance in", obj.GetNamespace())
		case "Namespace":
			fmt.Println("Namespace", obj.GetName())
		}
	}
}
Output:
Namespace flux-system
FluxInstance in custom-flux
Example (FluxWorkflowDefine)
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"
)

// workloadApp is the stack.ApplicationConfig the guide's applications use: a
// Deployment and a Service named after the application.
type workloadApp struct{}

func (workloadApp) Generate(app *stack.Application) ([]*client.Object, error) {
	var dep client.Object = kubernetes.CreateDeployment(app.Name, app.Namespace)
	var svc client.Object = kubernetes.CreateService(app.Name, app.Namespace)
	return []*client.Object{&dep, &svc}, nil
}

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

func main() {
	// The Flux source every bundle's Kustomization reads from.
	source := &stack.SourceRef{Kind: "GitRepository", Name: "flux-system"}

	certManager, err := stack.NewBundle("cert-manager", []*stack.Application{
		stack.NewApplication("cert-manager", "cert-manager", certManagerConfig),
	}, nil)
	if err != nil {
		panic(err)
	}
	certManager.SourceRef = source
	webTier, err := stack.NewBundle("web-tier", []*stack.Application{
		stack.NewApplication("frontend", "web", frontendConfig),
		stack.NewApplication("api-gateway", "web", apiConfig),
	}, nil)
	if err != nil {
		panic(err)
	}
	webTier.SourceRef = source

	cluster := stack.NewCluster("production", &stack.Node{
		Name: "production",
		Children: []*stack.Node{
			{Name: "infrastructure", Bundle: certManager},
			{Name: "applications", Bundle: webTier},
		},
	})
	for _, node := range cluster.Node.Children {
		b := node.Bundle
		fmt.Println(node.Name, b.Name, len(b.Applications), b.SourceRef.Kind, b.SourceRef.Name)
	}
}
Output:
infrastructure cert-manager 1 GitRepository flux-system
applications web-tier 2 GitRepository flux-system
Example (FluxWorkflowDeliveryIntent)
package main

import (
	"fmt"
	"maps"
	"slices"

	"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/fluxcd"
	"github.com/go-kure/kure/pkg/stack/layout"
)

// workloadApp is the stack.ApplicationConfig the guide's applications use: a
// Deployment and a Service named after the application.
type workloadApp struct{}

func (workloadApp) Generate(app *stack.Application) ([]*client.Object, error) {
	var dep client.Object = kubernetes.CreateDeployment(app.Name, app.Namespace)
	var svc client.Object = kubernetes.CreateService(app.Name, app.Namespace)
	return []*client.Object{&dep, &svc}, nil
}

var (
	databaseConfig stack.ApplicationConfig = workloadApp{}
	cacheConfig    stack.ApplicationConfig = workloadApp{}
)

func main() {
	database := stack.NewApplication("database", "data", databaseConfig)
	database.Delivery = stack.DeliveryIntent{
		PruneProtection: true, // keep its objects when they leave the source
		ForceReplace:    true, // delete and recreate on an immutable-field change
	}
	cache := stack.NewApplication("cache", "data", cacheConfig)

	dataTier, err := stack.NewBundle("data-tier", []*stack.Application{database, cache}, nil)
	if err != nil {
		panic(err)
	}
	dataTier.SourceRef = &stack.SourceRef{Kind: "GitRepository", Name: "flux-system"}
	cluster := stack.NewCluster("production", &stack.Node{Name: "production", Bundle: dataTier})

	// The Flux engine annotates the database's objects, and only those.
	ml, err := fluxcd.Engine().CreateLayoutWithResources(cluster, layout.DefaultLayoutRules())
	if err != nil {
		panic(err)
	}
	var show func(l *layout.ManifestLayout)
	show = func(l *layout.ManifestLayout) {
		for _, rec := range l.OriginApplicationObjects() {
			for _, obj := range rec.Objects {
				kind := obj.GetObjectKind().GroupVersionKind().Kind
				fmt.Println(rec.Application.Name, kind, len(obj.GetAnnotations()))
				for _, key := range slices.Sorted(maps.Keys(obj.GetAnnotations())) {
					fmt.Printf("  %s: %s\n", key, obj.GetAnnotations()[key])
				}
			}
		}
		for _, child := range l.Children {
			show(child)
		}
	}
	show(ml.(*layout.ManifestLayout))
}
Output:
database Deployment 2
  kustomize.toolkit.fluxcd.io/force: enabled
  kustomize.toolkit.fluxcd.io/prune: disabled
database Service 2
  kustomize.toolkit.fluxcd.io/force: enabled
  kustomize.toolkit.fluxcd.io/prune: disabled
cache Deployment 0
cache Service 0
Example (FluxWorkflowDependsOn)
package main

import (
	"fmt"

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

func main() {
	preInstall := &layout.ManifestLayout{
		Name: "nginx-00-pre-install",
		// ...
	}
	hooks := &layout.ManifestLayout{
		Name:      "nginx-01-hooks",
		DependsOn: []string{"nginx-00-pre-install"},
		// ...
	}
	fmt.Println(hooks.Name, "after", hooks.DependsOn[0] == preInstall.Name)
}
Output:
nginx-01-hooks after true
Example (FluxWorkflowEngine)
package main

import (
	"fmt"

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

func main() {
	engine := fluxcd.Engine()
	fmt.Println(engine.GetName())
}
Output:
FluxCD Workflow Engine
Example (FluxWorkflowLayout)
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/fluxcd"
	"github.com/go-kure/kure/pkg/stack/layout"
)

// workloadApp is the stack.ApplicationConfig the guide's applications use: a
// Deployment and a Service named after the application.
type workloadApp struct{}

func (workloadApp) Generate(app *stack.Application) ([]*client.Object, error) {
	var dep client.Object = kubernetes.CreateDeployment(app.Name, app.Namespace)
	var svc client.Object = kubernetes.CreateService(app.Name, app.Namespace)
	return []*client.Object{&dep, &svc}, nil
}

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

// productionCluster is the cluster Example_fluxWorkflowDefine builds, for the
// steps that start from it. Keep the two in step: the Example spells the
// cluster out because its body is the guide's Step 1, so it cannot call this.
func productionCluster() *stack.Cluster {
	source := &stack.SourceRef{Kind: "GitRepository", Name: "flux-system"}
	certManager, err := stack.NewBundle("cert-manager", []*stack.Application{
		stack.NewApplication("cert-manager", "cert-manager", certManagerConfig),
	}, nil)
	if err != nil {
		panic(err)
	}
	certManager.SourceRef = source
	webTier, err := stack.NewBundle("web-tier", []*stack.Application{
		stack.NewApplication("frontend", "web", frontendConfig),
		stack.NewApplication("api-gateway", "web", apiConfig),
	}, nil)
	if err != nil {
		panic(err)
	}
	webTier.SourceRef = source
	return stack.NewCluster("production", &stack.Node{
		Name: "production",
		Children: []*stack.Node{
			{Name: "infrastructure", Bundle: certManager},
			{Name: "applications", Bundle: webTier},
		},
	})
}

func main() {
	cluster := productionCluster()
	engine := fluxcd.Engine()

	// Define layout rules
	rules := layout.LayoutRules{
		NodeGrouping:        layout.GroupByName,
		BundleGrouping:      layout.GroupByName,
		ApplicationGrouping: layout.GroupByName,
		FilePer:             layout.FilePerResource,
		FluxPlacement:       layout.FluxSeparate, // Flux resources in separate tree
	}

	// Generate layout with Flux resources integrated
	ml, err := engine.CreateLayoutWithResources(cluster, rules)
	if err != nil {
		panic(err)
	}
	for _, child := range ml.(*layout.ManifestLayout).Children {
		fmt.Println(child.FullRepoPath())
	}
}
Output:
production/infrastructure
production/applications
production/flux-system
Example (FluxWorkflowServiceAccount)
package main

import (
	"fmt"

	kustv1 "github.com/fluxcd/kustomize-controller/api/v1"

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

func main() {
	// The umbrella names an account for its own Kustomization; a child gets
	// one only where it names its own.
	infra := &stack.Bundle{Name: "shop-infra", ServiceAccountName: "infra-deployer"}
	services := &stack.Bundle{Name: "shop-services"}
	shop := &stack.Bundle{Name: "shop", ServiceAccountName: "shop-deployer", Children: []*stack.Bundle{infra, services}}
	cluster := &stack.Cluster{Name: "prod", Node: &stack.Node{Name: "apps", Bundle: shop}}

	objects, err := fluxcd.Engine().GenerateFromCluster(cluster, layout.DefaultLayoutRules())
	if err != nil {
		panic(err)
	}
	for _, obj := range objects {
		kust := obj.(*kustv1.Kustomization)
		fmt.Printf("%s %q\n", kust.Name, kust.Spec.ServiceAccountName)
	}
}
Output:
shop "shop-deployer"
shop-infra "infra-deployer"
shop-services ""
Example (FluxWorkflowUmbrella)
package main

import (
	"fmt"

	kustv1 "github.com/fluxcd/kustomize-controller/api/v1"

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

func main() {
	umbrella := &stack.Bundle{
		Name: "platform",
		Children: []*stack.Bundle{
			{Name: "platform-infra"},
			{Name: "platform-services"},
			{Name: "platform-apps"},
		},
	}

	objects, err := fluxcd.Engine().ResourceGen.GenerateForBundle(umbrella, "production/apps/platform")
	if err != nil {
		panic(err)
	}
	ks := objects[0].(*kustv1.Kustomization)
	for _, hc := range ks.Spec.HealthChecks {
		fmt.Println(hc.Kind, hc.Namespace, hc.Name)
	}
}
Output:
Kustomization flux-system platform-infra
Kustomization flux-system platform-services
Kustomization flux-system platform-apps
Example (FluxWorkflowWrite)
ml := productionLayout()
out, err := os.MkdirTemp("", "kure-flux-workflow")
if err != nil {
	panic(err)
}
defer func() { _ = os.RemoveAll(out) }()

err = layout.WriteManifest(out, layout.DefaultLayoutConfig(), ml.(*layout.ManifestLayout))
if err != nil {
	panic(err)
}
printFiles(out)
Output:
clusters/production/applications/kustomization.yaml
clusters/production/applications/web-tier/api-gateway/kustomization.yaml
clusters/production/applications/web-tier/api-gateway/web-deployment-api-gateway.yaml
clusters/production/applications/web-tier/api-gateway/web-service-api-gateway.yaml
clusters/production/applications/web-tier/frontend/kustomization.yaml
clusters/production/applications/web-tier/frontend/web-deployment-frontend.yaml
clusters/production/applications/web-tier/frontend/web-service-frontend.yaml
clusters/production/applications/web-tier/kustomization.yaml
clusters/production/flux-system/flux-system-kustomization-cert-manager.yaml
clusters/production/flux-system/flux-system-kustomization-web-tier.yaml
clusters/production/flux-system/kustomization.yaml
clusters/production/infrastructure/cert-manager/cert-manager/cert-manager-deployment-cert-manager.yaml
clusters/production/infrastructure/cert-manager/cert-manager/cert-manager-service-cert-manager.yaml
clusters/production/infrastructure/cert-manager/cert-manager/kustomization.yaml
clusters/production/infrastructure/cert-manager/kustomization.yaml
clusters/production/infrastructure/kustomization.yaml
clusters/production/kustomization.yaml

Index

Examples

Constants

View Source
const (
	// DefaultNamespace is the namespace generated Flux resources are placed in
	// when the caller names none.
	DefaultNamespace = "flux-system"

	// DefaultSourceName is the name given to a generated GitRepository or
	// OCIRepository when the root node has no name of its own and
	// BootstrapConfig.SyncName names none.
	DefaultSourceName = "flux-system"

	// DefaultBootstrapName is the name given to the gotk bootstrap
	// Kustomization. It is not derived from the root node. Override it by
	// assigning [BootstrapGenerator.BootstrapName]; BootstrapConfig.SyncName,
	// set with a SourceURL, takes precedence over both. It does not reach the
	// FluxInstance, whose name is fixed — see [FluxInstanceName].
	DefaultBootstrapName = "flux-system"

	// FluxInstanceName is the metadata.name of the FluxInstance emitted in
	// flux-operator mode. It is not a default and has no override: the
	// flux-operator CRD requires metadata.name to be "flux" and rejects any
	// other name at admission (x-kubernetes-validations rule
	// `self.metadata.name == 'flux'` in the vendored flux_operator_install.yaml).
	// The name used to follow [BootstrapGenerator.BootstrapName], so a bundle
	// generated with the default ([DefaultBootstrapName]) or any override other
	// than "flux" was refused with "the only accepted name for a FluxInstance
	// is 'flux'". A test compares this constant against the vendored CRD's rule, so
	// an operator bump that changes the rule fails there rather than at apply.
	FluxInstanceName = "flux"

	// DefaultFluxDirName is the directory a separate Flux layout is placed in,
	// under FluxSeparate placement. It is a path segment, not a namespace: it
	// happens to share [DefaultNamespace]'s value and must not be derived from
	// it, because a caller who renames the namespace does not thereby rename
	// the directory. It has no override.
	DefaultFluxDirName = "flux-system"

	// DefaultFluxMode is the bootstrap mode used when BootstrapConfig.FluxMode
	// is empty. It is also the mode GenerateBootstrap dispatches on and the
	// first entry [BootstrapGenerator.SupportedBootstrapModes] reports, so
	// changing it here changes the default and the accepted spelling together
	// — the alternative left an empty FluxMode resolving to a mode the switch
	// no longer recognised.
	DefaultFluxMode = "flux-operator"

	// ModeGotk is the legacy bootstrap mode. It is not a default — nothing
	// falls back to it — but it is named here so the mode set has one
	// authority alongside [DefaultFluxMode] rather than a literal repeated in
	// the dispatch switch and the supported-mode list.
	ModeGotk = "gotk"

	// DefaultSourceKind is the kind of source object bootstrap emits, and
	// references, when BootstrapConfig.SourceKind does not name "GitRepository".
	// That includes the empty string: an unnamed kind yields an OCIRepository
	// for backward compatibility, which is generateSource's own behaviour.
	//
	// There is deliberately one identifier rather than one per emission site.
	// The bootstrap Kustomization's sourceRef, the source object itself and the
	// FluxInstance sync block previously each decided the kind for themselves,
	// and the first of the three used the opposite polarity to the other two —
	// so an empty SourceKind emitted an OCIRepository under a sourceRef naming a
	// GitRepository that was never created. [resolvedSourceKind] is now the only
	// place that decision is made.
	DefaultSourceKind = "OCIRepository"

	// DefaultSourceRef is the OCI tag used when BootstrapConfig.SourceRef is
	// empty, by both the gotk OCIRepository and the FluxInstance sync
	// ([resolvedSyncRef]). It has no GitRepository equivalent: an empty
	// SourceRef leaves the Git reference unset rather than guessing a branch.
	DefaultSourceRef = "latest"

	// DefaultSyncPath is the path a FluxInstance sync block uses when the
	// bootstrap applies the root of the source (no root node and no
	// ClusterName), and the prefix the directory is appended to otherwise
	// (syncPath). It has no override: it is the prefix a sync path is built
	// from, not a value a caller replaces. The gotk bootstrap Kustomization
	// names the same directory without this prefix (bootstrapDir).
	DefaultSyncPath = "./"
)

The values a generator falls back to when the caller supplies nothing.

pkg/stack is a workflow layer above pkg/kubernetes and may hold opinions — but as declared inputs with names a consumer can read, compare against and override, never as literals buried in a constructor. Every fallback the generators apply is one of the identifiers below; grep for the identifier to find every place the value can reach emitted YAML.

These are defaults, not policy, and they are overridden in one of two ways. DefaultNamespace, DefaultInterval and DefaultBootstrapName are copied into an exported field of ResourceGenerator or BootstrapGenerator by its constructor, and a caller that assigns the field afterwards is never overridden. The rest are applied where they are used, and are overridden by naming the corresponding input on stack.BootstrapConfig, stack.Bundle or the root stack.Node — the per-identifier comments below say which input each one yields to.

Two have no override at all: DefaultSyncPath and DefaultFluxDirName. Each is a fixed structural segment of a path the package builds, not a value a caller replaces, and their comments say so. They are named here anyway so the value is greppable and reviewable rather than a literal inside the function that emits it. FluxInstanceName is likewise fixed but is not a default of any kind: the flux-operator CRD accepts no other value, so it is a constraint the package satisfies, not an opinion it holds.

Interval and namespace are the two that always reach output. KustomizationSpec.Interval is +required upstream with no omitempty (kustomize-controller api/v1/kustomization_types.go:68), so a Kustomization cannot be emitted without one; DefaultInterval is what a caller who names no interval gets.

View Source
const DefaultInterval = 60 * time.Minute

DefaultInterval is the reconciliation interval used when the caller names none, on both generators. It applies only to an empty Bundle.Interval: a non-empty value that does not parse is a validation error, never a reason to fall back to this default.

DefaultMode names the kustomization.yaml listing mode the layout writers use for a layout with no Mode of its own (they treat KustomizationUnset as KustomizationExplicit). It is informational: no generator field is seeded from it, because a Kustomization's spec.path is not a mode of the generator but the directory of the layout that renders the bundle (layout.OriginIndex.KustomizationPath).

View Source
const FluxOperatorVersion = "v0.62.1"

FluxOperatorVersion is the upstream flux-operator release whose install manifest is vendored as fluxOperatorInstallYAML. It is pinned to match the github.com/controlplaneio-fluxcd/flux-operator Go module version in kure's go.mod so that the generated FluxInstance type and the install bundle stay in lockstep.

scripts/sync-flux-operator-pin.sh performs steps 2-4 below from go.mod's version, and Renovate runs it after a module bump. To refresh by hand instead:

  1. Bump github.com/controlplaneio-fluxcd/flux-operator in go.mod.
  2. Download the matching install.yaml from the flux-operator GitHub release page: https://github.com/controlplaneio-fluxcd/flux-operator/releases/download/{version}/install.yaml
  3. Replace pkg/stack/fluxcd/flux_operator_install.yaml with it.
  4. Update this constant, and the version named in pkg/stack/fluxcd/docs/bootstrap-generation.md ("currently **vX.Y.Z**"); no test checks it.
  5. Run the tests in this package and confirm the resource inventory in TestFluxOperatorInstallObjects still matches.
View Source
const GotkVersion = gotk.Version

GotkVersion is the upstream flux2 release whose install manifests base (the release's manifests.tar.gz asset) is vendored in internal/gotk, so gotk-mode bootstrap generation emits the controllers whose API types kure compiles against, without any network access. The pin, and the procedure for refreshing it after a flux2 bump, live next to the bundle; TestVendoredPinsMatchGoMod fails when the pin and go.mod disagree.

Variables

View Source
var (
	// ErrUmbrellaWait is wrapped by a refusal of a wait the setting exists to
	// prevent: an explicit Wait true, or health checks, on an umbrella, and
	// the setting on an entry point that cannot apply it.
	ErrUmbrellaWait = errors.New("an umbrella Kustomization does not wait under UmbrellasDoNotWait")
	// ErrUmbrellaDependency is wrapped by a refusal of a dependsOn on an
	// umbrella that cannot be written as one on its terminal leaves.
	ErrUmbrellaDependency = errors.New("a dependsOn on an umbrella Kustomization cannot be written as one on its terminal leaves")
	// ErrUmbrellaTerminals is returned, wrapped by a message only, by
	// UmbrellaTerminals for trees it cannot compute terminal sets for.
	ErrUmbrellaTerminals = errors.New("umbrella terminal sets cannot be computed")
)

Sentinels of the "umbrellas do not wait" setting (ResourceGenerator.UmbrellasDoNotWait) and of UmbrellaTerminals. Each refusal wraps one of them, so a caller can tell them apart with errors.Is whatever the message says.

Functions

func DefaultLayoutKustomizationName

func DefaultLayoutKustomizationName(unit, layoutName string) string

DefaultLayoutKustomizationName returns the name the layout integrator gives the per-layout Kustomization of an application or augmenter layout under FluxIntegratedPerLayout when the layout sets no KustomizationName: the default "<unit>-<layoutName>", shortened where it is longer than a Flux Kustomization name may be (see docs/child-layout-crs.md, "Per-layout name rule"). unit is the unit name: the name in effect (stack.Bundle.UnitName) of the Kustomization that applies the bundles the layout belongs to, which is the first bundle's where a grouping axis merged several into one directory, not necessarily that of the bundle holding the application. layoutName is the layout's Name.

The result is the same on every run for the same inputs, so a caller that checks names before writing them (for collisions or length) gets the name kure writes. It is the name only: whether the integrator accepts it (its characters, a duplicate) is checked where the Kustomization is created.

Example

The default per-layout Kustomization name, as the layout integrator writes it for a layout without KustomizationName: unchanged where it fits a Flux Kustomization name, shortened where it is longer.

package main

import (
	"fmt"

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

func main() {
	// The application "api" of the bundle "web": "<unit>-<layout name>".
	fmt.Println(fluxcd.DefaultLayoutKustomizationName("web", "api"))

	// Over 63 characters: the layout name stays, a prefix of the unit and a
	// hash replace the rest.
	fmt.Println(fluxcd.DefaultLayoutKustomizationName(
		"platform-services-payments", "checkout-service-payments-reconciler-worker"))
}
Output:
web-api
platform-s-7365aca5-checkout-service-payments-reconciler-worker

func FluxOperatorInstallObjects

func FluxOperatorInstallObjects() ([]client.Object, error)

FluxOperatorInstallObjects returns the parsed Flux Operator install manifest: Namespace, CRDs, RBAC, ServiceAccount, Service, and controller Deployment. The bytes are embedded at build time from flux_operator_install.yaml (version FluxOperatorVersion).

The returned slice is cached on first parse; callers must treat it as read-only. To mutate any object, deep-copy first.

The order of objects matches the order in the upstream install.yaml (Namespace → CRDs → RBAC → ServiceAccount → Deployment → Service), which is also a valid apply order.

func UmbrellaTerminals

func UmbrellaTerminals(roots ...*layout.ManifestLayout) (map[string][]string, error)

UmbrellaTerminals returns the terminal leaves of every umbrella Kustomization in one or more layout trees, keyed by the umbrella. Keys and values are "<namespace>/<name>", with an omitted namespace read as "default".

It is for a caller that generated several trees separately (one LayoutIntegrator.CreateLayoutWithResources per tree) and wires dependencies between them by name (stack.Bundle.NamedDependsOn): the integrator rewrites a dependsOn on an umbrella to its terminal leaves only inside the tree it places (ResourceGenerator.UmbrellasDoNotWait), and keeps a name it does not find as given. The caller applies the same rewrite to such a name: a dependsOn on a key of the map becomes one on each of its values.

An umbrella is a Flux Kustomization the integration placed or kept whose build applies at least one Flux Kustomization: its spec.path is a layout of the tree, and the directories a kustomize build of that layout includes host another Flux Kustomization. The terminal leaves are those the integrator writes (see UmbrellasDoNotWait). Each root is indexed on its own, because a spec.path is relative to its own tree; the trees are those an integration returned, with or without the setting.

Which Kustomizations the integration placed or kept is what it recorded in each layout (layout.ManifestLayout FluxKustomizations): one counts only while it still reads what was recorded, the same spec.path, spec.sourceRef and presence of spec.kubeConfig, in whatever form it is held (typed, unstructured or a List item). Every other Flux Kustomization is a leaf, whatever its spec.path names: one an application emits and the integration did not keep, one a caller added, one whose Source, cluster or path was changed after the integration (it may no longer build this tree's directory), and every one of a tree built by hand or read back from disk, which carries no record (go-kure/kure#1077). A caller placing Flux Kustomizations itself records them with SetFluxKustomizations to have them read as umbrellas; a record is compared in normal form (normalRecord).

It returns an error that wraps ErrUmbrellaTerminals, and no map, for a Kustomization identity found in two of the trees, for an umbrella without a terminal leaf and for a tree whose objects cannot be read. The error is a plain wrapped sentinel, not a typed resource error. Nil roots are skipped; no umbrella gives an empty map.

A tree that patches is read as its build shows it, patches applied, when the build can be made (go-kure/kure#1226); otherwise a plain entry proves nothing in it.

It counts only a dependsOn entry with no readyExpr as a wait for Ready (readyDeps): a sibling that another one names with a readyExpr is a terminal leaf, with or without ResourceGenerator.AdditiveCELDependencyCheckOff. It runs no cycle check, so a tree whose Kustomizations wait for each other only through a readyExpr returns its leaves, where it returned an error that wraps ErrUmbrellaTerminals before go-kure/kure#1190.

An unstructured object in a root that holds a value apimachinery cannot read, a plain int say, is replaced in place by one that holds its JSON typed counterpart, an int64 for it: its Object field is set to a new map, so the object the caller passed changes, and the caller's map does not. An object that holds only JSON typed values is left alone. A value of a shape outside the closed list at jsonContentOf (a struct, a pointer, a type with a marshaler) gives an error that wraps ErrUmbrellaTerminals, names the object and the field, and replaces no object. An error after the replacement puts every Object map back (go-kure/kure#1201).

Types

type BootstrapGenerator

type BootstrapGenerator struct {
	// DefaultNamespace is the namespace where bootstrap resources are created
	DefaultNamespace string
	// DefaultInterval is the default reconciliation interval
	DefaultInterval time.Duration
	// BootstrapName is the name given to the gotk bootstrap Kustomization. It
	// is not derived from the root node. [stack.BootstrapConfig.SyncName]
	// takes precedence when it is set with a SourceURL: it then names the
	// Kustomization and its source in both modes. Leaving it empty means the
	// default, not a nameless object — see [BootstrapGenerator.bootstrapName].
	//
	// It does not name the FluxInstance. That object's metadata.name is fixed
	// at [FluxInstanceName] by the flux-operator CRD, which admits no other
	// value; it used to take this field, so any bundle whose BootstrapName was
	// not "flux" — the default included — was rejected at apply
	// (go-kure/kure#847).
	BootstrapName string
}

BootstrapGenerator implements the workflow.BootstrapGenerator interface for Flux. It handles the generation of bootstrap resources for setting up Flux.

func NewBootstrapGenerator

func NewBootstrapGenerator() *BootstrapGenerator

NewBootstrapGenerator creates a FluxCD bootstrap generator seeded with the exported defaults (DefaultNamespace, DefaultInterval, DefaultBootstrapName). Assign the fields afterwards to override any of them.

func (*BootstrapGenerator) GenerateBootstrap

func (bg *BootstrapGenerator) GenerateBootstrap(config *stack.BootstrapConfig, rootNode *stack.Node, rules layout.LayoutRules) ([]client.Object, error)

GenerateBootstrap creates bootstrap resources for setting up Flux. When FluxMode is empty, flux-operator is used as the default.

rules are the layout rules the tree is written with: both modes point Flux at the top directory of the tree a walk with them writes for rootNode (bootstrapDir). They are validated first, as a walk validates them, so invalid rules are an error whatever config is, a nil or disabled one included. The directory itself is asked for only where it is used, so the root node's name is checked as a directory name only where it becomes a path (validateRootName).

func (*BootstrapGenerator) GenerateFluxInstance

func (bg *BootstrapGenerator) GenerateFluxInstance(config *stack.BootstrapConfig, rootNode *stack.Node, rules layout.LayoutRules) (*fluxv1.FluxInstance, error)

GenerateFluxInstance returns only the FluxInstance CR configured for the given bootstrap settings, without the full Flux Operator install bundle. Returns (nil, nil) when config is nil. Unlike GenerateBootstrap, this method does not check config.Enabled — the caller is responsible for that gate. An empty FluxVersion or Registry is an error, as on the bootstrap path.

rules are the layout rules the tree is written with, as in GenerateBootstrap: the sync.path is the top directory of that tree, and invalid rules are an error whatever config is, nil included. The directory is asked for only when a sync is built (syncDir).

Example
package main

import (
	"fmt"

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

func main() {
	engine := fluxcd.Engine()
	rootNode := &stack.Node{Name: "prod"}

	bootstrapConfig := &stack.BootstrapConfig{
		Enabled:     true,
		FluxVersion: "v2.8.2",
		Registry:    "ghcr.io/fluxcd",
		SourceURL:   "oci://registry.example.com/fleet",
		SourceRef:   "latest",
		SyncName:    "fleet",
	}

	fi, err := engine.GetBootstrapGenerator().GenerateFluxInstance(bootstrapConfig, rootNode, layout.LayoutRules{})
	if err != nil {
		panic(err)
	}
	fmt.Println(fi.Name, fi.Spec.Sync.Name, fi.Spec.Sync.Ref)
}
Output:
flux fleet latest

func (*BootstrapGenerator) SupportedBootstrapModes

func (bg *BootstrapGenerator) SupportedBootstrapModes() []string

SupportedBootstrapModes returns the bootstrap modes supported by this generator. DefaultFluxMode is the primary (recommended) mode; ModeGotk is the legacy one. This is the single list: GenerateBootstrap's validation error reports it rather than restating the modes.

type LayoutIntegrator

type LayoutIntegrator struct {
	// ResourceGenerator generates the Flux resources
	Generator *ResourceGenerator
}

LayoutIntegrator implements the workflow.LayoutIntegrator interface for Flux. It handles integration of Flux resources with manifest layouts.

Placement (FluxIntegratedPerLayout vs FluxSeparate) is configured via layout.LayoutRules.FluxPlacement on each call. CreateLayoutWithResources normalizes FluxUnset to FluxSeparate before invoking the SourceRef validation gate, WalkCluster, and IntegrateWithLayout, so all three observers agree on the effective placement.

Example (NodeKustomization)
package main

import (
	"fmt"

	kustv1 "github.com/fluxcd/kustomize-controller/api/v1"

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

func main() {
	// Two groups of nodes, neither with a bundle of its own. Each group gets
	// a Kustomization that applies its directory; the one for apps waits for
	// the one for platform.
	source := &stack.SourceRef{Kind: "GitRepository", Name: "flux-system", Namespace: "flux-system"}
	platform := &stack.Node{Name: "platform", KustomizationName: "platform", Children: []*stack.Node{
		{Name: "cert-manager", Bundle: &stack.Bundle{Name: "cert-manager", SourceRef: source}},
	}}
	apps := &stack.Node{Name: "apps", KustomizationName: "apps", DependsOn: []*stack.Node{platform}, Children: []*stack.Node{
		{Name: "shop", Bundle: &stack.Bundle{Name: "shop", SourceRef: source}},
	}}
	cluster := &stack.Cluster{Name: "prod", Node: &stack.Node{Name: "prod", Children: []*stack.Node{platform, apps}}}

	rules := layout.DefaultLayoutRules()
	rules.FluxPlacement = layout.FluxIntegratedPerLayout
	ml, err := fluxcd.NewLayoutIntegrator(fluxcd.NewResourceGenerator()).CreateLayoutWithResources(cluster, rules)
	if err != nil {
		panic(err)
	}
	for _, obj := range ml.Resources {
		kust, ok := obj.(*kustv1.Kustomization)
		if !ok {
			continue
		}
		var waitsFor []string
		for _, dep := range kust.Spec.DependsOn {
			waitsFor = append(waitsFor, dep.Name)
		}
		fmt.Println(kust.Name, kust.Spec.Path, waitsFor)
	}
}
Output:
platform prod/platform []
apps prod/apps [platform]

func NewLayoutIntegrator

func NewLayoutIntegrator(generator *ResourceGenerator) *LayoutIntegrator

NewLayoutIntegrator creates a FluxCD layout integrator.

func (*LayoutIntegrator) CreateLayoutWithResources

func (li *LayoutIntegrator) CreateLayoutWithResources(c *stack.Cluster, rules layout.LayoutRules) (*layout.ManifestLayout, error)

CreateLayoutWithResources creates a new layout that includes Flux resources.

rules.FluxPlacement is normalized once at the top of this method (FluxUnset -> FluxSeparate) and the normalized rules are passed to the SourceRef validation gate, WalkCluster, and IntegrateWithLayout. This guarantees a single placement authority per call.

The rules are validated by the walk, not here (layout.LayoutRules.Validate), also for a nil cluster: invalid rules are an error whatever the cluster is.

func (*LayoutIntegrator) IntegrateWithLayout

func (li *LayoutIntegrator) IntegrateWithLayout(ml *layout.ManifestLayout, c *stack.Cluster, rules layout.LayoutRules) (err error)

IntegrateWithLayout adds Flux resources to a manifest layout that layout.WalkCluster built from c.

Placement is driven by rules.FluxPlacement. FluxUnset is treated as FluxSeparate to match DefaultLayoutRules and the walker's normalization. The rules are validated first, as given, by the check the walks use (layout.LayoutRules.Validate): this call reads the placement and the file naming of a tree it did not walk.

Every placement first indexes the layout's origins (layout.IndexOrigins): a hand-built, partial or other-cluster tree is refused rather than matched by name, and every Kustomization's spec.path is the directory of the layout that renders its bundle. Integrating the same layout again adds nothing: a CR already present with the same name and spec.path in the layout that would host it is kept; one with the same name elsewhere or with another path is an error.

An unstructured object in ml that holds a value apimachinery cannot read, a plain int say, is replaced in place by one that holds its JSON typed counterpart, an int64 for it: its Object field is set to a new map, so the object the caller passed changes, and the caller's map does not. An object that holds only JSON typed values is left alone. A value of a shape outside the closed list at jsonContentOf (a struct, a pointer, a type with a marshaler) refuses the call, with the object and the field named, and a refused call puts every Object map back (go-kure/kure#1201).

type ResourceGenerator

type ResourceGenerator struct {
	// DefaultInterval is the default reconciliation interval for generated resources
	DefaultInterval time.Duration
	// DefaultNamespace is the default namespace for generated Flux resources
	DefaultNamespace string
	// Prune is the garbage-collection input for a Kustomization generated from
	// a layout.ManifestLayout (FluxIntegratedPerLayout mode) where neither the
	// layout (ManifestLayout.Prune) nor the bundle that holds its application
	// (Bundle.Prune) sets one. Kustomizations generated from a stack.Bundle
	// use that bundle's own Prune and ignore this field. nil emits
	// prune: false — see pruneValue.
	Prune *bool
	// UmbrellasDoNotWait, when true, makes readiness flow through dependsOn
	// only. kustomize-controller runs a Kustomization's health wait inside
	// one of its --concurrent workers, so umbrellas that wait for child
	// Kustomizations can hold every worker while no child has one to
	// reconcile with; a dependsOn that is not met yet holds none. With it:
	//
	//   - R1: an umbrella, a Kustomization whose build applies a Flux
	//     Kustomization, is written without wait and without health checks,
	//     and is Ready once applied. An explicit Wait true or HealthChecks
	//     that reach one are refused (ErrUmbrellaWait).
	//   - R2: an unset wait on any other Kustomization (a leaf) resolves to
	//     true; an explicit false is kept.
	//   - R3: a dependsOn on an umbrella is written as one on its terminal
	//     leaves (UmbrellaTerminals), so the dependent still starts after
	//     every last stage of the umbrella is Ready (ErrUmbrellaDependency).
	//
	// R1 and R3 need the integrator's placement: only
	// LayoutIntegrator with FluxIntegratedPerLayout or FluxIntegratedPerBundle
	// applies all three, GenerateForBundle applies R1 and R2 to the one
	// bundle, and the other entry points refuse the setting. The zero value
	// leaves every output as it is without it. A Flux Kustomization the
	// integration did not place is read in its context: its spec.path is a
	// directory of the tree only when it reads the Source of the
	// Kustomization whose apply writes it, without spec.kubeConfig, and so
	// its wait waits for what that directory holds, also when it transforms
	// its build (patches, components, name prefix or suffix, target
	// namespace: not modelled, so the wait is kept; with patches or
	// components, also for the Flux Kustomizations held as local config);
	// a health check on another cluster names none of the tree's
	// Kustomizations, and a spec.healthCheckExprs entry for Flux
	// Kustomizations is read as a wait for the checked one to be Ready,
	// whatever its expression says.
	UmbrellasDoNotWait bool
	// OmitUmbrellaChildHealthChecks, when true, writes none of the automatic
	// health checks an umbrella's Kustomization gets for its children
	// (Bundle.Children), in every placement and from every entry point; the
	// bundle's own HealthChecks are written as without it. Under an
	// integrated placement a Kustomization kept from an earlier integration
	// stays as written, child entries included; under FluxSeparate an
	// earlier flux-system child written with them no longer matches and is
	// refused, so integrate a freshly walked layout. The zero value leaves
	// every output as it is without it: with Wait unset or false and
	// UmbrellasDoNotWait unset, an umbrella gets one health check per child.
	//
	// It is for an umbrella whose children are applied by their own
	// Kustomizations, as under FluxSeparate, where they are not in the
	// umbrella's build: kustomize-controller runs the umbrella's health wait
	// inside one of its --concurrent workers until every child is Ready, and
	// each child needs a worker of its own to become Ready. The trade-off is
	// readiness: with Wait unset or false the umbrella no longer waits for
	// its children; it is Ready once applied and its own HealthChecks, if
	// any, pass, so a bundle that depends on it no longer waits for its
	// children. To keep that, list the children's Kustomizations in the
	// umbrella's HealthChecks, or depend on the children directly. With Wait
	// true the field changes nothing in any placement, since no entry was
	// written before either; under an integrated placement the umbrella's
	// wait still covers its children, under FluxSeparate it never did.
	// Unlike UmbrellasDoNotWait it changes no other field, and no entry
	// point refuses it.
	OmitUmbrellaChildHealthChecks bool
	// AdditiveCELDependencyCheckOff states that every kustomize-controller
	// reconciling the tree runs with its AdditiveCELDependencyCheck feature
	// gate off. That is Flux's default since v1.7 (kustomize-controller
	// v1.10.1 internal/features/features.go:97-99), so an operator running the
	// default controller sets this to true. kure cannot see the gate.
	//
	// false keeps the conservative read: a dependsOn with a readyExpr waits
	// for the dependency's Ready, whatever the expression says.
	//
	// true changes one case: a dependsOn whose readyExpr is exactly "true"
	// waits only for the dependency to exist. With the gate off Flux evaluates
	// the expression instead of its own readiness check, and it always
	// requires the dependency to exist first
	// (internal/controller/kustomization_controller.go:597-628). The
	// reconcile-order checks then wait for the apply of the Kustomization
	// that creates the dependency, or for nothing when no Kustomization of
	// the tree does (the Flux bootstrap, say). Every other expression still
	// waits for Ready in those checks. Picking terminal leaves and checking
	// a node's kept dependsOn count only an entry with no readyExpr as a wait
	// for Ready, with the field or without. Set on a cluster whose gate is on, where Flux checks
	// Ready after the expression, the checks can admit a tree that never
	// becomes Ready. Kustomizations kure generates carry no readyExpr, so it
	// changes only how Kustomizations an application emits, or a caller
	// keeps, patches or substitutes, are judged; no entry point refuses it.
	AdditiveCELDependencyCheckOff bool
}

ResourceGenerator implements the workflow.ResourceGenerator interface for Flux. It focuses purely on generating Flux CRDs from stack components.

func NewResourceGenerator

func NewResourceGenerator() *ResourceGenerator

NewResourceGenerator creates a FluxCD resource generator seeded with the exported defaults (DefaultInterval, DefaultNamespace). Assign the fields afterwards to override any of them; nothing else is injected into generated resources.

func (*ResourceGenerator) GenerateForBundle

func (g *ResourceGenerator) GenerateForBundle(b *stack.Bundle, path string) ([]client.Object, error)

GenerateForBundle creates the Flux resources for b itself: a Kustomization whose spec.path is path, verbatim, and a Source when b.SourceRef has a URL. Umbrella Children are not recursed. The generator computes no path: take it from the layout that renders b (layout.OriginIndex.KustomizationPath). A DependsOn bundle, a child, a NamedDependsOn entry or a health check with b's own Kustomization name is an error: the Kustomization would refer to itself. So are two children with one Kustomization name. The health check is accepted when b.Wait is true, where Flux ignores spec.healthChecks.

Example
package main

import (
	"fmt"

	kustv1 "github.com/fluxcd/kustomize-controller/api/v1"

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

func main() {
	// The bundles keep their names and directories; their Kustomizations
	// get the names set here.
	db := &stack.Bundle{Name: "db", KustomizationName: "apps-db"}
	shop := &stack.Bundle{Name: "shop", KustomizationName: "apps-shop", DependsOn: []*stack.Bundle{db}}

	objects, err := fluxcd.NewResourceGenerator().GenerateForBundle(shop, "clusters/prod/shop")
	if err != nil {
		panic(err)
	}
	kust := objects[0].(*kustv1.Kustomization)
	fmt.Println(kust.Name, kust.Spec.Path, kust.Spec.DependsOn[0].Name)
}
Output:
apps-shop clusters/prod/shop apps-db

func (*ResourceGenerator) GenerateFromCluster

func (g *ResourceGenerator) GenerateFromCluster(c *stack.Cluster, rules layout.LayoutRules) ([]client.Object, error)

GenerateFromCluster creates Flux Kustomizations and Sources from a cluster definition: it walks the cluster with rules and generates from that layout (see GenerateFromLayout).

It refuses, in this order: FluxIntegratedPerLayout rules (below), whatever the cluster; invalid rules with an absent or empty cluster, which otherwise yields nothing; a cluster stack.ValidateCluster refuses (umbrella cycles, disjointness violations, etc.), before the walk; rules the walk refuses (layout.LayoutRules.Validate), reported like every other walk error; and, after the walk, a cluster in which an application sets a delivery intent (below). Invalid rules are therefore an error whatever the cluster is.

The spec.path values are the directories WalkCluster writes under rules, so rules must be the ones the caller writes the tree with: with layout.DefaultLayoutRules, the root node at <root> and its children at <root>/<child>. The objects are returned as a list and placed nowhere (CreateLayoutWithResources places them in the layout it walks), and the list is the same under FluxSeparate and FluxIntegratedPerBundle.

FluxIntegratedPerLayout is refused. A tree written with it lists no directory child in its parent, and the Kustomizations that apply those children (application, augmenter and bundle-less node directories) exist only where the integrator places them, so this list would leave them applied by nothing: use CreateLayoutWithResources with those rules.

A set delivery intent (stack.Application.Delivery) is refused, naming the application. The intent is annotations on the application's objects, which the integrator sets on a layout; this call discards the layout it walks and returns none of those objects, so the intent would be dropped without a word: use CreateLayoutWithResources. GenerateFromLayout does not refuse a delivery intent: its caller holds the layout and may have integrated it.

The walk renders every application and runs every LayoutAugmenter, so their errors surface here.

func (*ResourceGenerator) GenerateFromLayout

func (g *ResourceGenerator) GenerateFromLayout(root *layout.ManifestLayout, c *stack.Cluster) ([]client.Object, error)

GenerateFromLayout creates one Kustomization (and, when its SourceRef has a URL, a Source) for every reconciliation unit of the layout tree root — every directory that renders bundles — in layout pre-order. root must have been walked from c (layout.WalkCluster): layout.IndexOrigins refuses anything else. Each spec.path is that directory, relative to the writer's output root; the bundles a grouping axis merged into it share the Kustomization (see generateForUnit).

A tree in which any layout carries FluxIntegratedPerLayout is refused, before anything else and whatever c is. The writers list no directory child of such a layout in its kustomization.yaml, and the Kustomizations that apply those children (application, augmenter and bundle-less node directories) are placed only by the integrator, so this list would leave them applied by nothing: use LayoutIntegrator.CreateLayoutWithResources or IntegrateWithLayout. The placement decides, not the tree's shape: a per-layout tree without such a child is refused too, and so is one the integrator already placed, which holds every Kustomization it needs. The error names the first such layout in pre-order.

Only bundles get a Kustomization here, so a node's KustomizationName, DependsOn and NamedDependsOn are refused, and so is any of the eleven settings of a layout's own Kustomization a layout sets (go-kure/kure#1032): the error names the first such layout in pre-order and every such field it sets.

An unstructured object in root that holds a value apimachinery cannot read, a plain int say, is replaced in place by one that holds its JSON typed counterpart, an int64 for it: its Object field is set to a new map, so the object the caller passed changes, and the caller's map does not. An object that holds only JSON typed values is left alone. A value of a shape outside the closed list at jsonContentOf (a struct, a pointer, a type with a marshaler) refuses the call, with the object and the field named, and replaces no object, and a refusal after it puts every Object map back (go-kure/kure#1201).

A caller's object whose GetObjectKind, GetName, GetNamespace, GetLabels or GetAnnotations panics, in a layout, in an origin record of one or in a typed List, refuses the call, in an error that names its Go type and never the panic's text, whether or not the call would have read it: bundles merged into one directory read each other's objects to check a targeted patch (go-kure/kure#1245).

Example
package main

import (
	"fmt"

	kustv1 "github.com/fluxcd/kustomize-controller/api/v1"
	"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/fluxcd"
	"github.com/go-kure/kure/pkg/stack/layout"
)

// configMapApp is a minimal stack.ApplicationConfig: one ConfigMap named after
// the application.
type configMapApp struct{}

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

// exampleCluster is the cluster the examples generate from: a root node
// "apps" whose bundle "web" holds one application.
func exampleCluster() *stack.Cluster {
	cluster, err := stack.NewClusterBuilder("prod").
		WithNode("apps").
		WithBundle("web").
		WithApplication("web", configMapApp{}).
		End().
		End().
		Build()
	if err != nil {
		panic(err)
	}
	return cluster
}

func main() {
	cluster := exampleCluster()
	engine := fluxcd.Engine()
	rules := layout.DefaultLayoutRules()
	bundle := cluster.Node.Bundle

	// From an entire cluster: walks it with the rules you write the tree with
	objects, err := engine.GenerateFromCluster(cluster, rules)
	if err != nil {
		panic(err)
	}
	fmt.Println(objects[0].GetName(), objects[0].(*kustv1.Kustomization).Spec.Path)

	// From a layout you walked (and will write) yourself
	ml, err := layout.WalkCluster(cluster, rules)
	if err != nil {
		panic(err)
	}
	objects, err = engine.ResourceGen.GenerateFromLayout(ml, cluster)
	if err != nil {
		panic(err)
	}
	fmt.Println(objects[0].GetName(), objects[0].(*kustv1.Kustomization).Spec.Path)

	// For one bundle, at a path you supply
	objects, err = engine.ResourceGen.GenerateForBundle(bundle, "clusters/prod/apps/web")
	if err != nil {
		panic(err)
	}
	fmt.Println(objects[0].GetName(), objects[0].(*kustv1.Kustomization).Spec.Path)
}
Output:
web apps/web
web apps/web
web clusters/prod/apps/web

func (*ResourceGenerator) GetName

func (g *ResourceGenerator) GetName() string

GetName returns the name of this resource generator.

func (*ResourceGenerator) GetVersion

func (g *ResourceGenerator) GetVersion() string

GetVersion returns the version of this resource generator.

func (*ResourceGenerator) UmbrellaTerminals

func (g *ResourceGenerator) UmbrellaTerminals(roots ...*layout.ManifestLayout) (map[string][]string, error)

UmbrellaTerminals is the package function UmbrellaTerminals, and returns the terminal leaves g's integration writes. They no longer depend on the setting: an entry with a readyExpr never makes a Kustomization it names depended on, so the method returns what the package function does. It stays for callers that already use it.

type WorkflowEngine

type WorkflowEngine struct {
	// ResourceGen handles core resource generation
	ResourceGen *ResourceGenerator
	// LayoutInteg handles layout integration
	LayoutInteg *LayoutIntegrator
	// BootstrapGen handles bootstrap resource generation
	BootstrapGen *BootstrapGenerator
}

WorkflowEngine implements the stack.Workflow interface by composing the specialized generator components. This provides a complete FluxCD workflow implementation with clear separation of concerns.

func Engine

func Engine() *WorkflowEngine

Engine returns a WorkflowEngine initialized with defaults. This is the primary entry point for FluxCD workflow functionality.

Example
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/fluxcd"
	"github.com/go-kure/kure/pkg/stack/layout"
)

// configMapApp is a minimal stack.ApplicationConfig: one ConfigMap named after
// the application.
type configMapApp struct{}

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

// exampleCluster is the cluster the examples generate from: a root node
// "apps" whose bundle "web" holds one application.
func exampleCluster() *stack.Cluster {
	cluster, err := stack.NewClusterBuilder("prod").
		WithNode("apps").
		WithBundle("web").
		WithApplication("web", configMapApp{}).
		End().
		End().
		Build()
	if err != nil {
		panic(err)
	}
	return cluster
}

func main() {
	cluster := exampleCluster()

	// Create engine with defaults. Placement is set on the LayoutRules passed
	// to the layout call, not on the engine — see the Layout Integration page.
	engine := fluxcd.Engine()

	// Generate all Flux resources for a cluster: each spec.path is a directory
	// a walk with the rules you pass writes
	objects, err := engine.GenerateFromCluster(cluster, layout.DefaultLayoutRules())
	if err != nil {
		panic(err)
	}
	for _, obj := range objects {
		fmt.Println(obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())
	}
}
Output:
Kustomization web
Example (DirName)
package main

import (
	"fmt"

	kustv1 "github.com/fluxcd/kustomize-controller/api/v1"

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

func main() {
	// The children's directories get the names set here; the bundles and
	// their Kustomizations keep theirs.
	infra := &stack.Bundle{Name: "shop-infra", DirName: "00-infra"}
	services := &stack.Bundle{Name: "shop-services", DirName: "10-services", DependsOn: []*stack.Bundle{infra}}
	shop := &stack.Bundle{Name: "shop", Children: []*stack.Bundle{infra, services}}
	cluster := &stack.Cluster{Name: "prod", Node: &stack.Node{Name: "apps", Bundle: shop}}

	objects, err := fluxcd.Engine().GenerateFromCluster(cluster, layout.DefaultLayoutRules())
	if err != nil {
		panic(err)
	}
	for _, obj := range objects {
		kust := obj.(*kustv1.Kustomization)
		fmt.Println(kust.Name, kust.Spec.Path)
	}
}
Output:
shop apps/shop
shop-infra apps/shop/00-infra
shop-services apps/shop/10-services

func NewWorkflowEngine

func NewWorkflowEngine() *WorkflowEngine

NewWorkflowEngine creates a FluxCD workflow engine with default components.

Example
package main

import (
	"fmt"

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

func main() {
	// Default engine
	engine := fluxcd.Engine()

	// The same, built from its components
	built := fluxcd.NewWorkflowEngine()
	fmt.Println(engine.GetName() == built.GetName(), built.SupportedBootstrapModes())
}
Output:
true [flux-operator gotk]

func (*WorkflowEngine) CreateLayoutWithResources

func (we *WorkflowEngine) CreateLayoutWithResources(c *stack.Cluster, rules stack.LayoutRulesProvider) (stack.ManifestLayoutResult, error)

CreateLayoutWithResources creates a new layout that includes Flux resources.

Example
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"

	"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/fluxcd"
	"github.com/go-kure/kure/pkg/stack/layout"
)

// configMapApp is a minimal stack.ApplicationConfig: one ConfigMap named after
// the application.
type configMapApp struct{}

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

// exampleCluster is the cluster the examples generate from: a root node
// "apps" whose bundle "web" holds one application.
func exampleCluster() *stack.Cluster {
	cluster, err := stack.NewClusterBuilder("prod").
		WithNode("apps").
		WithBundle("web").
		WithApplication("web", configMapApp{}).
		End().
		End().
		Build()
	if err != nil {
		panic(err)
	}
	return cluster
}

// printFiles prints every file below dir, relative to it.
func printFiles(dir string) {
	err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if err == nil && !d.IsDir() {
			rel, _ := filepath.Rel(dir, path)
			fmt.Println(rel)
		}
		return err
	})
	if err != nil {
		panic(err)
	}
}

func main() {
	cluster := exampleCluster()
	engine := fluxcd.Engine()
	rules := layout.DefaultLayoutRules()
	out, err := os.MkdirTemp("", "kure-fluxcd-example")
	if err != nil {
		panic(err)
	}
	defer func() { _ = os.RemoveAll(out) }()

	// Create layout with Flux resources integrated
	ml, err := engine.CreateLayoutWithResources(cluster, rules)
	if err != nil {
		panic(err)
	}

	// Write to disk: every spec.path is relative to <out>/clusters
	err = layout.WriteManifest(out, layout.DefaultLayoutConfig(), ml.(*layout.ManifestLayout))
	if err != nil {
		panic(err)
	}
	printFiles(out)
}
Output:
clusters/apps/flux-system/flux-system-kustomization-web.yaml
clusters/apps/flux-system/kustomization.yaml
clusters/apps/kustomization.yaml
clusters/apps/web/cluster-configmap-web.yaml
clusters/apps/web/kustomization.yaml

func (*WorkflowEngine) GenerateBootstrap

func (we *WorkflowEngine) GenerateBootstrap(config *stack.BootstrapConfig, rootNode *stack.Node, rules stack.LayoutRulesProvider) ([]client.Object, error)

GenerateBootstrap creates bootstrap resources for setting up Flux, pointed at the top directory of the tree a walk with rules writes for rootNode (see BootstrapGenerator.GenerateBootstrap). rules must be a layout.LayoutRules value, the one the tree is written with: anything else, nil included, is refused rather than replaced by defaults, whatever config is.

Example
package main

import (
	"fmt"

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

func main() {
	engine := fluxcd.Engine()
	rootNode := &stack.Node{Name: "prod"}

	bootstrapConfig := &stack.BootstrapConfig{
		Enabled:     true,
		FluxMode:    "flux-operator",  // or "gotk"; empty defaults to "flux-operator"
		FluxVersion: "v2.8.2",         // required in flux-operator mode
		Registry:    "ghcr.io/fluxcd", // required in flux-operator mode
		SourceURL:   "oci://registry.example.com/fleet",
		SourceRef:   "latest",
	}

	objects, err := engine.GenerateBootstrap(bootstrapConfig, rootNode, layout.LayoutRules{})
	if err != nil {
		panic(err)
	}
	for _, obj := range objects {
		if obj.GetObjectKind().GroupVersionKind().Kind == "FluxInstance" {
			fmt.Println(obj.GetNamespace(), obj.GetName())
		}
	}
}
Output:
flux-system flux

func (*WorkflowEngine) GenerateFromCluster

func (we *WorkflowEngine) GenerateFromCluster(c *stack.Cluster, rules stack.LayoutRulesProvider) ([]client.Object, error)

GenerateFromCluster creates Flux resources from a cluster definition, with the spec.path values of a walk with rules (see ResourceGenerator.GenerateFromCluster). rules must be a layout.LayoutRules value: anything else, nil included, is refused rather than replaced by defaults. Rules with FluxIntegratedPerLayout are refused as well: use CreateLayoutWithResources for that placement.

func (*WorkflowEngine) GetBootstrapGenerator

func (we *WorkflowEngine) GetBootstrapGenerator() *BootstrapGenerator

GetBootstrapGenerator returns the underlying bootstrap generator for advanced configuration.

func (*WorkflowEngine) GetLayoutIntegrator

func (we *WorkflowEngine) GetLayoutIntegrator() *LayoutIntegrator

GetLayoutIntegrator returns the underlying layout integrator for advanced configuration.

func (*WorkflowEngine) GetName

func (we *WorkflowEngine) GetName() string

GetName returns a human-readable name for this workflow engine.

func (*WorkflowEngine) GetResourceGenerator

func (we *WorkflowEngine) GetResourceGenerator() *ResourceGenerator

GetResourceGenerator returns the underlying resource generator for advanced configuration.

func (*WorkflowEngine) GetVersion

func (we *WorkflowEngine) GetVersion() string

GetVersion returns the version of this workflow engine.

func (*WorkflowEngine) IntegrateWithLayout

func (we *WorkflowEngine) IntegrateWithLayout(ml *layout.ManifestLayout, c *stack.Cluster, rules layout.LayoutRules) error

IntegrateWithLayout adds Flux resources to an existing manifest layout.

func (*WorkflowEngine) SupportedBootstrapModes

func (we *WorkflowEngine) SupportedBootstrapModes() []string

SupportedBootstrapModes returns the bootstrap modes supported by this engine.

Jump to

Keyboard shortcuts

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