Add must_env and env native functions for Jsonnet configs#280
Merged
Conversation
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
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 functionsmust_env(name)andenv(name, default). - Use
newJsonnetVM()when evaluating.jsonnetconfig files inreadConfigFile. - 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 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 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 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 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 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 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) |
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add
must_envandenvas Jsonnet native functions when evaluating.jsonnetconfig files. These mirror the Go template helpers intemplate.goso 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 andjson.Unmarshalcannot coerce a string to aboolfield.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:produces
"disabled": "true"(string) in the JSON, which then fails:With this PR, the same conditional becomes:
which evaluates to a proper JSON boolean at Jsonnet evaluation time and passes through unchanged to
json.Unmarshal.Changes
jsonnet.gowith a helpernewJsonnetVM()that registersmust_env(name)andenv(name, default)as Jsonnet native functions.newJsonnetVM()intoreadConfigFileinconfig.go.jsonnet_test.gowith unit tests formust_env,env, the unset-variable error path, and a regression test for the original boolean-field motivation.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 callsstd.native('must_env')orstd.native('env').