Envplate

repository·master·Indexed 43 days ago

https://github.com/kreuzwerker/envplate

A tool for performing trivial templating in configuration files using environment variables. It replaces variable references like ${key} or ${key:-default} with values from the environment, modifying files inline or outputting to stdout. Designed for containerized applications, it can be used as a Docker ENTRYPOINT to prepare configuration files before executing a main process.

Tokens
2.1K
Snippets
8
Records
8
Agent score
56%

What's inside Envplate

  1. Use Envplate for trivial configuration templating

    master

    Envplate (ep) is a tool for performing trivial templating in configuration files using environment variables. It parses files matching provided glob patterns and replaces variable references with values from the environment or provided default values. The replacement happens inline, meaning the original files are modified.

    Variable Syntax:

    • ${key}: Replaces with the value of the environment variable key.
    • ${key:-default value}: Replaces with the value of key, or uses default value if the variable is not set.

    Note: If the supplied glob pattern does not resolve to at least one file, ep will return an error.

    # No specific code example provided for the core concept, but syntax is:
    ${key}
    ${key:-default value}
  2. Escape environment variable sequences in config files

    master

    If your configuration files need to contain literal ${key} sequences that should not be replaced by ep, you can use backslash escaping:

    • Use an odd number of leading backslashes to escape the sequence (e.g., \${KEY}).
    • Use an even number of leading backslashes to ensure the sequence is parsed (e.g., \\${KEY}).

    Essentially, a leading backslash \ escapes the following character.

    # Example of escaping behavior
    # Input:
    Escaped1=\${FOO_DATABASE}
    NotEscaped1=\\${FOO_DATABASE}
    
    # Output after 'ep':
    Escaped1=${FOO_DATABASE}
    NotEscaped1=\${FOO_DATABASE}
  3. Install Envplate in a Dockerfile

    master

    You can download and install ep directly into your Docker image using GitHub releases. This is useful for applications that require configuration files to be populated from environment variables at runtime.

    Installation pattern:

    1. Use wget to download the appropriate tarball for your architecture.
    2. Extract the tarball.
    3. Move the envplate binary to /usr/local/bin/ep.
    4. Set permissions with chmod +x.

    Runtime pattern: Use ep as the CMD or ENTRYPOINT to parse your configuration files before executing your main application process.

    # Installation
    RUN wget -q https://github.com/kreuzwerker/envplate/releases/download/v1.0.2/envplate_1.0.2_$(uname -s)_$(uname -m).tar.gz -O - | tar xz && mv envplate /usr/local/bin/ep && chmod +x /usr/local/bin/ep
    
    # Execution
    CMD [ "/usr/local/bin/ep", "-v", "/etc/nginx/nginx.conf", "--", "/usr/sbin/nginx", "-c", "/etc/nginx/nginx.conf" ]
  4. Environment variable reference syntax and escaping

    master

    Envplate uses a specific syntax for identifying environment variables within files. It supports default values and escaping mechanisms.

    Reference Syntax

    • ${VAR}: Expands to the value of the environment variable VAR.
    • ${VAR:-default}: Expands to the value of VAR. If VAR is not defined, it expands to default.

    Escaping

    To prevent a sequence from being expanded, you can use backslashes. An odd number of backslashes before the $ symbol acts as an escape sequence.

    • \${VAR}: The sequence is treated as a literal string ${VAR} rather than an environment variable reference.

    Strict Mode Behavior

    • When Handler.Strict is true: If a reference like ${VAR} is found but VAR is not set in the environment, an error is returned.
    • When Handler.Strict is false: If ${VAR} is not set, the expansion fails (unless a default is provided via :-). Note that the current implementation logs a debug message when using a default value in non-strict mode.
    // Example file content before envplate:
    // API_URL=${API_ENDPOINT:-http://localhost:8080}
    // SECRET=\${STRICT_VAR}
    
    // Example file content after envplate (assuming API_ENDPOINT=https://api.prod.com):
    // API_URL=https://api.prod.com
    // SECRET=${STRICT_VAR}
  5. Configure Envplate CLI options

    master

    When running ep, you can use the following flags to control its behavior:

    • -b (backup): Creates backup copies of the files being changed, appending a .bak extension.
    • -d (dry-run): Instead of modifying files inline, outputs the processed content to stdout.
    • -s (strict): Refuses to use default values; if a variable cannot be resolved via the environment, it will fail.
    • -v (verbose): Enables verbose output about the operations being performed.
    • -c <charset> (charset): Specifies a custom charset to use for variable replacement (e.g., iso8859-1).

    To execute another command after parsing configuration files, use -- followed by the path to the binary and its arguments.

    # Example: Parse configs and then execute nginx
    /usr/local/bin/ep -v *.conf -- /usr/sbin/nginx -c /etc/nginx.conf
  6. Use the Handler to apply environment variable templates to files

    master

    The envplate.Handler struct is the primary entry point for processing files. It scans files matching provided glob patterns, identifies environment variable references in the format ${VAR} or ${VAR:-default}, and replaces them with their actual values from the environment.

    Configuration Options

    FieldTypeDescription
    BackupboolIf true, creates a backup of the file before overwriting it with the expanded content.
    DryRunboolIf true, performs the expansion in memory and logs the result without modifying any files.
    StrictboolIf true, an error is returned if an environment variable is undeclared and no default value is provided via the ${VAR:-default} syntax. If false, the default value is used.
    CharsetstringSpecifies a character set to which the expanded content should be converted (e.g., using go-charset). If empty, no conversion is performed.

    Applying Templates

    Call Apply(globs []string) with a slice of file patterns (e.g., []string{"config/*.yaml"}). The method returns an error if no files match the patterns or if parsing/writing fails.

    package main
    
    import "github.com/kreuzwerker/kreuzwerker/envplate"
    
    func main() {
    	h := &envplate.Handler{
    		Backup: true,
    		Strict: false,
    		DryRun: false,
    	}
    
    	// Apply templates to all .env files in the config directory
    	err := h.Apply("[]string{\"config/*.env\"}")
    	if err != nil {
    		panic(err)
    	}
    }
  7. Configure envplate CLI flags

    master

    The following flags are available for the ep command:

    FlagShorthandTypeDescription
    --backup-bboolCreate a backup file when using inline mode
    --dry-run-dboolDry-run - output templates to stdout instead of inline replacement
    --strict-sboolStrict-mode - fail when falling back on defaults
    --verbose-vboolVerbose logging
    --charset-cstringOutput charset
    # Example of using dry-run and strict mode
    ep --dry-run --strict config.yaml
    
    # Example of creating backups
    ep -b config.yaml
  8. Use the envplate CLI

    master

    The ep command provides trivial templating for configuration files using environment keys. It can perform inline replacements in files or output processed templates to stdout. After processing, it can optionally execute an additional command using the processed environment.

    # Example usage (assuming ep is in your PATH)
    ep [flags] [files...]