This guide demonstrates how to use tag attributes to inject arbitrary values into CUE evaluations. A separate guide details how to inject system information.

One of CUE’s core concepts is that evaluations should be repeatable: given the same input, the same output should be produced. However, sometimes it can be necessary to introduce context or other information into an evaluation that might cause the output to vary. As described in the cue help injection reference, CUE allows information to be introduced, or injected, by using tag attributes and tag variables. This guide demonstrates tag attributes.

Injecting a value

string.cue
package example

// A tag's value is treated as a string unless
// an alternative type is specified (see below).
A: string @tag(a)

// A default provides a value if the related key
// is not specified for the cue command.
B: *"bar" | string @tag(b)
TERMINAL
$ cue export -t a=foo
{
    "A": "foo",
    "B": "bar"
}

Injecting a numeric value

number.cue
package example

A: int @tag(a,type=int)

// The number field type is compatible with both
// integers and floating point numbers.
B: number @tag(b,type=number)

// To treat an injected value exclusively as a
// float, use a tag with a number type and a field
// of type float.
C: float @tag(b,type=number)
TERMINAL
$ cue eval -t a=42 -t b=4.2
A: 42
B: 4.2
C: 4.2

Both the B and C fields refer to the same tag attribute, b. Injecting a single value can affect multiple fields.

Injecting a boolean value

boolean.cue
package example

A: bool @tag(a,type=bool)

// This constraint causes the evaluation to fail.
A: false
TERMINAL
$ cue vet -t a=true
A: conflicting values false and true:
    ./boolean.cue:6:4

Injecting lists of values

list.cue
package example

import "encoding/json"

asString: string @tag(a)

// Using a disjunction with the empty list ensures
// that an evaluation can succeed even if no value
// is provided for the tag value.
asList: *json.Unmarshal(asString) | []

A: [
	for e in asList {"\(e)-with-suffix"},
]
TERMINAL
$ cue eval -t a='["foo", "bar"]'
asString: "[\"foo\", \"bar\"]"
asList: ["foo", "bar"]
A: ["foo-with-suffix", "bar-with-suffix"]