Is there a way to remove a key/value pair from the loaded config file?
viper.Set("key", nil)
does not work
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
}
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
Try
Example:
To delete "backends.setibe.servers.server1"