Kube-rs: Skip serializing None values in Kubeconfig

Created on 7 Aug 2021  路  7Comments  路  Source: kube-rs/kube-rs

I am building a tool for upserting configs in to my kube user's ~/.kube/config file. I read in the file, munge it up, then reserialize the Kubeconfig with serde_yaml but I'm getting a ton of ~ values that really blow up the line count.

For example, it outputs:

    user:
      username: ~
      password: ~
      token: ~
      tokenFile: ~
      client-certificate: ~
      client-certificate-data: ~
      client-key: ~

would we be OK with taking:

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct AuthInfo {
    /// The username for basic authentication to the kubernetes cluster.
    pub username: Option<String>,
    /// The password for basic authentication to the kubernetes cluster.
    pub password: Option<String>,

    /// OMIT
}

and making it something like

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct AuthInfo {
    /// The username for basic authentication to the kubernetes cluster.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
    /// The password for basic authentication to the kubernetes cluster.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// OMIT
}

which would then just skip the field at serialize time

help wanted config

Most helpful comment

One more nit, since I overlooked it. I'm a bit reluctant to derive Default on the kubeconfig structs, because that would imply that the defaults are usable, which generally they are not (in particular Config::try_default is usable).

All 7 comments

Also, it would be handy to make these struct derive Default so it's easy to skip fields

Yeah, I think that's a good idea. More rust native way to deal with these structs. I don't expect this to be a breaking change, and besides, we're not ever posting the kubeconfig structs anywhere. Happy to take a PR for this!

I'm not sure serde is the right choice for editing yaml files meant for human consumption, since it will also drop things like comments and normalize formatting.

I hear you on that, it's not great to lose comments. Formatting I'm OK with. My internal users will appreciate having a tool which makes things "just work". I spend too much time fixing their configs. And the tool will create timestamped backups before writing out the munged up file, undo is possible.

One more nit, since I overlooked it. I'm a bit reluctant to derive Default on the kubeconfig structs, because that would imply that the defaults are usable, which generally they are not (in particular Config::try_default is usable).

OK, that's fair, I can skip the Default bit.

The PR is up.

Was this page helpful?
0 / 5 - 0 ratings