Removal of key-value pair from viper config file

2.6k views Asked by At

Is there a way to remove a key/value pair from the loaded config file?

viper.Set("key", nil)

does not work

3

There are 3 answers

2
GuidoV On BEST ANSWER

Try

delete(viper.Get("path.to.key").(map[string]interface{}), "key")

Example:

[backends]
  [backends.setibe]
    [backends.setibe.servers]
      [backends.setibe.servers.server0]
      url = "http://192.168.1.20:80"
      weight = 1
      [backends.setibe.servers.server1]
      url = "http://192.168.1.21:80"
      weight = 1

To delete "backends.setibe.servers.server1"

delete(viper.Get("backends.setibe.servers").(map[string]interface{}), "server2")
0
Mark On

Building on the comment by @user539810, I have the following:

var rootCmd = &cobra.Command{
    //...
    PersistentPreRunE: writeConfig, //if --writeCfg, write viper config file and exit
}
func writeConfig(cmd *cobra.Command, args []string) error {
    if !writeCfg {
        return nil
    }
    cfg := viper.New()
    for k, v := range viper.AllSettings() {
        switch k {
        case "writecfg", "config", "dryrun":
            //do not propagate these
        default:
            //TODO: also check for zero values and exclude
            cfg.Set(k, v)
        }
    }
    if cfgFile == "" {
        filename := "." + os.Args[0] + ".yaml"
        home, err := os.UserHomeDir()
        cobra.CheckErr(err)
        cfgFile = filepath.Join(home, filename)
    }

    cfg.SetConfigFile(cfgFile)
    var err error
    if _, err = os.Stat(cfgFile); err != nil {
        err = os.WriteFile(cfgFile, nil, 0644)
        cobra.CheckErr(err)
    }
    err = cfg.WriteConfig()
    cobra.CheckErr(err)
    fmt.Println("config written successfully:")
    f, err := os.Open(cfgFile)
    cobra.CheckErr(err)
    defer f.Close()
    _, err = io.Copy(os.Stdout, f)
    cobra.CheckErr(err)
    os.Exit(0)
    return nil //unreachable
}
0
Will Brode On
func Save(ignoredkeys ...string) error {
    file := viper.ConfigFileUsed()
    if len(file) == 0 {
        file = "./default.yml"
    }

    configMap := viper.AllSettings()
    for _, key := range ignoredkeys {
        delete(configMap, key)
    }

    content, err := yaml.Marshal(configMap)
    if err != nil {
        return err
    }

    fs.WriteTextFile(file, string(content))

    return nil
}

This will "flatten" all the config sources into one, then remove the key, then write the file.

Source: https://github.com/spf13/viper/pull/519#issuecomment-858683594