Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info

    Hey guys. I am not sure this is the correct place for this but....

    I am using Viper to manage environment variables for a web app. It works perfectly if I run in normally....

    So the web app reads a couple of values from the environment using AutomaticEnv() and a couple of calls to GetString().

    If I package this up into a docker container viper will not be able to grab the env values it would if running outside the docker container. I know the environment variables are getting set. I can exec into the container see it.

    I tried switching to os.Getenv(). That call is able to pull in the values.

    Any ideas what's broken?

    Rotem Erlich
    I made PR #760 for read only view using separated interface. It also have support for sub config with environment variables support (fix #643)
    Pedro Silva
    @sagikazarmark it just seems to take for ever to get things merged. Maybe the people responsible for the repo should find others to help maintain the repo so it doesn't take 3 months to get PRs merged
    Just NON
    hello i have a problem when i use viper.GetString("") outside main package return nil somebody help

    hello i have a problem when i use viper.GetString("") outside main package return nil somebody help
    `package main

    import (

    func main() {
    //Config handling
    err = viper.ReadInConfig()

    `package Model

    import ("github.com/spf13/viper"

    var sqlhost = viper.GetString("db.host")

    func foo() {
    } `

    Just NON
    someone help
    Márk Sági-Kazár
    @ivybridge-3c33 I answered to your issue. TL;DR since you read in the config in main and the variable is evaluated before main is executed, this won't work. You have to fetch data from Viper after you read in the config file.
    Just NON
    Thank you
    Tobias Frischholz
    Hello guys,
    Maybe I found a bug, but I'am not sure...

    I just want to write a config with mapstructure annotations on it...

        type Person struct {
            Age    int    `mapstructure:"a"`
            Gender string `mapstructure:"g"`
            Family string `mapstructure:"f"`
            Name   string `mapstructure:"n"`

    The write method to write a config file:

    import (
    func WriteConfig(configInstance interface{}, filePath string,) error {
        v := viper.New()
        b, err := yaml.Marshal(&configInstance)
        if err != nil {
            return err
        defaultConfig := bytes.NewReader(b)
        if err := v.MergeConfig(defaultConfig); err != nil {
            return err
        return v.WriteConfigAs(filePath)

    The result for yaml or json is always:

      "age": 48,
      "family": "Family-Name",
      "gender": "m",
      "name": "Name"


    age: 48
    family: Family-Name
    gender: m
    name: Name

    The mapstructure annotation are not respected..
    Do I make something wrong here???

    btw. I am using the latest version from viper 1.6.1
    Márk Sági-Kazár
    yaml.Marshal won't respect mapstructure tag. Either use yaml tag in mapstructure as well (you can do that by configuring mapstructure), or first marshal your config to a map using mapstructure and then marshal that to yaml.
    What does someone have to do in order to have Default Flag -> Env -> CliFag work with cobra/ viper?
    My Cobra Flags never get bound to viper.GetString(configKeyClientKeyPath) ever after running
            flags.String(longOpt, defaultValue, description)
            config.ViperBindPFlag(key, flags.Lookup(longOpt))
            viper.SetDefault(key, defaultValue)
    Hi guys, is there an any method to check that all params in config structure was set in .yaml file ?
    Abdelkader Bouadjadja
    Hello folks ! I have config file and structs that look like : https://pastebin.com/dMLNS7XN. I'm usingWithEnvPrefix("MYPREFIX") and WithAutomaticEnv(true) when loading the config. I absolutely need the env vars to have the priority over by config, but i don't know how my env var should be named, as my config is not flag, but contain array and nested key/vals.
    For a flat config, i know that if my config os named host, my env var should be named MYPREFIX_HOST
    But for such nested array config, i don't know. Thanks a lot.
    Márk Sági-Kazár
    You don't actually have arrays in your example config though.
    Just maps
    You can set a key name replacer and replace dots with underscores
    Then you can use MYPREFIX_LEVEL1_LEVEL2
    Abdelkader Bouadjadja
    Not arrays sorry, but i meant nested configs with multiple levels.
    Excellent, thanks a lot.
    Hi .. I have recently started working on cobra, can someone help me to know how to read a custom yml from cobra command line using viper.
    How do you guys share one viper instance to the multiple packages?
    Darragh Bailey
    When using viper.AutomaticEnv() is there a way to get env variable to display in the help along with each option automatically?
    Darragh Bailey
    I've used the following code to handle this, but seems like something that would be nice to enable automatically:
        RootCmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
            envKey := strings.ToUpper(replacer.Replace(f.Name))
            f.Usage = fmt.Sprintf("%s [env: %s]", f.Usage, envKey)
    Luke Hinds
    Which viper.Get method should I use to retrieve JSON from a YAML config?
    is it supported to use relative path in viper.AddConfigPath() ?
    Dan Rollo
    Hi. I found myself in a rabbit hole, and put together a PR that I hope will help others avoid the issue. spf13/viper#949
    Is this the right forum to post about this? Thanks for a great tool BTW!
    Juan Ignacio Borda

    Hi Vipers!!!
    Im reading an INI file and I want to extract the sections names

    [section 1]

    is this possible with viper!?

    Juan Ignacio Borda
    I need to get a map like ["section1","section2" ....]

    Which viper.Get method should I use to retrieve JSON from a YAML config?

    did you tried with viper.GetString("path.to.your.json") ?
    then parse with viper again

    Juan Ignacio Borda

    Hi Vipers!!!
    Im reading an INI file and I want to extract the sections names

    [section 1]

    is this possible with viper!?

    dont worry i've already done this with a regular expresion and a file read

    Marques Johansson
    I asked a similar question in Slack, and @sagikazarmark created an FAQ tracking issue: spf13/viper#969
    Cong Luwen
    Hi guys, the signature of the MergeConfigMap will return an "error", but when I'm looked into the source code, I found that this method just return a nil error. Is there a way to make it return an error when the merge procedure is wrong?
    Márk Sági-Kazár
    Hey folks!
    Viper is heading towards v2 and needs your input. Please give us your thoughts and feedback: https://forms.gle/f96kZQuBcuxW2p5E8
    Márk Sági-Kazár
    Christian Francia

    Hey guys, really small question here but in the README of viper, I don't see any documentation as to how to write to the the config file. I understand that there is the viper.WriteConfig() but what I am wishing to do is something like:

    viper.WriteConfig("key.key", "val")

    is there a semantic approach to staging changes to the config file before viper.WriteConfig() ?

    John Millner
    Hey all - i created this issue before noticing this IRC - got a small trouble shooting that would be great to have some help on - trying to get the envVar overrides to be in all underscores rather than periods - am i missing something obvious? spf13/viper#1029

    Hello all, Quick question. When invoking


    is there an automatic conversion from string to bool when the string in the yaml file is set to "no"?
    I'm seeing this behavior, and I'm not sure if that is configurable.

    Omer Hamerman

    Hello friends! I'm working with environment variables to set configurations in place and it seems that viper.IsSet() is not picking them up, my config is:

      someaccount: "one"

    When I set this structure from and environment variable like so: ACCOUNTS_SOMEACCOUNT=one (without reconfiguring this from the config.yaml file), while viper.GetString(accounts.someaccount) works as expected, viper.IsSet('accounts') does not. When setting the structure through yaml as the example above everything works as expected.
    Am I missing something? Is this a bug or intentional behavior? Any tips on how to overcome this?

    Mark Petrovic
    What is the recommended or reasonable pattern to use for a viper.GetX(key) when the value at rest in the config file is, say, a hex string, but you really want the Get to return the hex-decoded byte slice? Maybe this is an antipattern, but thought I'd ask.
    1 reply
    Muhammet Ali AKBAY
    Hi people, is it possible to use environment variables in yaml configuration file eg: "${VARIABLE}" ?
    hello there! i think i'm missing some documentation on how to declare noop flags (like --version, which displays the version when set). Do I need to use this kind of flag as a boolean flag or is there another method? Thanks in advance!
    nvm, i found it 😅

    How do i parse the following yaml with viper ?

      name: pg-instance
      id: test-db
      storageGB: 5
      dbInstanceClass: db.t2.small
      multiAZ: true
      publiclyAccessible: false
      engineVersion: "9.6"
      storageType: gp2
      region: eu-central-1
         jacket: leather
         trousers: denim

    I am parsing as follows

    // Configurations exported
    type Configurations struct {
            DBInstance                                DBInstanceConfigurations
    type DBInstanceConfigurations struct {
            Name                string
            Id                  string
            StorageGB               string
            DBInstanceClass     string
            EngineVersion       string
            StorageType         string
            Region                          string
            MultiAZ                     bool
            PubliclyAccessible  bool
            whiteList           string `mapstructure:"path_map"`
    func main() {
            // Set the path to look for the configurations file
            // Enable VIPER to read Environment Variables
            var configuration Configurations
            if err := viper.ReadInConfig(); err != nil {
                    fmt.Printf("Error reading config file, %s", err)
            err := viper.Unmarshal(&configuration)
            if err != nil {
                    fmt.Printf("Unable to decode into struct, %v", err)
            fmt.Println("DBInstanceName is\t", configuration.DBInstance.Name)
            fmt.Println("DBInstanceID is\t", configuration.DBInstance.Id)
            fmt.Println("Storage is\t", configuration.DBInstance.StorageGB)
            fmt.Println("DBInstanceClass is\t", configuration.DBInstance.DBInstanceClass)
            fmt.Println("EngineVersion is\t", configuration.DBInstance.EngineVersion)
            fmt.Println("MultiAZ is\t", configuration.DBInstance.MultiAZ)
            fmt.Println("PubliclyAccessible is\t", configuration.DBInstance.PubliclyAccessible)
            fmt.Println("StorageType is\t", configuration.DBInstance.StorageType)
            fmt.Println("Region is\t", configuration.DBInstance.Region)
            fmt.Println("Whitelist is\t", configuration.DBInstance.whiteList)

    I would like to parse that whiteList IPs for looping and also the clothing key with the struct way ?

    Any suggestions ?