Skip to main content
Version: v1.11-alpha

Full Examples

Complete end-to-end definition examples — one per definition type — showing real-world usage patterns with full Go source, generated definition YAML, and a working Application validated against a live cluster.

All Go sources below are taken from the kubevela/vela-go-definitions repository — each section links to its canonical file.

Component Definition — Task

A complete task component that runs a one-time Job to completion. Uses JobHealth/CustomStatus presets, OneOf for typed volume variants, Each for volumeMount/volume array mapping, and MapVariant for per-type volume configuration.

Source: components/task.go.

components/task.go
package components

import (
"github.com/oam-dev/kubevela/pkg/definition/defkit"
)

func Task() *defkit.ComponentDefinition {
labels := defkit.StringKeyMap("labels").Optional().Description("Specify the labels in the workload")
annotations := defkit.StringKeyMap("annotations").Optional().Description("Specify the annotations in the workload")
count := defkit.Int("count").Default(1).Description("Specify number of tasks to run in parallel").Short("c")
image := defkit.String("image").Description("Which image would you like to use for your service").Short("i")
imagePullPolicy := defkit.String("imagePullPolicy").
Optional().
Values("Always", "Never", "IfNotPresent").
Description("Specify image pull policy for your service")
imagePullSecrets := defkit.StringList("imagePullSecrets").Optional().Description("Specify image pull secrets for your service")
restart := defkit.String("restart").Default("Never").
Description("Define the job restart policy, the value can only be Never or OnFailure. By default, it's Never.")
cmd := defkit.StringList("cmd").Optional().Description("Commands to run in the container")
env := defkit.List("env").Optional().Description("Define arguments by using environment variables").
WithFields(
defkit.String("name").Description("Environment variable name"),
defkit.String("value").Optional().Description("The value of the environment variable"),
defkit.Object("valueFrom").Optional().Description("Specifies a source the value of this var should come from").
WithFields(
defkit.Object("secretKeyRef").Optional().Description("Selects a key of a secret in the pod's namespace").
WithFields(
defkit.String("name").Description("The name of the secret in the pod's namespace to select from"),
defkit.String("key").Description("The key of the secret to select from. Must be a valid secret key"),
),
defkit.Object("configMapKeyRef").Optional().Description("Selects a key of a config map in the pod's namespace").
WithFields(
defkit.String("name").Description("The name of the config map in the pod's namespace to select from"),
defkit.String("key").Description("The key of the config map to select from. Must be a valid secret key"),
),
),
)
cpu := defkit.String("cpu").Optional().Description("Number of CPU units for the service, like `0.5` (0.5 CPU core), `1` (1 CPU core)")
memory := defkit.String("memory").Optional().Description("Specifies the attributes of the memory resource required for the container.")
volumes := defkit.List("volumes").Optional().Description("Declare volumes and volumeMounts").
WithFields(
defkit.String("name"),
defkit.String("mountPath"),
defkit.OneOf("type").
Description("Specify volume type, options: \"pvc\",\"configMap\",\"secret\",\"emptyDir\", default to emptyDir").
Default("emptyDir").
Variants(
defkit.Variant("pvc").WithFields(
defkit.Field("claimName", defkit.ParamTypeString),
),
defkit.Variant("configMap").WithFields(
defkit.Field("defaultMode", defkit.ParamTypeInt).Default(420),
defkit.Field("cmName", defkit.ParamTypeString),
defkit.Field("items", defkit.ParamTypeArray).Optional().Nested(
defkit.Struct("").WithFields(
defkit.Field("key", defkit.ParamTypeString),
defkit.Field("path", defkit.ParamTypeString),
defkit.Field("mode", defkit.ParamTypeInt).Default(511),
),
),
),
defkit.Variant("secret").WithFields(
defkit.Field("defaultMode", defkit.ParamTypeInt).Default(420),
defkit.Field("secretName", defkit.ParamTypeString),
defkit.Field("items", defkit.ParamTypeArray).Optional().Nested(
defkit.Struct("").WithFields(
defkit.Field("key", defkit.ParamTypeString),
defkit.Field("path", defkit.ParamTypeString),
defkit.Field("mode", defkit.ParamTypeInt).Default(511),
),
),
),
defkit.Variant("emptyDir").WithFields(
defkit.Field("medium", defkit.ParamTypeString).Default("").Values("", "Memory"),
),
),
)
livenessProbe := defkit.Object("livenessProbe").
Optional().
WithSchemaRef("HealthProbe").
Description("Instructions for assessing whether the container is alive.")
readinessProbe := defkit.Object("readinessProbe").
Optional().
WithSchemaRef("HealthProbe").
Description("Instructions for assessing whether the container is in a suitable state to serve traffic.")

return defkit.NewComponent("task").
Description("Describes jobs that run code or a script to completion.").
Workload("batch/v1", "Job").
CustomStatus(defkit.Status().
IntField("status.active", "status.active", 0).
IntField("status.failed", "status.failed", 0).
IntField("status.succeeded", "status.succeeded", 0).
Message("Active/Failed/Succeeded:\\(status.active)/\\(status.failed)/\\(status.succeeded)").
Build()).
HealthPolicy(defkit.JobHealth().Build()).
Helper("HealthProbe", CronTaskHealthProbeParam()).
Params(
labels, annotations,
count, image, imagePullPolicy, imagePullSecrets,
restart, cmd, env,
cpu, memory, volumes,
livenessProbe, readinessProbe,
).
Template(taskTemplate)
}

