Use decodeEnv lookup again since eval.Value does not work on complete hcl.Body
@@ -13,6 +13,7 @@ import (
"time"
"github.com/hashicorp/hcl/v2"
+ "github.com/hashicorp/hcl/v2/hclsyntax"
pkce "github.com/jimlambrt/go-oauth-pkce-code-verifier"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
@@ -56,7 +57,7 @@ func NewContext(src []byte, defaults *config.Defaults) *Context {
}
variables := make(map[string]cty.Value)
- variables[Environment] = newCtyEnvMap(defaultEnvVariables)
+ variables[Environment] = newCtyEnvMap(src, defaultEnvVariables)
variables[Couper] = newCtyCouperVariablesMap()
return &Context{
@@ -446,7 +447,7 @@ func newVariable(ctx context.Context, cookies []*http.Cookie, headers http.Heade
}
}
-func newCtyEnvMap(defaultValues map[string]string) cty.Value {
+func newCtyEnvMap(src []byte, defaultValues map[string]string) cty.Value {
ctyMap := make(map[string]cty.Value)
for k, v := range defaultValues {
ctyMap[k] = cty.StringVal(v)
@@ -459,6 +460,15 @@ func newCtyEnvMap(defaultValues map[string]string) cty.Value {
ctyMap[key] = cty.StringVal(value)
}
}
+
+ emptyString := cty.StringVal("")
+ referenced := decodeEnvironmentRefs(src)
+ for _, key := range referenced {
+ if _, exist := ctyMap[key]; !exist {
+ ctyMap[key] = emptyString
+ }
+ }
+
return cty.MapVal(ctyMap)
}
@@ -484,3 +494,32 @@ func newFunctionsMap() map[string]function.Function {
"url_encode": lib.UrlEncodeFunc,
}
}
+
+func decodeEnvironmentRefs(src []byte) []string {
+ tokens, diags := hclsyntax.LexConfig(src, "tmp.hcl", hcl.InitialPos)
+ if diags.HasErrors() {
+ panic(diags)
+ }
+ needle := []byte("env")
+ var keys []string
+ for i, token := range tokens {
+ if token.Type == hclsyntax.TokenDot && i > 0 &&
+ bytes.Equal(tokens[i-1].Bytes, needle) &&
+ i+1 < len(tokens) {
+ value := string(tokens[i+1].Bytes)
+ if !hasValue(keys, value) {
+ keys = append(keys, value)
+ }
+ }
+ }
+ return keys
+}
+
+func hasValue(list []string, needle string) bool {
+ for _, s := range list {
+ if s == needle {
+ return true
+ }
+ }
+ return false
+}
