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 ¶
- Constants
- Variables
- func DefaultLayoutKustomizationName(unit, layoutName string) string
- func FluxOperatorInstallObjects() ([]client.Object, error)
- func UmbrellaTerminals(roots ...*layout.ManifestLayout) (map[string][]string, error)
- type BootstrapGenerator
- func (bg *BootstrapGenerator) GenerateBootstrap(config *stack.BootstrapConfig, rootNode *stack.Node, rules layout.LayoutRules) ([]client.Object, error)
- func (bg *BootstrapGenerator) GenerateFluxInstance(config *stack.BootstrapConfig, rootNode *stack.Node, rules layout.LayoutRules) (*fluxv1.FluxInstance, error)
- func (bg *BootstrapGenerator) SupportedBootstrapModes() []string
- type LayoutIntegrator
- type ResourceGenerator
- func (g *ResourceGenerator) GenerateForBundle(b *stack.Bundle, path string) ([]client.Object, error)
- func (g *ResourceGenerator) GenerateFromCluster(c *stack.Cluster, rules layout.LayoutRules) ([]client.Object, error)
- func (g *ResourceGenerator) GenerateFromLayout(root *layout.ManifestLayout, c *stack.Cluster) ([]client.Object, error)
- func (g *ResourceGenerator) GetName() string
- func (g *ResourceGenerator) GetVersion() string
- func (g *ResourceGenerator) UmbrellaTerminals(roots ...*layout.ManifestLayout) (map[string][]string, error)
- type WorkflowEngine
- func (we *WorkflowEngine) CreateLayoutWithResources(c *stack.Cluster, rules stack.LayoutRulesProvider) (stack.ManifestLayoutResult, error)
- func (we *WorkflowEngine) GenerateBootstrap(config *stack.BootstrapConfig, rootNode *stack.Node, ...) ([]client.Object, error)
- func (we *WorkflowEngine) GenerateFromCluster(c *stack.Cluster, rules stack.LayoutRulesProvider) ([]client.Object, error)
- func (we *WorkflowEngine) GetBootstrapGenerator() *BootstrapGenerator
- func (we *WorkflowEngine) GetLayoutIntegrator() *LayoutIntegrator
- func (we *WorkflowEngine) GetName() string
- func (we *WorkflowEngine) GetResourceGenerator() *ResourceGenerator
- func (we *WorkflowEngine) GetVersion() string
- func (we *WorkflowEngine) IntegrateWithLayout(ml *layout.ManifestLayout, c *stack.Cluster, rules layout.LayoutRules) error
- func (we *WorkflowEngine) SupportedBootstrapModes() []string
Examples ¶
- Package (BuilderContractDefaults)
- Package (FluxWorkflowBootstrapNamespace)
- Package (FluxWorkflowDefine)
- Package (FluxWorkflowDeliveryIntent)
- Package (FluxWorkflowDependsOn)
- Package (FluxWorkflowEngine)
- Package (FluxWorkflowLayout)
- Package (FluxWorkflowServiceAccount)
- Package (FluxWorkflowUmbrella)
- Package (FluxWorkflowWrite)
- BootstrapGenerator.GenerateFluxInstance
- DefaultLayoutKustomizationName
- Engine
- Engine (DirName)
- LayoutIntegrator (NodeKustomization)
- NewWorkflowEngine
- ResourceGenerator.GenerateForBundle
- ResourceGenerator.GenerateFromLayout
- WorkflowEngine.CreateLayoutWithResources
- WorkflowEngine.GenerateBootstrap
Constants ¶
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.
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.
const DefaultMode = layout.KustomizationExplicit
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).
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:
- Bump github.com/controlplaneio-fluxcd/flux-operator in go.mod.
- Download the matching install.yaml from the flux-operator GitHub release page: https://github.com/controlplaneio-fluxcd/flux-operator/releases/download/{version}/install.yaml
- Replace pkg/stack/fluxcd/flux_operator_install.yaml with it.
- Update this constant, and the version named in pkg/stack/fluxcd/docs/bootstrap-generation.md ("currently **vX.Y.Z**"); no test checks it.
- Run the tests in this package and confirm the resource inventory in TestFluxOperatorInstallObjects still matches.
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 ¶
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 ¶
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 ¶
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.
Source Files
¶
- bootstrap_generator.go
- build_guard.go
- build_guard_kinds.go
- built_objects.go
- built_view.go
- caller_objects.go
- defaults.go
- delivery.go
- doc.go
- durations.go
- flux_build.go
- flux_operator_install.go
- fluxcd.go
- gotk_install.go
- layout_fields.go
- layout_integrator.go
- layout_patches.go
- layout_postbuild.go
- layout_refusal.go
- layout_settings.go
- merge_gate.go
- node_kustomization.go
- order_graph.go
- resource_generator.go
- umbrella_builtclasses.go
- umbrella_nowait.go
- umbrella_terminals.go
- validate.go
- workflow_engine.go
- wrapper_promotion.go