Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle environment variable for yaml file #69

Merged
merged 3 commits into from
Oct 7, 2024
Merged

Conversation

bthuillier
Copy link
Contributor

No description provided.

resource/resource.go Outdated Show resolved Hide resolved
@99-not-out
Copy link
Contributor

This is a great addition! 👍

@qboileau
Copy link
Member

qboileau commented Oct 3, 2024

@bthuillier @99-not-out
If you want here is an implementation that still panic when missing env var in a "strict mode" and replace with empty value in a "non strict mode"
It also accumulates missing env to panic with all of them in the error message

import (
	"fmt"
	"os"
	"regexp"
	"strings"
)

var envVarRegex = regexp.MustCompile(`\$\{([^}]+)\}`)

func expandEnvVars(input []byte, strict bool) []byte {
	missingEnvVars := make([]string, 0)
	result := envVarRegex.ReplaceAllFunc(input, func(match []byte) []byte {
		varName := string(match[2 : len(match)-1])
		defaultValue := ""
		if strings.Contains(varName, ":-") {
			parts := strings.SplitN(varName, ":-", 2)
			varName = parts[0]
			defaultValue = parts[1]
		}
		value, isFound := os.LookupEnv(varName)

		// use default value
		if (!isFound || value == "") && defaultValue != "" {
			return []byte(defaultValue)
		}

		if strict {
			if (!isFound || value == "") && defaultValue == "" {
				missingEnvVars = append(missingEnvVars, varName)
				return []byte("")
			}
		} else {
			if !isFound && defaultValue == "" {
				missingEnvVars = append(missingEnvVars, varName)
				return []byte("")
			}
		}
	        return []byte(value)
	})
	if len(missingEnvVars) > 0 {
		panic(fmt.Sprintf("Missing environment variables: %s", strings.Join(missingEnvVars, ", ")))
	}
	return result
}

The strict mode could be a CLI flag with by default is strict and be disabled with a --permissive flag or something

WDYT ?

@bthuillier
Copy link
Contributor Author

I love it ❤️

@bthuillier bthuillier merged commit d391136 into main Oct 7, 2024
4 checks passed
@bthuillier bthuillier deleted the handle-environment-var branch October 7, 2024 16:33
@jheerman
Copy link

jheerman commented Dec 8, 2024

Somehow I slept on this new feature. Amazing and very much appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants