diff --git a/model/relabel/relabel.go b/model/relabel/relabel.go index d29c3d07a..692ed66c1 100644 --- a/model/relabel/relabel.go +++ b/model/relabel/relabel.go @@ -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") diff --git a/model/relabel/relabel_test.go b/model/relabel/relabel_test.go index 6798fb02a..4c5f4d8d1 100644 --- a/model/relabel/relabel_test.go +++ b/model/relabel/relabel_test.go @@ -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)) + }) + } +}