Skip to content

Does viper require a config file in order to use ENV variables? #584

@jsirianni

Description

@jsirianni

Hi, I have an application that can use both a config file and env variable.

My initConfig() method looks like this:

if err := viper.ReadInConfig(); err == nil {
	fmt.Println("Using config file:", viper.ConfigFileUsed())
} else {
	fmt.Println("Config file not found:", cfgFile)
}

viper.SetEnvPrefix("GC")
viper.AutomaticEnv()

err := viper.Unmarshal(&config)
if err != nil {
	fmt.Println(err.Error())
	os.Exit(1)
}

unmarshal drops the config into a struct, and it works well.

I am facing an issue where if my config file does not exist (or is empty), viper seems to completely ignore any environment variables. I have verified that viper can see the env variables, by printing them to standard out. My workaround is to deploy the config file, with all the correct keys but no values. Viper then correctly overrides the config file with my environment variables.

Am I wrong to assume that Viper should be able to use environment variables when no config file is found?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions