Skip to content

Commit

Permalink
Add resolve option to error on missing keys
Browse files Browse the repository at this point in the history
By default, the template engine uses "<no value>" when a key is missing
from a lookup, and it does not return an error. That behavior can make
it less obvious when something is going wrong in a template.

Signed-off-by: Justin Kulikauskas <jkulikau@redhat.com>
  • Loading branch information
JustinKuli committed Apr 26, 2024
1 parent ed92bd3 commit f7526fe
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ var (
ErrCacheDisabled = client.ErrCacheDisabled
ErrNoCacheEntry = client.ErrNoCacheEntry
ErrContextTransformerFailed = errors.New("the context transformer failed")
ErrMissingKey = errors.New("missing key while resolving template")
)

// Config is a struct containing configuration for the API.
Expand Down Expand Up @@ -121,6 +122,7 @@ type ResolveOptions struct {
DisableAutoCacheCleanUp bool
LookupNamespace string
Watcher *client.ObjectIdentifier
ErrorOnMissingKey bool
}

type ClusterScopedObjectIdentifier struct {
Expand Down Expand Up @@ -629,11 +631,19 @@ func (t *TemplateResolver) ResolveTemplate(
}
}

if options.ErrorOnMissingKey {
tmpl = tmpl.Option("missingkey=error")
}

err = tmpl.Execute(&buf, ctx)
if err != nil {
tmplRawStr := string(tmplRaw)
klog.Errorf("error resolving the template %v,\n template str %v,\n error: %v", tmplRawStr, templateStr, err)

if options.ErrorOnMissingKey && strings.Contains(err.Error(), "no entry for key") {
return resolvedResult, fmt.Errorf("%w %v: %w", ErrMissingKey, tmplRawStr, err)
}

return resolvedResult, fmt.Errorf("failed to resolve the template %v: %w", tmplRawStr, err)
}

Expand Down
7 changes: 7 additions & 0 deletions pkg/templates/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,13 @@ func TestResolveTemplateErrors(t *testing.T) {
ErrInvalidInput,
),
},
"error_on_missing_key": {
inputTmpl: `foo: '{{ (lookup "v1" "ConfigMap" "testns" "nonexist-cm").data }}'`,
resolveOptions: ResolveOptions{
ErrorOnMissingKey: true,
},
expectedErr: ErrMissingKey,
},
}

for testName, test := range testcases {
Expand Down

0 comments on commit f7526fe

Please sign in to comment.