func taskTemplate(tpl *defkit.Template) {
vela := defkit.VelaCtx()

labels := defkit.StringKeyMap("labels")
annotations := defkit.StringKeyMap("annotations")
count := defkit.Int("count")
image := defkit.String("image")
imagePullPolicy := defkit.String("imagePullPolicy")
imagePullSecrets := defkit.StringList("imagePullSecrets")
restart := defkit.String("restart")
cmd := defkit.StringList("cmd")
env := defkit.List("env")
cpu := defkit.String("cpu")
memory := defkit.String("memory")
volumes := defkit.List("volumes")

job := defkit.NewResource("batch/v1", "Job").
Set("metadata.name", defkit.Interpolation(vela.AppName(), defkit.Lit("-"), vela.Name())).
Set("spec.parallelism", count).
Set("spec.completions", count).
SpreadIf(labels.IsSet(), "spec.template.metadata.labels", labels).
Set("spec.template.metadata.labels[app.oam.dev/name]", vela.AppName()).
Set("spec.template.metadata.labels[app.oam.dev/component]", vela.Name()).
SetIf(annotations.IsSet(), "spec.template.metadata.annotations", annotations).
Set("spec.template.spec.restartPolicy", restart).
Set("spec.template.spec.containers[0].name", vela.Name()).
Set("spec.template.spec.containers[0].image", image).
SetIf(imagePullPolicy.IsSet(), "spec.template.spec.containers[0].imagePullPolicy", imagePullPolicy).
SetIf(cmd.IsSet(), "spec.template.spec.containers[0].command", cmd).
SetIf(env.IsSet(), "spec.template.spec.containers[0].env", env).
If(cpu.IsSet()).
Set("spec.template.spec.containers[0].resources.limits.cpu", cpu).
Set("spec.template.spec.containers[0].resources.requests.cpu", cpu).
EndIf().
If(memory.IsSet()).
Set("spec.template.spec.containers[0].resources.limits.memory", memory).
Set("spec.template.spec.containers[0].resources.requests.memory", memory).
EndIf().
SetIf(volumes.IsSet(), "spec.template.spec.containers[0].volumeMounts",
defkit.Each(volumes).Map(defkit.FieldMap{
"mountPath": defkit.FieldRef("mountPath"),
"name": defkit.FieldRef("name"),
})).
SetIf(volumes.IsSet(), "spec.template.spec.volumes",
defkit.Each(volumes).
Map(defkit.FieldMap{
"name": defkit.FieldRef("name"),
}).
MapVariant("type", "pvc", defkit.FieldMap{
"persistentVolumeClaim": defkit.NestedFieldMap(defkit.FieldMap{
"claimName": defkit.FieldRef("claimName"),
}),
}).
MapVariant("type", "configMap", defkit.FieldMap{
"configMap": defkit.NestedFieldMap(defkit.FieldMap{
"defaultMode": defkit.FieldRef("defaultMode"),
"name": defkit.FieldRef("cmName"),
"items": defkit.OptionalFieldRef("items"),
}),
}).
MapVariant("type", "secret", defkit.FieldMap{
"secret": defkit.NestedFieldMap(defkit.FieldMap{
"defaultMode": defkit.FieldRef("defaultMode"),
"secretName": defkit.FieldRef("secretName"),
"items": defkit.OptionalFieldRef("items"),
}),
}).
MapVariant("type", "emptyDir", defkit.FieldMap{
"emptyDir": defkit.NestedFieldMap(defkit.FieldMap{
"medium": defkit.FieldRef("medium"),
}),
})).
SetIf(imagePullSecrets.IsSet(), "spec.template.spec.imagePullSecrets",
ImagePullSecretsTransform(imagePullSecrets))

tpl.Output(job)
}

