Implement MarshalYAML for relabel.Config so that we do not generate a regex field if it was not provided in the first place

Signed-off-by: Liam Howe <liam.howe@maersk.com>
This commit is contained in:
Liam Howe 2024-04-30 09:58:47 +01:00
parent 34ee8c6078
commit 835dfa7eb6
2 changed files with 48 additions and 0 deletions

View File

@ -111,6 +111,15 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
return c.Validate()
}
// MarshalYAML implements the yaml.Marshaler interface.
func (c Config) MarshalYAML() (interface{}, error) {
// Omit the regex if it is the default regex as it was not provided in the first place.
if c.Regex == DefaultRelabelConfig.Regex {
c.Regex.Regexp = nil
}
return c, nil
}
func (c *Config) Validate() error {
if c.Action == "" {
return fmt.Errorf("relabel action cannot be empty")

View File

@ -851,3 +851,42 @@ func BenchmarkRelabel(b *testing.B) {
})
}
}
func TestConfig_UnmarshalThenMarshal(t *testing.T) {
tests := []struct {
name string
inputYaml string
}{
{
name: "Values provided",
inputYaml: `source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_port]
separator: ;
regex: \\d+
target_label: __meta_kubernetes_pod_container_port_number
replacement: $1
action: replace
`,
},
{
name: "No regex provided",
inputYaml: `source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_port]
separator: ;
target_label: __meta_kubernetes_pod_container_port_number
replacement: $1
action: keepequal
`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
unmarshalled := Config{}
err := yaml.Unmarshal([]byte(test.inputYaml), &unmarshalled)
require.NoError(t, err)
marshalled, err := yaml.Marshal(&unmarshalled)
require.NoError(t, err)
require.Equal(t, test.inputYaml, string(marshalled))
})
}
}