Skip to content

Add must_env and env native functions for Jsonnet configs#280

Merged
Songmu merged 1 commit into
Songmu:mainfrom
tzmfreedom:feat/jsonnet-native-funcs
May 21, 2026
Merged

Add must_env and env native functions for Jsonnet configs#280
Songmu merged 1 commit into
Songmu:mainfrom
tzmfreedom:feat/jsonnet-native-funcs

Conversation

@tzmfreedom
Copy link
Copy Markdown

Summary

Add must_env and env as Jsonnet native functions when evaluating .jsonnet config files. These mirror the Go template helpers in template.go so that Jsonnet configs can branch on environment variables at evaluation time.

Motivation

The existing {{ must_env "ENV" }} Go template substitution operates on the JSON bytes produced by Jsonnet evaluation. This means it can only substitute values inside string literals — it cannot produce a boolean, number, or any non-string JSON token because Jsonnet always JSON-quotes its output and json.Unmarshal cannot coerce a string to a bool field.

In practice this is limiting for fields like Rule.Disabled bool, which a user would naturally want to set conditionally per environment (e.g., "all rules disabled in prod, enabled in dev"). With the existing template-only mechanism, writing:

disabled: '{{ if eq (must_env `ENV`) `prod` }}true{{ else }}false{{ end }}'

produces "disabled": "true" (string) in the JSON, which then fails:

json: cannot unmarshal string into Go struct field Rule.rules.disabled of type bool

With this PR, the same conditional becomes:

local isProd = std.native('must_env')('ENV') == 'prod';
{ ..., rules: [{ ..., disabled: isProd }] }

which evaluates to a proper JSON boolean at Jsonnet evaluation time and passes through unchanged to json.Unmarshal.

Changes

  • Add jsonnet.go with a helper newJsonnetVM() that registers must_env(name) and env(name, default) as Jsonnet native functions.
  • Wire newJsonnetVM() into readConfigFile in config.go.
  • Add jsonnet_test.go with unit tests for must_env, env, the unset-variable error path, and a regression test for the original boolean-field motivation.
  • Document the new native functions in README.md.

Compatibility

Existing configs that only use Go template {{ must_env ... }} continue to work unchanged — those substitutions happen after Jsonnet evaluation on the JSON bytes, and that code path is untouched. The new native functions are only invoked when a config explicitly calls std.native('must_env') or std.native('env').

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds Jsonnet-native environment variable helpers so .jsonnet configs can branch on environment variables during Jsonnet evaluation (enabling non-string JSON tokens like booleans), and wires the new VM into config loading.

Changes:

  • Add newJsonnetVM() registering Jsonnet native functions must_env(name) and env(name, default).
  • Use newJsonnetVM() when evaluating .jsonnet config files in readConfigFile.
  • Add unit tests and README documentation for the new Jsonnet native functions.
Show a summary per file
File Description
README.md Documents Jsonnet-time env access via std.native('must_env') / std.native('env') and provides an example for boolean fields.
jsonnet.go Introduces newJsonnetVM() and registers the Jsonnet native functions.
jsonnet_test.go Adds unit tests for the native functions and a regression test for boolean-field output.
config.go Switches .jsonnet evaluation to use newJsonnetVM() instead of a plain VM.

Copilot's findings

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

  • Files reviewed: 4/4 changed files
  • Comments generated: 6

Comment thread jsonnet.go
Comment on lines +15 to +22
// - must_env(name): returns env var `name`; errors if unset.
// - env(name, default): returns env var `name`, or `default` if unset.
//
// These mirror the Go template helpers in template.go. They are required
// for setting non-string fields (e.g., `disabled: bool`) conditionally per
// environment, which cannot be done via the post-evaluation Go template
// substitution because that operates on JSON byte streams (string values
// only).
Comment thread jsonnet.go
Comment on lines +40 to +52
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "env",
Params: []ast.Identifier{"name", "default"},
Func: func(args []interface{}) (interface{}, error) {
key, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("env: name must be a string")
}
if v, ok := os.LookupEnv(key); ok {
return v, nil
}
return args[1], nil
},
Comment thread jsonnet_test.go
Comment on lines +11 to +23
out, err := vm.EvaluateAnonymousSnippet("test.jsonnet", `{
v: std.native('must_env')('ECSCHEDULE_TEST_ENV'),
isProd: std.native('must_env')('ECSCHEDULE_TEST_ENV') == 'prod',
}`)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, `"v": "prod"`) {
t.Errorf("expected v=prod, got %s", out)
}
if !strings.Contains(out, `"isProd": true`) {
t.Errorf("expected isProd=true, got %s", out)
}
Comment thread jsonnet_test.go
Comment on lines +26 to +30
func TestJsonnetMustEnvUnset(t *testing.T) {
vm := newJsonnetVM()
_, err := vm.EvaluateAnonymousSnippet("test.jsonnet",
`std.native('must_env')('ECSCHEDULE_TEST_UNSET_VAR_XYZ')`)
if err == nil {
Comment thread jsonnet_test.go
Comment on lines +38 to +41
out, err := vm.EvaluateAnonymousSnippet("test.jsonnet", `{
set: std.native('env')('ECSCHEDULE_TEST_ENV', 'default'),
unset: std.native('env')('ECSCHEDULE_TEST_UNSET_VAR_XYZ', 'default'),
}`)
Comment thread config.go
Comment on lines 157 to 161
if ext == jsonnetExt {
vm := jsonnet.MakeVM()
vm := newJsonnetVM()
bs, err := vm.EvaluateFile(confPath)
if err != nil {
return nil, ext, fmt.Errorf("failed to evaluate jsonnet file: %w", err)
@Songmu Songmu merged commit f74b052 into Songmu:main May 21, 2026
6 checks passed
@github-actions github-actions Bot mentioned this pull request May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants