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

run: Add the possibility to load an env file #3278

Merged
merged 6 commits into from
May 15, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions cmd/commandfuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,19 @@ func cmdRun(fl Flags) (int, error) {
runCmdConfigFlag := fl.String("config")
runCmdConfigAdapterFlag := fl.String("adapter")
runCmdResumeFlag := fl.Bool("resume")
runCmdLoadEnvfileFlag := fl.String("envfile")
runCmdPrintEnvFlag := fl.Bool("environ")
runCmdWatchFlag := fl.Bool("watch")
runCmdPingbackFlag := fl.String("pingback")

// load all additional envs as soon as possible
if runCmdLoadEnvfileFlag != "" {
if err := loadEnvFromFile(runCmdLoadEnvfileFlag); err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("loading additional environment variables: %v", err)
}
}

// if we are supposed to print the environment, do that first
if runCmdPrintEnvFlag {
printEnvironment()
Expand Down
6 changes: 5 additions & 1 deletion cmd/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ using 'caddy run' instead to keep it in the foreground.`,
RegisterCommand(Command{
Name: "run",
Func: cmdRun,
Usage: "[--config <path> [--adapter <name>]] [--environ] [--watch]",
Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--environ] [--watch]",
Short: `Starts the Caddy process and blocks indefinitely`,
Long: `
Starts the Caddy process, optionally bootstrapped with an initial config file,
Expand All @@ -115,6 +115,9 @@ As a special case, if the current working directory has a file called
that file will be loaded and used to configure Caddy, even without any command
line flags.

If --envfile is specified, an environment file with environment variables in
the KEY=VALUE format will be loaded into the Caddy process.

If --environ is specified, the environment as seen by the Caddy process will
be printed before starting. This is the same as the environ command but does
not quit after printing, and can be useful for troubleshooting.
Expand All @@ -129,6 +132,7 @@ development environment.`,
fs := flag.NewFlagSet("run", flag.ExitOnError)
fs.String("config", "", "Configuration file")
fs.String("adapter", "", "Name of config adapter to apply")
fs.String("envfile", "", "Environment file to load")
fs.Bool("environ", false, "Print environment")
fs.Bool("resume", false, "Use saved config, if any (and prefer over --config file)")
fs.Bool("watch", false, "Watch config file for changes and reload it automatically")
Expand Down
68 changes: 68 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package caddycmd

import (
"bufio"
"bytes"
"flag"
"fmt"
Expand Down Expand Up @@ -339,6 +340,73 @@ func flagHelp(fs *flag.FlagSet) string {
return buf.String()
}

func loadEnvFromFile(envFile string) error {
file, err := os.Open(envFile)
if err != nil {
return fmt.Errorf("reading environment file: %v", err)
}
defer file.Close()

envMap, err := parseEnvFile(file)
if err != nil {
return fmt.Errorf("parsing environment file: %v", err)
}

for k, v := range envMap {
if err := os.Setenv(k, v); err != nil {
return fmt.Errorf("setting environment variables: %v", err)
}
}

return nil
}

func parseEnvFile(envInput io.Reader) (map[string]string, error) {
envMap := make(map[string]string)

scanner := bufio.NewScanner(envInput)
var line string
lineNumber := 0

for scanner.Scan() {
line = strings.TrimSpace(scanner.Text())
lineNumber++

// skip lines starting with comment
if strings.HasPrefix(line, "#") {
continue
}

// skip empty line
if len(line) == 0 {
continue
}

fields := strings.SplitN(line, "=", 2)
if len(fields) != 2 {
return nil, fmt.Errorf("Can't parse line %d; line should be in KEY=VALUE format", lineNumber)
elcore marked this conversation as resolved.
Show resolved Hide resolved
}

if strings.Contains(fields[0], " ") {
return nil, fmt.Errorf("Can't parse line %d; KEY contains whitespace", lineNumber)
elcore marked this conversation as resolved.
Show resolved Hide resolved
}

key := fields[0]
val := fields[1]

if key == "" {
return nil, fmt.Errorf("Can't parse line %d; KEY can't be empty string", lineNumber)
elcore marked this conversation as resolved.
Show resolved Hide resolved
}
envMap[key] = val
}

if err := scanner.Err(); err != nil {
return nil, err
}

return envMap, nil
}

func printEnvironment() {
fmt.Printf("caddy.HomeDir=%s\n", caddy.HomeDir())
fmt.Printf("caddy.AppDataDir=%s\n", caddy.AppDataDir())
Expand Down