func init() {
defkit.Register(Task())
}

Apply and verify (output captured live from k3d):

vela def apply ./vela-templates/definitions/component/task.cue
vela up -f task-demo-app.yaml
NAME        COMPONENT    TYPE   PHASE     HEALTHY   STATUS                          AGE
task-demo hello-task task running true Active/Failed/Succeeded:0/0/1 51s

The component renders to a batch/v1 Job named <appName>-<componentName>:

$ kubectl get job task-demo-hello-task -n default \
-o jsonpath='completions={.spec.completions} image={.spec.template.spec.containers[0].image} restartPolicy={.spec.template.spec.restartPolicy} status={.status.succeeded}'
completions=1 image=busybox:latest restartPolicy=Never status=1

$ kubectl get job task-demo-hello-task -n default \
-o jsonpath='{.spec.template.spec.containers[0].command}'
["sh","-c","echo hello && sleep 5 && echo done"]

Trait Definition — CPUScaler

A complete cpuscaler trait that creates an HPA resource to automatically scale the component based on CPU usage. Demonstrates tpl.Outputs() for emitting a secondary resource from a trait.

Source: traits/cpuscaler.go.

traits/cpuscaler.go
package traits

import "github.com/oam-dev/kubevela/pkg/definition/defkit"

func CPUScaler() *defkit.TraitDefinition {
min := defkit.Int("min").Description("Specify the minimal number of replicas to which the autoscaler can scale down").Default(1)
max := defkit.Int("max").Description("Specify the maximum number of of replicas to which the autoscaler can scale up").Default(10)
cpuUtil := defkit.Int("cpuUtil").Description("Specify the average CPU utilization, for example, 50 means the CPU usage is 50%").Default(50)
targetAPIVersion := defkit.String("targetAPIVersion").Description("Specify the apiVersion of scale target").Default("apps/v1")
targetKind := defkit.String("targetKind").Description("Specify the kind of scale target").Default("Deployment")

return defkit.NewTrait("cpuscaler").
Description("Automatically scale the component based on CPU usage.").
AppliesTo("deployments.apps", "statefulsets.apps").
Params(min, max, cpuUtil, targetAPIVersion, targetKind).
Template(func(tpl *defkit.Template) {
vela := defkit.VelaCtx()

hpa := defkit.NewResource("autoscaling/v1", "HorizontalPodAutoscaler").
Set("metadata.name", vela.Name()).
Set("spec.scaleTargetRef.apiVersion", targetAPIVersion).
Set("spec.scaleTargetRef.kind", targetKind).
Set("spec.scaleTargetRef.name", vela.Name()).
Set("spec.minReplicas", min).
Set("spec.maxReplicas", max).
Set("spec.targetCPUUtilizationPercentage", cpuUtil)

tpl.Outputs("cpuscaler", hpa)
})
}

func init() {
defkit.Register(CPUScaler())
}

Apply and verify (output captured live from k3d):

vela def apply ./vela-templates/definitions/trait/cpuscaler.cue
vela up -f cpuscaler-demo-app.yaml
NAME             COMPONENT    TYPE         PHASE     HEALTHY   STATUS      AGE
cpuscaler-demo scaled-web webservice running true Ready:1/1 51s

The trait emits a sibling HorizontalPodAutoscaler that targets the component's Deployment:

$ kubectl get hpa -n default
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
scaled-web Deployment/scaled-web cpu: 0%/50% 1 3 1 71s

$ kubectl get hpa scaled-web -n default \
-o jsonpath='kind={.spec.scaleTargetRef.kind} target={.spec.scaleTargetRef.name} min={.spec.minReplicas} max={.spec.maxReplicas}'
kind=Deployment target=scaled-web min=1 max=3

Policy Definition — Apply Once

A complete apply-once policy that allows configuration drift for applied resources. Demonstrates defkit.NewPolicy with inline Helper type definitions and WithSchemaRef for type reuse across params.

Source: policies/apply_once.go.

info

Policies use only .Params() — no .Template() — because KubeVela's built-in engine processes policy params directly. .Helper("TypeName", struct) registers a named CUE type (#TypeName) that can be referenced via .WithSchemaRef("TypeName") in other params.

policies/apply_once.go
package policies

import "github.com/oam-dev/kubevela/pkg/definition/defkit"

