viper: Question: Cobra required flags don't work with Viper automatic env vars
Hi,
I already mentioned this here: https://github.com/spf13/cobra/pull/502 and @dixudx properly pointed that environment variables were out of the scope of Cobra.
However, we are using AutomaticEnv and we have a CLI that is using flags that can be set with environment variables. We did a hacky function shown in the previously mentioned issue to support required flags, however, after upgrading cobra, pflag et al we are getting an error because the required flags are not being set. That’s not fully true because we were setting them with environment variables.
So, my question is, are we using Cobra and Viper right and this is a bug that should be fixed or are we doing something wrong? In case it’s a bug, could you point me out how to help to fix and where it should be fixed? I suppose that here, in viper.
Thanks!
About this issue
- Original URL
- State: open
- Created 7 years ago
- Reactions: 19
- Comments: 15
Hey all, it’s 2020 now. Do we now have a proper fix for this?
I use the following snippet to use the required flag functionallity with viper environment support:
2022
Lame but I did the following, by forcing the validation through the Config struct. I can use env or flags to define the var and use the validator to mark required options.
I might be missing something obvious here but couldn’t you just mark the flag as not required if it’s set by viper?
This seems way easier than trying to set the values on the flags. Especially in the case where the flag is a slice for example.
Any updates?
@trobert2 I switched to kingpin, which I found simpler and doesn’t have this issue.
I agree with @agonzalezro - the current behaviour is confusing. Flags may be set via environment variables, so required flags should count as “present” if the environment variable is present.
This is difficult to work around cleanly because
Viper.IsSetreturns true even if the flag is only set via a default value.in
root.go:in
subcommand.goIf like me, you expected Viper to be bi-directional with Cobra (setting an Viper environment variable would bind to Cobra and it’s variable) the following might be of some use. It’s based on both simonklb and v-braun’s snippets. It only works for the root commands (not children) as in my case it’s just the global settings I’m likely to provide via environment variables. I’ve left the SetAnnotation in there commented out for reference, as I found the rootCmd.Flags().Set() function did what I wanted.