func ApplyOnce() *defkit.PolicyDefinition {
applyOnceStrategy := defkit.Struct("strategy").WithFields(
defkit.Field("affect", defkit.ParamTypeString).
Description("When the strategy takes effect, e.g. onUpdate, onStateKeep").
Optional(),
defkit.Field("path", defkit.ParamTypeArray).
Of(defkit.ParamTypeString).
Description("Specify the path of the resource that allow configuration drift"),
)

applyOncePolicyRule := defkit.Struct("rule").WithFields(
defkit.Field("selector", defkit.ParamTypeStruct).
Description("Specify how to select the targets of the rule").
Optional().
WithSchemaRef("ResourcePolicyRuleSelector"),
defkit.Field("strategy", defkit.ParamTypeStruct).
Description("Specify the strategy for configuring the resource level configuration drift behaviour").
WithSchemaRef("ApplyOnceStrategy"),
)

resourcePolicyRuleSelector := defkit.Struct("selector").
WithFields(RuleSelectorFields()...)

return defkit.NewPolicy("apply-once").
Description("Allow configuration drift for applied resources, " +
"delivery the resource without continuously reconciliation.").
Helper("ApplyOnceStrategy", applyOnceStrategy).
Helper("ApplyOncePolicyRule", applyOncePolicyRule).
Helper("ResourcePolicyRuleSelector", resourcePolicyRuleSelector).
Params(
defkit.Bool("enable").
Description("Whether to enable apply-once for the whole application").
Default(false),
defkit.Array("rules").
Description("Specify the rules for configuring apply-once policy in resource level").
WithSchemaRef("ApplyOncePolicyRule").
Optional(),
)
}

func init() {
defkit.Register(ApplyOnce())
}

Apply and verify (output captured live from k3d):

vela def apply ./vela-templates/definitions/policy/apply-once.cue
vela up -f apply-once-demo-app.yaml
NAME              COMPONENT        TYPE         PHASE     HEALTHY   STATUS      AGE
apply-once-demo drift-tolerant webservice running true Ready:1/1 51s

The policy is recorded on the Application's spec but emits no Kubernetes resources of its own — it changes how the controller reconciles existing ones:

$ kubectl get app apply-once-demo -n default -o jsonpath='{.spec.policies}' | python3 -m json.tool
[
{
"name": "stable",
"properties": {"enable": true},
"type": "apply-once"
}
]

WorkflowStep Definition — Apply Component

A complete apply-component workflow step. The simplest definition type — workflow steps often require no template at all because the step execution is handled by KubeVela's built-in step executor.

Source: workflowsteps/apply_component.go.

workflowsteps/apply_component.go
package workflowsteps

import "github.com/oam-dev/kubevela/pkg/definition/defkit"

func ApplyComponent() *defkit.WorkflowStepDefinition {
component := defkit.String("component").Description("Specify the component name to apply")
cluster := defkit.String("cluster").Default("").Description("Specify the cluster")
namespace := defkit.String("namespace").Default("").Description("Specify the namespace")

return defkit.NewWorkflowStep("apply-component").
Description("Apply a specific component and its corresponding traits in application").
Category("Application Delivery").
Scope("Application").
Params(component, cluster, namespace)
}

func init() {
defkit.Register(ApplyComponent())
}

Apply and verify (output captured live from k3d):

vela def apply ./vela-templates/definitions/workflowstep/apply-component.cue
vela up -f workflow-demo-app.yaml
NAME            COMPONENT   TYPE         PHASE     HEALTHY   STATUS      AGE
workflow-demo web-a webservice running true Ready:1/1 51s

Both steps execute in declared order and the workflow status records the final phase per step:

$ kubectl get app workflow-demo -n default -o jsonpath='{.status.workflow.steps}' | python3 -m json.tool
[
{
"id": "nox3bf5n8y",
"name": "deploy-a",
"phase": "succeeded",
"type": "apply-component"
},
{
"id": "394hsuj65t",
"name": "deploy-b",
"phase": "succeeded",
"type": "apply-component"
}
]
Key patterns per type

Component — use preset health/status builders (DeploymentHealth, DeploymentStatus), ForEachWith for per-element logic, and tpl.OutputsIf for optional secondary resources.

Trait — use tpl.Outputs(name, resource) to emit secondary resources (HPA, Service, etc.). Use tpl.UsePatchContainer(config) when the trait needs to mutate container specs (env vars, resource limits, volume mounts).

Policy — parameters only; use .Helper("TypeName", struct) for reusable named CUE types and .WithSchemaRef() to reference them in array element schemas.

WorkflowStep — often just .Params() with .Category() and .Scope() metadata. Add .Template() only when the step needs to generate resources itself.